commit f3e5078c578f3fdf24d2a2409628ad9ef500a075 Author: 彭勇平 Date: Tue Feb 25 16:24:22 2025 +0800 初始提交 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb06c9b --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/.idea/ +/logs/ +/target/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..2288fbe --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +**项目说明** +- sqx-fast是一个轻量级的,前后端分离的Java快速开发平台,能快速开发项目并交付 +- 支持MySQL、PostgreSQL等主流数据库 +
+ + +**具有如下特点** +- 友好的代码结构及注释,便于阅读及二次开发 +- 实现前后端分离,通过token进行数据交互,前端再也不用关注后端技术 +- 灵活的权限控制,可控制到页面或按钮,满足绝大部分的权限需求 +- 页面交互使用Vue2.x,极大的提高了开发效率 +- 引入API模板,根据token作为登录令牌,极大的方便了APP接口开发 +- 引入swagger文档支持,方便编写API接口文档 +
+ + +**技术选型:** +- 核心框架:Spring Boot 2.6 +- 安全框架:Apache Shiro 1.4 +- 视图框架:Spring MVC 5.0 +- 持久层框架:MyBatis 3.3 +- 数据库连接池:Druid 1.0 +- 日志管理:SLF4J 1.7、Log4j +- 页面交互:Vue2.x +
+ + + **后端部署** +- 通过git下载源码 +- idea、eclipse需安装lombok插件,不然会提示找不到entity的get set方法 +- 创建数据库sqx_fast,数据库编码为UTF-8 +- 执行db/mysql.sql文件,初始化数据 +- 修改application-dev.yml,更新MySQL账号和密码 +- Eclipse、IDEA运行sqxApplication.java,则可启动项目 +- Swagger文档路径:http://localhost:8964/sqx_fast/swagger/index.html +- Swagger注解路径:http://localhost:8964/sqx_fast/swagger-ui.html + + +
diff --git a/db/songshui.sql b/db/songshui.sql new file mode 100644 index 0000000..8e18146 --- /dev/null +++ b/db/songshui.sql @@ -0,0 +1,2049 @@ +/* + Navicat Premium Data Transfer + + Source Server : 服务器数据库 + Source Server Type : MySQL + Source Server Version : 50734 + Source Host : 42.193.11.150:3306 + Source Schema : z3 + + Target Server Type : MySQL + Target Server Version : 50734 + File Encoding : 65001 + + Date: 02/12/2024 18:57:30 +*/ + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- Table structure for address +-- ---------------------------- +DROP TABLE IF EXISTS `address`; +CREATE TABLE `address` ( + `address_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '地址id', + `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名', + `phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话', + `province` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '省', + `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '市', + `district` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '区', + `details_address` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '详细地址', + `is_default` int(11) NULL DEFAULT NULL COMMENT '是否是默认地址 0 否 1是', + `create_time` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '时间', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `longitude` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '经度', + `latitude` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '纬度', + `is_update` int(1) NULL DEFAULT 0 COMMENT '0未修改过 1已修改过', + PRIMARY KEY (`address_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 208 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of address +-- ---------------------------- + +-- ---------------------------- +-- Table structure for app +-- ---------------------------- +DROP TABLE IF EXISTS `app`; +CREATE TABLE `app` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'app升级', + `android_wgt_url` varchar(600) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '安卓地址', + `create_at` varchar(600) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '创建时间', + `des` varchar(600) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '描述', + `ios_version` varchar(255) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '苹果版本', + `ios_wgt_url` varchar(600) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '苹果地址', + `method` varchar(600) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '是否强制升级', + `version` varchar(600) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '安卓版本', + `wgt_url` varchar(600) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '通用更新地址', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = big5 COLLATE = big5_chinese_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of app +-- ---------------------------- +INSERT INTO `app` VALUES (5, 'https://www.pgyer.com/hb2v', '2020-07-20 18:35:00', '升级', NULL, '', 'false', '1.0', 'https://www.pgyer.com/hb2v'); + +-- ---------------------------- +-- Table structure for apply +-- ---------------------------- +DROP TABLE IF EXISTS `apply`; +CREATE TABLE `apply` ( + `apply_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '申请id', + `apply_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名', + `apply_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '电话', + `apply_age` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '年龄', + `apply_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '内容', + `classify` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类 1推广员 2代理商', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `status` int(11) NULL DEFAULT NULL COMMENT '状态 1待审核 2通过 3拒绝', + `audit_content` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '审核内容', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`apply_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 42 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of apply +-- ---------------------------- + +-- ---------------------------- +-- Table structure for banner +-- ---------------------------- +DROP TABLE IF EXISTS `banner`; +CREATE TABLE `banner` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'bannerid', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '名称', + `image_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图片地址', + `state` int(2) NULL DEFAULT NULL COMMENT '状态1正常2隐藏', + `classify` int(2) NULL DEFAULT NULL COMMENT '分类1banner图2金刚区分类', + `url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '跳转地址 ', + `sort` int(4) NULL DEFAULT NULL COMMENT '顺序', + `describes` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '描述', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 31 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of banner +-- ---------------------------- +INSERT INTO `banner` VALUES (3, '2023-03-14 19:48:41', '轮播', 'https://songshui.xianmaxiong.com/file/uploadPath/2023/03/14/d533c9b5de68d51aa5ce4364d3d5a86f.png', 1, 1, '/my/youhuiquan/index', 3, '轮播'); +INSERT INTO `banner` VALUES (19, '2022-11-25 13:29:08', '邀请背景图', 'https://songshui.xianmaxiong.com/file/uploadPath/2022/11/25/70a926741db179bbfdc33301fe881757.png', 1, 5, 'https://peiwan.xianmxkj.com', NULL, '邀请背景图'); +INSERT INTO `banner` VALUES (29, '2023-06-25 11:54:16', '桶装水', 'https://songshui.xianmaxiong.com/file/uploadPath/2023/06/25/96cc8ec31b1d36e9745d549e1e560dcd.png', 1, 2, '/my/order/orderDet', NULL, '桶装水'); +INSERT INTO `banner` VALUES (30, '2024-06-25 14:08:49', '水票购买', 'https://songshui.xianmaxiong.com/file/uploadPath/2023/11/27/8c10680dd9e1920c1390e133cc184c3e.png', 1, 2, '/my/shuipiao/index?index=0', NULL, NULL); + +-- ---------------------------- +-- Table structure for car +-- ---------------------------- +DROP TABLE IF EXISTS `car`; +CREATE TABLE `car` ( + `car_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '车辆id', + `car_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '车辆型号', + `car_classify` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '车辆类型', + `car_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '车辆号码', + `car_color` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '车辆颜色', + `car_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '车主名称', + `car_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '车主电话', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `car_logo` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '车辆logo', + PRIMARY KEY (`car_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of car +-- ---------------------------- + +-- ---------------------------- +-- Table structure for cash_out +-- ---------------------------- +DROP TABLE IF EXISTS `cash_out`; +CREATE TABLE `cash_out` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '申请提现id', + `create_at` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '申请时间', + `is_out` int(2) NULL DEFAULT NULL COMMENT '是否转账', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '提现金额', + `out_at` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '转账时间', + `relation_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '会员编号', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `zhifubao` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付宝账号', + `zhifubao_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付宝姓名', + `order_number` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单编号', + `state` int(11) NULL DEFAULT NULL COMMENT '状态 0待转账 1成功 -1退款', + `refund` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '退款原因', + `classify` int(11) NULL DEFAULT NULL COMMENT '提现方式 1支付宝 2微信小程序 3微信公众号', + `rate` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '利息', + `wx_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '微信提现二维码', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 118 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of cash_out +-- ---------------------------- + +-- ---------------------------- +-- Table structure for chat_content +-- ---------------------------- +DROP TABLE IF EXISTS `chat_content`; +CREATE TABLE `chat_content` ( + `chat_content_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '聊天内容id', + `chat_conversation_id` int(11) NULL DEFAULT NULL COMMENT '聊天会话id', + `content` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '内容', + `message_type` int(11) NULL DEFAULT NULL COMMENT '类型 1文字 2图片 3语音', + `width` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图片宽度', + `height` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图片高度', + `user_id` int(11) NULL DEFAULT NULL COMMENT '发送用户id', + `status` int(11) NULL DEFAULT NULL COMMENT '0未读 1已读', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发送时间', + PRIMARY KEY (`chat_content_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 614 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of chat_content +-- ---------------------------- + +-- ---------------------------- +-- Table structure for chat_conversation +-- ---------------------------- +DROP TABLE IF EXISTS `chat_conversation`; +CREATE TABLE `chat_conversation` ( + `chat_conversation_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '聊天会话id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '发送用户id', + `focused_user_id` int(11) NULL DEFAULT NULL COMMENT '接受用户id', + `status` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '状态', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新时间', + `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注', + `is_wx_msg` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否推送微信消息1是', + `is_send_msg` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否推送短信消息1是', + PRIMARY KEY (`chat_conversation_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 184 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of chat_conversation +-- ---------------------------- + +-- ---------------------------- +-- Table structure for chats +-- ---------------------------- +DROP TABLE IF EXISTS `chats`; +CREATE TABLE `chats` ( + `chat_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '会话id', + `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `user_count` int(20) NULL DEFAULT 0 COMMENT '用户未读条数', + `user_count2` int(20) NULL DEFAULT 0 COMMENT '好友未读条数', + `user_head` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户头像', + `user_head2` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '好友头像', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `user_id2` bigint(20) NULL DEFAULT NULL COMMENT '好友id', + `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户昵称', + `user_name2` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '好友昵称', + `store_count` int(11) NULL DEFAULT 0 COMMENT '后台未读条数', + `store_head` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '后台头像', + `store_id` bigint(20) NULL DEFAULT NULL COMMENT '总后台id(总后台传0', + `store_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商户昵称', + PRIMARY KEY (`chat_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 2442 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '聊天会话' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of chats +-- ---------------------------- + +-- ---------------------------- +-- Table structure for chats_content +-- ---------------------------- +DROP TABLE IF EXISTS `chats_content`; +CREATE TABLE `chats_content` ( + `chat_content_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '会话内容id', + `chat_id` bigint(20) NULL DEFAULT NULL COMMENT '会话Id', + `content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '聊天内容', + `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `send_type` bigint(20) NULL DEFAULT NULL COMMENT '消息来源(1用户消息 2好友消息)', + `status` int(11) NULL DEFAULT 1 COMMENT '是否已读(1未读 2已读)', + `type` int(1) NULL DEFAULT NULL COMMENT '类型(1文字 2图片 3链接)', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `user_id2` bigint(20) NULL DEFAULT NULL COMMENT '好友id', + `store_id` bigint(20) NULL DEFAULT NULL COMMENT '后台id(总后台传0)', + PRIMARY KEY (`chat_content_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1184 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '聊天会话内容' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of chats_content +-- ---------------------------- + +-- ---------------------------- +-- Table structure for city_agency +-- ---------------------------- +DROP TABLE IF EXISTS `city_agency`; +CREATE TABLE `city_agency` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '代理id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '意向代理城市', + `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名', + `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '电话', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `classify` int(11) NULL DEFAULT NULL COMMENT '类型', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of city_agency +-- ---------------------------- + +-- ---------------------------- +-- Table structure for collect_order_taking +-- ---------------------------- +DROP TABLE IF EXISTS `collect_order_taking`; +CREATE TABLE `collect_order_taking` ( + `collect_order_taking_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '收藏id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `order_taking_id` int(11) NULL DEFAULT NULL COMMENT '服务id', + `create_time` varbinary(64) NULL DEFAULT NULL COMMENT '时间', + PRIMARY KEY (`collect_order_taking_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 58 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of collect_order_taking +-- ---------------------------- + +-- ---------------------------- +-- Table structure for comment_fabulous +-- ---------------------------- +DROP TABLE IF EXISTS `comment_fabulous`; +CREATE TABLE `comment_fabulous` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '点赞id', + `taking_comment_id` bigint(20) NULL DEFAULT NULL COMMENT '接单评论id', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of comment_fabulous +-- ---------------------------- + +-- ---------------------------- +-- Table structure for common_info +-- ---------------------------- +DROP TABLE IF EXISTS `common_info`; +CREATE TABLE `common_info` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '配置文件id', + `create_at` varchar(255) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '创建时间', + `max` varchar(255) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '暂未使用', + `min` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '配置文件名称', + `type` int(11) NULL DEFAULT NULL COMMENT '类型', + `value` text CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL COMMENT '值', + `condition_from` varchar(255) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '分类', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 417 CHARACTER SET = big5 COLLATE = big5_chinese_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of common_info +-- ---------------------------- +INSERT INTO `common_info` VALUES (1, '2022-03-28 11:25:23', NULL, '客服二维码', 1, 'https://taobao.xianmxkj.com/custom.jpg', 'xitongs'); +INSERT INTO `common_info` VALUES (2, '2020-02-21 21:17:17', NULL, '公众号二维码', 2, 'https://taobao.xianmxkj.com/erweima.jpg', 'weixins'); +INSERT INTO `common_info` VALUES (3, '2020-02-21 21:17:17', NULL, '邀请码是否必填(是:必填 否:选填)', 3, '否', 'kaiguan'); +INSERT INTO `common_info` VALUES (5, '2020-07-09 17:59:45', NULL, '微信公众号APPID ', 5, '', 'weixin'); +INSERT INTO `common_info` VALUES (6, '2021-03-15 21:16:30', NULL, '短信签名', 6, '省钱兄', 'duanxin'); +INSERT INTO `common_info` VALUES (16, '2020-02-25 20:43:38', NULL, '微信公众号秘钥 ', 21, '', 'weixin'); +INSERT INTO `common_info` VALUES (17, '2020-02-25 20:43:59', NULL, '公众号Token', 16, 'maxd', 'weixin'); +INSERT INTO `common_info` VALUES (18, '2020-02-25 20:44:15', NULL, '公众号EncodingAESKey ', 17, 'O8T7NubxpjOd7uNoVV7g01PDpPGUWpiGrLWWIFyaaCH', 'weixin'); +INSERT INTO `common_info` VALUES (20, '2022-12-26 10:47:12', NULL, '后台管理平台域名配置 ', 20, 'https://songshuiadmin.xianmaxiong.com', 'xitong'); +INSERT INTO `common_info` VALUES (21, '2022-12-26 10:46:58', NULL, 'h5服务域名配置 ', 19, 'https://songshui.xianmaxiong.com', 'xitong'); +INSERT INTO `common_info` VALUES (22, '2022-03-28 11:22:48', NULL, '短信服务商(1 腾讯云 2 阿里云 3短信宝)', 79, '3', 'duanxin'); +INSERT INTO `common_info` VALUES (23, '2022-03-28 11:22:29', NULL, '后台服务名称 ', 12, '省钱兄', 'xitong'); +INSERT INTO `common_info` VALUES (24, '2022-11-26 11:26:50', NULL, '师傅端域名配置', 24, 'https://peizhensf.xianmaxiong.com', NULL); +INSERT INTO `common_info` VALUES (27, '2020-03-09 20:46:10', NULL, '通用APP下载地址 ', 25, 'https://pw.xianmxkj.com/pw.apk', 'xitong'); +INSERT INTO `common_info` VALUES (33, '2021-03-15 21:19:27', NULL, '腾讯云短信clientId ', 31, '', 'duanxin'); +INSERT INTO `common_info` VALUES (34, '2020-03-28 00:47', NULL, '腾讯云短信clientSecret ', 32, '', 'duanxin'); +INSERT INTO `common_info` VALUES (47, '2022-11-07 17:03:26', NULL, '微信小程序APPID', 45, '', 'weixin'); +INSERT INTO `common_info` VALUES (48, '2022-11-07 17:03:31', NULL, '微信小程序秘钥', 46, '', 'weixin'); +INSERT INTO `common_info` VALUES (51, '2020-03-29 00:21', NULL, '分享安卓下载地址', 49, 'https://www.pgyer.com/xiansqx', 'xitongs'); +INSERT INTO `common_info` VALUES (52, '2020-03-29 00:21', NULL, '分享苹果下载地址', 50, 'https://www.pgyer.com/c11o', 'xitongs'); +INSERT INTO `common_info` VALUES (58, '2020-03-29 00:21', NULL, '开启微信登录', 53, '是', 'weixins'); +INSERT INTO `common_info` VALUES (69, '2020-06-04 16:34', NULL, 'APP消息推送PushAppKey', 60, 'uW0zDpss4H9YBco3dgOUM8', 'push'); +INSERT INTO `common_info` VALUES (70, '2020-06-04 16:34', NULL, 'APP消息推送PushAppId', 61, 'ciYgxyP9Xb95ig2yowsIF6', 'push'); +INSERT INTO `common_info` VALUES (71, '2020-06-04 16:34', NULL, 'APP消息推送PushMasterSecret', 62, '7mjw0QAlTD8s7TJWfAuCTA', 'push'); +INSERT INTO `common_info` VALUES (72, '2020-06-04 16:34', NULL, '企业支付宝APPID', 63, '', 'zhifubao'); +INSERT INTO `common_info` VALUES (73, '2020-06-04 16:34', NULL, '企业支付宝公钥', 64, '', 'zhifubao'); +INSERT INTO `common_info` VALUES (74, '2020-06-04 16:34', NULL, '企业支付宝商户秘钥', 65, '', 'zhifubao'); +INSERT INTO `common_info` VALUES (77, '2021-03-15 21:22:30', NULL, '文件上传阿里云Endpoint', 68, 'https://oss-cn-beijing.aliyuncs.com', 'oss'); +INSERT INTO `common_info` VALUES (78, '2021-03-15 21:22:38', NULL, '文件上传阿里云账号accessKeyId', 69, '', 'oss'); +INSERT INTO `common_info` VALUES (79, '2021-03-15 21:22:46', NULL, '文件上传阿里云账号accessKeySecret', 70, '', 'oss'); +INSERT INTO `common_info` VALUES (80, '2021-03-15 21:22:53', NULL, '文件上传阿里云Bucket名称', 71, '', 'oss'); +INSERT INTO `common_info` VALUES (81, '2021-03-15 21:23:00', NULL, '文件上传阿里云Bucket域名', 72, 'https://shegnqx.oss-cn-beijing.aliyuncs.com', 'oss'); +INSERT INTO `common_info` VALUES (83, '2020-07-27 15:17', NULL, '微信APPappId', 74, '', 'weixin'); +INSERT INTO `common_info` VALUES (84, '2020-07-27 15:17', NULL, '微信商户key', 75, '', 'weixin'); +INSERT INTO `common_info` VALUES (85, '2020-07-27 15:17', NULL, '微信商户号mchId', 76, '', 'weixin'); +INSERT INTO `common_info` VALUES (88, '2021-02-24 18:46:57', NULL, '官方邀请码', 88, '666666', 'xitong'); +INSERT INTO `common_info` VALUES (96, '2020-07-27 15:17', NULL, '阿里云登陆或注册模板code(开启阿里云短信必须配置)', 80, 'SMS_200190994', 'duanxin'); +INSERT INTO `common_info` VALUES (97, '2020-07-27 15:17', NULL, '阿里云找回密码模板code(开启阿里云短信必须配置)', 81, 'SMS_200176048', 'duanxin'); +INSERT INTO `common_info` VALUES (98, '2020-07-27 15:17', NULL, '阿里云绑定手机号模板code(开启阿里云短信必须配置)', 82, 'SMS_200186024', 'duanxin'); +INSERT INTO `common_info` VALUES (99, '2020-07-27 15:17', NULL, '阿里云短信accessKeyId', 83, '', 'duanxin'); +INSERT INTO `common_info` VALUES (100, '2020-07-27 15:17', NULL, '阿里云短信accessSecret', 84, '', 'duanxin'); +INSERT INTO `common_info` VALUES (101, '2020-07-27 15:17', NULL, '邀请赚钱推广内容', 101, '', 'xitongs'); +INSERT INTO `common_info` VALUES (102, '2022-04-21 19:39:21', NULL, '转账方式 1支付宝证书 2支付宝秘钥 3手动', 98, '3', 'zhifubao'); +INSERT INTO `common_info` VALUES (103, '2020-07-27 15:17', NULL, '邀请赚钱微信分享内容', 103, '全民竞技,人人可参与的赛事平台!让电竞更简单', 'xitongs'); +INSERT INTO `common_info` VALUES (108, '2021-11-02 15:26:21', NULL, '公众号是否自动登录', 108, '否', 'weixins'); +INSERT INTO `common_info` VALUES (118, '2021-12-20 14:43:56', NULL, '用户端签到模块签到规则周期', 118, '0', 'xitongs'); +INSERT INTO `common_info` VALUES (119, '2020-11-13 13:06:39', NULL, '用户端每日签到积分', 119, '0', 'xitongs'); +INSERT INTO `common_info` VALUES (120, '2020-11-13 13:06:39', NULL, '用户端每天增加签到积分', 120, '0', 'xitongs'); +INSERT INTO `common_info` VALUES (130, '2021-12-03 17:59:08', NULL, '提现最低额度', 112, '10', 'fuwufei'); +INSERT INTO `common_info` VALUES (140, '2020-07-27 15:17', NULL, '用户端腾讯地图key', 128, 'WI7BZ-YZCKF-U3BJQ-JUMBB-XUQ3E-UXFYU', 'weixins'); +INSERT INTO `common_info` VALUES (154, '2020-11-04 10:31:40', NULL, '是否开启APP微信分享', 136, '否', 'weixins'); +INSERT INTO `common_info` VALUES (159, '2021-11-02 14:53:27', NULL, 'H5推广是否分享APP下载页面', 141, '否', 'xitongs'); +INSERT INTO `common_info` VALUES (170, '2020-11-04 10:31:40', NULL, '提现手续费', 152, '0.01', 'fuwufei'); +INSERT INTO `common_info` VALUES (171, '2021-09-06 16:19:51', NULL, '最高提现金额', 153, '1000', 'fuwufei'); +INSERT INTO `common_info` VALUES (172, '2020-11-04 10:31:40', NULL, '金币比列(充值的钱比例默认1:1)', 154, '1', 'fuwufeis'); +INSERT INTO `common_info` VALUES (173, '2021-08-14 19:09:54', NULL, '平台费率0.3表示百分之30,', 155, '0.3', 'fuwufeis'); +INSERT INTO `common_info` VALUES (174, '2021-08-14 19:09:54', NULL, '会员费率会员特权的折扣费用', 156, '0.9', 'fuwufeis'); +INSERT INTO `common_info` VALUES (182, '2022-03-28 11:24:34', NULL, '短信宝用户名', 164, '', 'duanxin'); +INSERT INTO `common_info` VALUES (183, '2022-03-28 11:24:47', NULL, '短信宝密码', 165, '', 'duanxin'); +INSERT INTO `common_info` VALUES (200, '2022-08-01 15:09:22', NULL, '帮助中心', 175, '

本应用尊重并保护所有使用服务用户的个人隐私权。为了给您提供更准确、更有个性化的服务,本应用会按照本隐私权政策的规定使用和披露您的个人信息。但本应用将以高度的勤勉、审慎义务对待这些信息。除本隐私权政策另有规定外,在未征得您事先许可的情况下,本应用不会将这些信息对外披露或向第三方提供。本应用会不时更新本隐私权政策。 您在同意本应用服务使用协议之时,即视为您已经同意本隐私权政策全部内容。本隐私权政策属于本应用服务使用协议不可分割的一部分。

1. 适用范围

(a) 在您注册本应用帐号时,您根据本应用要求提供的个人注册信息;

(b) 在您使用本应用网络服务,或访问本应用平台网页时,本应用自动接收并记录的您的浏览器和计算机上的信息,包括但不限于您的IP地址、浏览器的类型、使用的语言、访问日期和时间、软硬件特征信息及您需求的网页记录等数据;

(c) 本应用通过合法途径从商业伙伴处取得的用户个人数据。

您了解并同意,以下信息不适用本隐私权政策:

(a) 您在使用本应用平台提供的搜索服务时输入的关键字信息;

(b) 本应用收集到的您在本应用发布的有关信息数据,包括但不限于参与活动、成交信息及评价详情;

(c) 违反法律规定或违反本应用规则行为及本应用已对您采取的措施。

2. 信息使用

(a)本应用不会向任何无关第三方提供、出售、出租、分享或交易您的个人信息,除非事先得到您的许可,或该第三方和本应用(含本应用关联公司)单独或共同为您提供服务,且在该服务结束后,其将被禁止访问包括其以前能够访问的所有这些资料。

(b) 本应用亦不允许任何第三方以任何手段收集、编辑、出售或者无偿传播您的个人信息。任何本应用平台用户如从事上述活动,一经发现,本应用有权立即终止与该用户的服务协议。

(c) 为服务用户的目的,本应用可能通过使用您的个人信息,向您提供您感兴趣的信息,包括但不限于向您发出产品和服务信息,或者与本应用合作伙伴共享信息以便他们向您发送有关其产品和服务的信息(后者需要您的事先同意)。

3. 信息披露

在如下情况下,本应用将依据您的个人意愿或法律的规定全部或部分的披露您的个人信息:

(a) 经您事先同意,向第三方披露;

(b)为提供您所要求的产品和服务,而必须和第三方分享您的个人信息;

(c) 根据法律的有关规定,或者行政或司法机构的要求,向第三方或者行政、司法机构披露;

(d) 如您出现违反中国有关法律、法规或者本应用服务协议或相关规则的情况,需要向第三方披露;

(e) 如您是适格的知识产权投诉人并已提起投诉,应被投诉人要求,向被投诉人披露,以便双方处理可能的权利纠纷;

(f) 在本应用平台上创建的某一交易中,如交易任何一方履行或部分履行了交易义务并提出信息披露请求的,本应用有权决定向该用户提供其交易对方的联络方式等必要信息,以促成交易的完成或纠纷的解决。

(g) 其它本应用根据法律、法规或者网站政策认为合适的披露。

4. 信息存储和交换

本应用收集的有关您的信息和资料将保存在本应用及(或)其关联公司的服务器上,这些信息和资料可能传送至您所在国家、地区或本应用收集信息和资料所在地的境外并在境外被访问、存储和展示。

5. Cookie的使用

(a) 在您未拒绝接受cookies的情况下,本应用会在您的计算机上设定或取用cookies ,以便您能登录或使用依赖于cookies的本应用平台服务或功能。本应用使用cookies可为您提供更加周到的个性化服务,包括推广服务。

(b) 您有权选择接受或拒绝接受cookies。您可以通过修改浏览器设置的方式拒绝接受cookies。但如果您选择拒绝接受cookies,则您可能无法登录或使用依赖于cookies的本应用网络服务或功能。

(c) 通过本应用所设cookies所取得的有关信息,将适用本政策。

6. 信息安全

(a) 本应用帐号均有安全保护功能,请妥善保管您的用户名及密码信息。本应用将通过对用户密码进行加密等安全措施确保您的信息不丢失,不被滥用和变造。尽管有前述安全措施,但同时也请您注意在信息网络上不存在“完善的安全措施”。

(b) 在使用本应用网络服务进行网上交易时,您不可避免的要向交易对方或潜在的交易对方披露自己的个人信息,如联络方式或者邮政地址。请您妥善保护自己的个人信息,仅在必要的情形下向他人提供。如您发现自己的个人信息泄密,尤其是本应用用户名及密码发生泄露,请您立即联络本应用客服,以便本应用采取相应措施。

7.本隐私政策的更改

(a)如果决定更改隐私政策,我们会在本政策中、本公司网站中以及我们认为适当的位置发布这些更改,以便您了解我们如何收集、使用您的个人信息,哪些人可以访问这些信息,以及在什么情况下我们会透露这些信息。

(b)本公司保留随时修改本政策的权利,因此请经常查看。如对本政策作出重大更改,本公司会通过网站通知的形式告知。

', 'xieyis'); +INSERT INTO `common_info` VALUES (201, '2021-08-14 19:10:04', NULL, '隐私政策', 176, '

本应用尊重并保护所有使用服务用户的个人隐私权。为了给您提供更准确、更有个性化的服务,本应用会按照本隐私权政策的规定使用和披露您的个人信息。但本应用将以高度的勤勉、审慎义务对待这些信息。除本隐私权政策另有规定外,在未征得您事先许可的情况下,本应用不会将这些信息对外披露或向第三方提供。本应用会不时更新本隐私权政策。 您在同意本应用服务使用协议之时,即视为您已经同意本隐私权政策全部内容。本隐私权政策属于本应用服务使用协议不可分割的一部分。

1. 适用范围

(a) 在您注册本应用帐号时,您根据本应用要求提供的个人注册信息;

(b) 在您使用本应用网络服务,或访问本应用平台网页时,本应用自动接收并记录的您的浏览器和计算机上的信息,包括但不限于您的IP地址、浏览器的类型、使用的语言、访问日期和时间、软硬件特征信息及您需求的网页记录等数据;

(c) 本应用通过合法途径从商业伙伴处取得的用户个人数据。

您了解并同意,以下信息不适用本隐私权政策:

(a) 您在使用本应用平台提供的搜索服务时输入的关键字信息;

(b) 本应用收集到的您在本应用发布的有关信息数据,包括但不限于参与活动、成交信息及评价详情;

(c) 违反法律规定或违反本应用规则行为及本应用已对您采取的措施。

2. 信息使用

(a)本应用不会向任何无关第三方提供、出售、出租、分享或交易您的个人信息,除非事先得到您的许可,或该第三方和本应用(含本应用关联公司)单独或共同为您提供服务,且在该服务结束后,其将被禁止访问包括其以前能够访问的所有这些资料。

(b) 本应用亦不允许任何第三方以任何手段收集、编辑、出售或者无偿传播您的个人信息。任何本应用平台用户如从事上述活动,一经发现,本应用有权立即终止与该用户的服务协议。

(c) 为服务用户的目的,本应用可能通过使用您的个人信息,向您提供您感兴趣的信息,包括但不限于向您发出产品和服务信息,或者与本应用合作伙伴共享信息以便他们向您发送有关其产品和服务的信息(后者需要您的事先同意)。

3. 信息披露

在如下情况下,本应用将依据您的个人意愿或法律的规定全部或部分的披露您的个人信息:

(a) 经您事先同意,向第三方披露;

(b)为提供您所要求的产品和服务,而必须和第三方分享您的个人信息;

(c) 根据法律的有关规定,或者行政或司法机构的要求,向第三方或者行政、司法机构披露;

(d) 如您出现违反中国有关法律、法规或者本应用服务协议或相关规则的情况,需要向第三方披露;

(e) 如您是适格的知识产权投诉人并已提起投诉,应被投诉人要求,向被投诉人披露,以便双方处理可能的权利纠纷;

(f) 在本应用平台上创建的某一交易中,如交易任何一方履行或部分履行了交易义务并提出信息披露请求的,本应用有权决定向该用户提供其交易对方的联络方式等必要信息,以促成交易的完成或纠纷的解决。

(g) 其它本应用根据法律、法规或者网站政策认为合适的披露。

4. 信息存储和交换

本应用收集的有关您的信息和资料将保存在本应用及(或)其关联公司的服务器上,这些信息和资料可能传送至您所在国家、地区或本应用收集信息和资料所在地的境外并在境外被访问、存储和展示。

5. Cookie的使用

(a) 在您未拒绝接受cookies的情况下,本应用会在您的计算机上设定或取用cookies ,以便您能登录或使用依赖于cookies的本应用平台服务或功能。本应用使用cookies可为您提供更加周到的个性化服务,包括推广服务。

(b) 您有权选择接受或拒绝接受cookies。您可以通过修改浏览器设置的方式拒绝接受cookies。但如果您选择拒绝接受cookies,则您可能无法登录或使用依赖于cookies的本应用网络服务或功能。

(c) 通过本应用所设cookies所取得的有关信息,将适用本政策。

6. 信息安全

(a) 本应用帐号均有安全保护功能,请妥善保管您的用户名及密码信息。本应用将通过对用户密码进行加密等安全措施确保您的信息不丢失,不被滥用和变造。尽管有前述安全措施,但同时也请您注意在信息网络上不存在“完善的安全措施”。

(b) 在使用本应用网络服务进行网上交易时,您不可避免的要向交易对方或潜在的交易对方披露自己的个人信息,如联络方式或者邮政地址。请您妥善保护自己的个人信息,仅在必要的情形下向他人提供。如您发现自己的个人信息泄密,尤其是本应用用户名及密码发生泄露,请您立即联络本应用客服,以便本应用采取相应措施。

7.本隐私政策的更改

(a)如果决定更改隐私政策,我们会在本政策中、本公司网站中以及我们认为适当的位置发布这些更改,以便您了解我们如何收集、使用您的个人信息,哪些人可以访问这些信息,以及在什么情况下我们会透露这些信息。

(b)本公司保留随时修改本政策的权利,因此请经常查看。如对本政策作出重大更改,本公司会通过网站通知的形式告知。

', 'xieyi'); +INSERT INTO `common_info` VALUES (202, '2021-08-14 19:09:54', NULL, '注册协议', 177, '

尊敬的用户您好:在您使用本服务之前,请您认真阅读本用户协议,更好的了解我们所提供的服务以及您享有的权利义务。您开始使用时,即表示您已经了解并确认接受了本文件中的全部条款,包括我们对本服务条款随时做的任何修改。

一、协议的效力

本协议内容包括协议正文及所有已经发布或将来可能发布的各类规则。所有规则为本协议不可分割的组成部分,与协议正文具有同等法律效力。您承诺接受并遵守本协议的约定。如果您不同意本协议的约定,您应立即停止使用本平台服务。

二、用户行为规范

用户同意将不会利用本服务进行任何违法或不正当的活动,包括但不限于下列行为∶

发布或以其它方式传送含有下列内容之一的信息:

反对宪法所确定的基本原则的;

危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的;

损害国家荣誉和利益的;

煽动民族仇恨、民族歧视、破坏民族团结的;

破坏国家宗教政策,宣扬邪教和封建迷信的;

散布谣言,扰乱社会秩序,破坏社会稳定的;

散布淫秽、色情、赌博、暴力、凶杀、恐怖或者教唆犯罪的;

侮辱或者诽谤他人,侵害他人合法权利的;

含有虚假、诈骗、有害、胁迫、侵害他人隐私、骚扰、侵害、中伤、粗俗、猥亵、或其它道德上令人反感的内容;

含有当地法律、法规、规章、条例以及任何具有法律效力之规范所限制或禁止的其它内容的;

含有不适合在本平台展示的内容;

以任何方式危害他人的合法权益;

冒充其他任何人或机构,或以虚伪不实的方式陈述或谎称与任何人或机构有关;

将依据任何法律或合约或法定关系(例如由于雇佣关系和依据保密合约所得知或揭露之内部资料、专属及机密资料)知悉但无权传送之任何内容加以发布、发送电子邮件或以其它方式传送;

将侵害他人著作权、专利权、商标权、商业秘密、或其它专属权利(以下简称“专属权利”)之内容加以发布或以其它方式传送;

将任何广告信函、促销资料、“垃圾邮件”、““滥发信件”、“连锁信件”、“直销”或其它任何形式的劝诱资料加以发布、发送或以其它方式传送;

将设计目的在于干扰、破坏或限制任何计算机软件、硬件或通讯设备功能之计算机病毒(包括但不限于木马程序(trojan horses)、蠕虫(worms)、定时炸弹、删除蝇(cancelbots)(以下简称“病毒”)或其它计算机代码、档案和程序之任何资料,加以发布、发送或以其它方式传送;

干扰或破坏本服务或与本服务相连线之服务器和网络,或违反任何关于本服务连线网络之规定、程序、政策或规范;

跟踪、人肉搜索或以其它方式骚扰他人;

故意或非故意地违反任何适用的当地、国家法律,以及任何具有法律效力的规则;

未经合法授权而截获、篡改、收集、储存或删除他人个人信息、站内邮件或其它数据资料,或将获知的此类资料用于任何非法或不正当目的。

三、知识产权

本平台所有设计图样以及其他图样、产品及服务名称。任何人不得使用、复制或用作其他用途。未经我们许可,任何单位和个人不得私自复制、传播、展示、镜像、上载、下载、使用,或者从事任何其他侵犯我们知识产权的行为。否则,我们将追究相关法律责任。

我们鼓励用户充分利用平台自由地张贴和共享自己的信息,但这些内容必须位于公共领域内,或者用户拥有这些内容的使用权。同时,用户对于其创作并在本平台上发布的合法内容依法享有著作权及其相关权利。

四、免责声明

互联网是一个开放平台,用户将照片等个人资料上传到互联网上,有可能会被其他组织或个人复制、转载、擅改或做其它非法用途,用户必须充分意识此类风险的存在。用户明确同意其使用本服务所存在的风险将完全由其自己承担;因其使用本服务而产生的一切后果也由其自己承担,我们对用户不承担任何责任。

对于用户上传的照片、资料、证件等,已采用相关措施并已尽合理努力进行审核,但不保证其内容的正确性、合法性或可靠性,相关责任由上传上述内容的会员负责。

尽管已采取相应的技术保障措施 ,但用户仍有可能收到各类的广告信或其他不以招聘/应聘为目的邮件或其它方式传送的任何内容,本平台不承担责任。

对于各种广告信息、链接、资讯等,不保证其内容的正确性、合法性或可靠性,相关责任由广告商承担;用户通过本服务与广告商进行任何形式的通讯或商业往来,或参与促销活动,包含相关商品或服务之付款及交付,以及达成的其它任何相关条款、条件、保证或声明,完全为用户与广告商之间之行为,与本平台无关。用户因前述任何交易或前述广告商而遭受的任何性质的损失或损害,本平台不承担任何责任。

本平台不保证其提供的服务一定能满足用户的要求和期望,也不保证服务不会中断,对服务的及时性、安全性、准确性也都不作保证。对于因不可抗力或无法控制的原因造成的网络服务中断或其他缺陷,不承担任何责任。我们不对用户所发布信息的删除或储存失败承担责任。我们有权判断用户的行为是否符合本网站使用协议条款之规定,如果我们认为用户违背了协议条款的规定,我们有终止向其提供服务的权利。

本平台保留变更、中断或终止部分网络服务的权利。保留根据实际情况随时调整平台提供的服务种类、形式的权利。本平台不承担因业务调整给用户造成的损失。本平台仅提供相关服务,除此之外与本服务有关的设备(如电脑、调制解调器及其他与接入互联网有关的装置)及所需的费用(如为接入互联网而支付的电话费及上网费)均应由用户自行负担。

', 'xieyi'); +INSERT INTO `common_info` VALUES (203, '2021-08-14 19:09:54', NULL, '关于我们', 187, '关于我们,有问题可以在线联系客服哦。', 'xieyi'); +INSERT INTO `common_info` VALUES (204, '2021-08-14 19:09:54', NULL, '登录是否获取手机号', 188, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (205, '2020-10-28 16:57:07', NULL, '邀请赏金(邀请用户可以获得的赏金)', 189, '0', 'fuwufei'); +INSERT INTO `common_info` VALUES (206, '2023-01-19 11:24:28', NULL, '送水工默认佣金', 206, '0.1', 'fuwufei'); +INSERT INTO `common_info` VALUES (217, '2022-10-18 14:02:41', NULL, '师傅端微信腾讯地图key', 217, 'WI7BZ-YZCKF-U3BJQ-JUMBB-XUQ3E-UXFYU', 'weixin'); +INSERT INTO `common_info` VALUES (234, '2022-05-18 14:52:58', NULL, '上传方式 1阿里云oss 2本地', 234, '2', 'oss'); +INSERT INTO `common_info` VALUES (237, '2021-11-02 15:26:21', NULL, '是否开启公众号', 237, '否', 'weixins'); +INSERT INTO `common_info` VALUES (238, '2023-12-19 11:40:56', NULL, '小程序上架是否显示1', 238, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (239, '2023-01-28 16:09:39', NULL, '师傅微信小程序APPID', 239, '', 'weixin'); +INSERT INTO `common_info` VALUES (240, '2023-01-28 16:09:47', NULL, '师傅微信小程序秘钥', 240, '', 'weixin'); +INSERT INTO `common_info` VALUES (243, '2020-11-04 10:31:40', NULL, '是否开启微信提现', 243, '否', 'weixins'); +INSERT INTO `common_info` VALUES (244, '2021-12-22 10:11:36', NULL, '微信提现方式 1自动 2手动', 244, '2', 'weixins'); +INSERT INTO `common_info` VALUES (245, '2020-11-04 10:31:40', NULL, '是否开启支付宝提现', 245, '是', 'zhifubao'); +INSERT INTO `common_info` VALUES (246, NULL, NULL, '微信证书地址', 201, '/www/wexixin', 'weixin'); +INSERT INTO `common_info` VALUES (247, '2020-10-28 16:57:07', NULL, '万能任务最低金额', 202, '20', 'fuwufeis'); +INSERT INTO `common_info` VALUES (248, '2023-12-19 13:07:05', NULL, '接单端是否上线', 203, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (250, '2020-11-04 10:31:40', NULL, '超时几分钟短信通知', 250, '5', 'duanxins'); +INSERT INTO `common_info` VALUES (251, '2020-11-04 10:31:40', NULL, '几条未读短信通知', 251, '1', 'duanxins'); +INSERT INTO `common_info` VALUES (252, '2022-10-18 14:00:59', NULL, '推广员佣金', 207, '0', 'fuwufei'); +INSERT INTO `common_info` VALUES (253, '2022-10-18 14:01:07', NULL, '代理商佣金', 208, '0', 'fuwufei'); +INSERT INTO `common_info` VALUES (254, '2022-10-18 14:02:41', NULL, '是否开启佣金', 209, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (255, '2022-01-24 21:03:25', NULL, '分享提示语', 255, '分享提示分享提示', 'xitongs'); +INSERT INTO `common_info` VALUES (257, '2022-07-07 13:11:53', NULL, '小程序上架是否显示2', 257, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (258, '2022-05-06 12:35:13', NULL, '支付宝方式 1证书 2秘钥', 258, '2', 'zhifubao'); +INSERT INTO `common_info` VALUES (259, '2022-05-06 12:35:13', NULL, '支付宝证书方式 证书地址', 259, '1', 'zhifubao'); +INSERT INTO `common_info` VALUES (260, '2022-05-06 12:35:13', NULL, '是否开启我的团队', 260, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (261, '2020-11-13 13:06:39', NULL, '积分抵扣比例(1元)', 261, '100', 'xitongs'); +INSERT INTO `common_info` VALUES (298, '2022-11-07 12:28:58', NULL, '聊天关键词过滤', 602, '1', 'xitongs'); +INSERT INTO `common_info` VALUES (301, '2022-08-22 11:54:53', NULL, '师傅保证金金额', 271, '1', 'fuwufei'); +INSERT INTO `common_info` VALUES (302, '2022-06-21 16:47:57', NULL, '保证金缴纳协议', 272, '送水技术工认证需要保证金300', 'xitong'); +INSERT INTO `common_info` VALUES (303, '2022-06-21 16:47:57', NULL, '保证金退款协议', 273, '送水技术工认证需要保证金300', 'xitong'); +INSERT INTO `common_info` VALUES (304, '2022-09-01 10:31:04', NULL, '企业微信链接', 274, 'https://work.weixin.qq.com/kfid/kfc59fa3a70b4f7cde1', 'xitong'); +INSERT INTO `common_info` VALUES (305, '2022-09-01 10:30:52', NULL, '企业微信客服APPID', 275, 'ww16896a4e2489dd2d', 'xitong'); +INSERT INTO `common_info` VALUES (306, '2022-08-22 11:55:06', NULL, '分享标题', 276, '上门洗车 洗车啦', 'xitongs'); +INSERT INTO `common_info` VALUES (307, '2022-06-21 16:47:57', NULL, '分享图', 277, 'https://taobao.xianmxkj.com/custom.jpg', 'xitongs'); +INSERT INTO `common_info` VALUES (308, '2022-11-26 12:04:05', NULL, '订单变更通知', 278, 'FNkvrHMfKKAfJD3LWtzKFY-XOmhC7jgTQsoCbVkTesQ', 'weixin'); +INSERT INTO `common_info` VALUES (309, '2023-03-22 17:19:35', NULL, '充值金额分类', 279, '1,50,100,200,500,1000', 'xitong'); +INSERT INTO `common_info` VALUES (310, '2024-04-15 15:20:32', NULL, '新人优惠券(格式:id,数量)', 310, '1,5', 'xitong'); +INSERT INTO `common_info` VALUES (312, '2022-11-28 15:28:08', NULL, '师傅新订单通知', 312, 'XRdYhbfDujEaujdYB_aWCqXDF3DpXDDQ-m36L9GKiqw', 'weixin'); +INSERT INTO `common_info` VALUES (315, '2024-01-09 14:28:18', NULL, '送水上线开关2', 315, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (316, '2022-11-26 11:26:50', NULL, '是否开启新人优惠券(1开启 0未开启)', 316, '1', 'xitong'); +INSERT INTO `common_info` VALUES (318, '2020-11-04 10:30:40', NULL, '订单无人接单自动取消时间(分钟)', 318, '30', 'fuwufei'); +INSERT INTO `common_info` VALUES (321, '2022-11-28 15:28:08', NULL, '师傅接单通知', 321, 'H7gyQkw314q-ALva8G0Ede6CZvEc5YDAQwHmNBSz0t0', 'weixin'); +INSERT INTO `common_info` VALUES (322, '2022-11-28 15:28:08', NULL, '库存预警值', 322, '10', 'fuwufei'); +INSERT INTO `common_info` VALUES (323, '2024-03-25 10:02:17', NULL, '联系客服方式 1,手机号 2,企业微信  3,客服二维码', 323, '1', 'xitong'); +INSERT INTO `common_info` VALUES (324, '2024-03-25 10:02:22', NULL, '客服电话', 324, '1', 'xitong'); +INSERT INTO `common_info` VALUES (325, '2022-11-28 15:28:08', NULL, '展示附近多少公里的师傅(单位:公里)', 325, '5', 'xitong'); +INSERT INTO `common_info` VALUES (326, '2023-04-12 19:47:22', NULL, '单桶价格(单位:元)', 326, '0.01', 'xitong'); +INSERT INTO `common_info` VALUES (327, '2023-05-17 19:49:25', NULL, '是否开启师傅修改压桶权限(是:开启。否:关闭)', 327, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (329, '2023-04-20 15:36:55', NULL, '接单是否需要送水工认证(是:需要 否:不需要)', 329, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (330, '2023-06-26 17:42:03', NULL, '是否开启用户一键下单(是:开启 否:关闭)', 330, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (331, '2024-03-01 10:36:48', NULL, '是否开启师傅一键下单(是:开启 否:关闭)', 331, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (332, '2024-03-01 13:16:00', NULL, '师傅端是否上线', 332, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (333, '2023-06-26 17:41:50', NULL, '首页是否展示站点单(是:展示 否:隐藏)', 333, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (334, '2023-04-24 11:02:03', NULL, '是否开启师傅端不需要确认码就可以提交(是:开启 否:关闭)', 334, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (335, '2024-04-15 15:19:29', NULL, '首页一键订水商品', 335, '315', 'xitong'); +INSERT INTO `common_info` VALUES (336, '2023-04-24 11:02:03', NULL, '一键订水购买数量配置', 336, '1,2,3,4,5,6,7,8,9,10', 'xitong'); +INSERT INTO `common_info` VALUES (338, '2023-04-27 14:20:32', NULL, '首页图片配置', 338, 'https://songshui.xianmaxiong.com/file/uploadPath/2023/04/27/980525a70df0b6480fb1526f003345db.png', 'image'); +INSERT INTO `common_info` VALUES (339, '2023-06-26 17:45:07', NULL, '是否展示水贝余额(是:开启,否:关闭)', 339, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (340, '2023-05-30 16:12:00', NULL, '是否开启师傅接单池定时器开关(是:开启,否:关闭)', 340, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (341, '2023-05-31 14:07:37', NULL, '用户端是否开启完成按钮(是:开启,否:关闭)', 341, '否', 'kaiguan'); +INSERT INTO `common_info` VALUES (342, '2023-06-25 16:35:11', NULL, '下单压桶开关(是:开启,否:关闭)', 342, '是', 'kaiguan'); +INSERT INTO `common_info` VALUES (414, '2023-07-26 16:27:15', NULL, '地图方式 1腾讯 2天地图', 414, '2', 'xitong'); +INSERT INTO `common_info` VALUES (415, '2023-07-26 16:27:15', NULL, '天地图key', 415, 'cc3051d93f476fdf11abbbfa3e009657', 'xitong'); +INSERT INTO `common_info` VALUES (416, '2024-09-18 11:37:51', NULL, '否开启定位', 416, '是', 'kaiguan'); + +-- ---------------------------- +-- Table structure for game +-- ---------------------------- +DROP TABLE IF EXISTS `game`; +CREATE TABLE `game` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '分类id', + `game_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类名称', + `status` int(2) NULL DEFAULT NULL COMMENT '0启用1删除\r\n', + `game_img` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类图标', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改时间', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of game +-- ---------------------------- +INSERT INTO `game` VALUES (15, '桶装水(需压桶)', 0, 'https://jiazheng.xianmxkj.com/file/uploadPath/2022/07/29/f972796249f8b3d5266973b9899a6bf2.png', '2022-07-29 15:00:09', '2023-10-25 21:57:55'); +INSERT INTO `game` VALUES (16, '一次性饮用水', 0, 'https://jiazheng.xianmxkj.com/file/uploadPath/2022/07/29/600cae4df8c5e2ac85173a5749e48bc0.png', '2022-07-29 15:00:18', '2023-10-25 21:57:57'); +INSERT INTO `game` VALUES (17, '饮用水设备', 0, 'https://jiazheng.xianmxkj.com/file/uploadPath/2022/07/29/978a503ad0efbed73020fb713fdf262f.png', '2022-07-29 15:00:35', '2023-10-25 21:57:58'); +INSERT INTO `game` VALUES (18, '好山好水', 0, NULL, '2023-04-13 11:25:31', '2023-10-25 21:57:59'); +INSERT INTO `game` VALUES (19, '其他', 0, NULL, '2023-04-20 13:35:11', '2023-04-20 13:35:11'); +INSERT INTO `game` VALUES (20, '茶叶', 0, NULL, '2024-06-12 14:03:47', '2024-06-12 14:03:47'); + +-- ---------------------------- +-- Table structure for goods_attr +-- ---------------------------- +DROP TABLE IF EXISTS `goods_attr`; +CREATE TABLE `goods_attr` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '规格id', + `attr_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '属性名称', + `goods_id` bigint(20) NULL DEFAULT NULL COMMENT '商品id', + `rule_id` bigint(20) NULL DEFAULT NULL COMMENT '规格模板id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 3262 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of goods_attr +-- ---------------------------- + +-- ---------------------------- +-- Table structure for goods_attr_value +-- ---------------------------- +DROP TABLE IF EXISTS `goods_attr_value`; +CREATE TABLE `goods_attr_value` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '属性id', + `detail` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '属性值组合:{尺寸: \'7寸\', 颜色: \'红底\'}', + `goods_id` bigint(20) NULL DEFAULT NULL COMMENT '商品id', + `attr_id` bigint(20) NULL DEFAULT NULL COMMENT '商品规格id', + `value` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '规格属性名称', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1521 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of goods_attr_value +-- ---------------------------- + +-- ---------------------------- +-- Table structure for goods_rule +-- ---------------------------- +DROP TABLE IF EXISTS `goods_rule`; +CREATE TABLE `goods_rule` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '创建时间', + `rule_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '规格名称', + `game_id` int(11) NULL DEFAULT NULL COMMENT '分类id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 152 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of goods_rule +-- ---------------------------- + +-- ---------------------------- +-- Table structure for goods_rule_value +-- ---------------------------- +DROP TABLE IF EXISTS `goods_rule_value`; +CREATE TABLE `goods_rule_value` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `detail` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '规格属性值', + `rule_id` bigint(20) NULL DEFAULT NULL COMMENT '规格id', + `value` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '规格属性名称', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 298 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of goods_rule_value +-- ---------------------------- + +-- ---------------------------- +-- Table structure for goods_sku +-- ---------------------------- +DROP TABLE IF EXISTS `goods_sku`; +CREATE TABLE `goods_sku` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `goods_id` bigint(20) NULL DEFAULT NULL COMMENT '商品id', + `sku_img` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT 'sku图片', + `sku_member_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'sku会员价', + `sku_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'sku商品售价', + `stock` int(11) NULL DEFAULT NULL COMMENT '库存', + `sales` int(11) NULL DEFAULT NULL COMMENT '销量', + `detail_json` text CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL COMMENT 'sku信息,json封装', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 6482 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of goods_sku +-- ---------------------------- + +-- ---------------------------- +-- Table structure for help_classify +-- ---------------------------- +DROP TABLE IF EXISTS `help_classify`; +CREATE TABLE `help_classify` ( + `help_classify_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '帮助中心分类', + `help_classify_name` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类名称', + `sort` int(11) NULL DEFAULT NULL COMMENT '排序', + `parent_id` int(11) NULL DEFAULT NULL COMMENT '上级id', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `types` int(11) NULL DEFAULT NULL COMMENT '类型', + PRIMARY KEY (`help_classify_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of help_classify +-- ---------------------------- +INSERT INTO `help_classify` VALUES (7, '登录问题', 0, NULL, '2022-07-06', 1); +INSERT INTO `help_classify` VALUES (8, '师傅端入驻申请流程', 0, NULL, '2022-07-06', 2); +INSERT INTO `help_classify` VALUES (9, '商家端怎么发起服务?', 0, NULL, '2022-07-06', 2); + +-- ---------------------------- +-- Table structure for help_order +-- ---------------------------- +DROP TABLE IF EXISTS `help_order`; +CREATE TABLE `help_order` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '跑腿订单id', + `help_take_id` int(11) NULL DEFAULT NULL COMMENT '接单id', + `order_no` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '订单编号', + `content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '内容', + `phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话', + `province` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '省', + `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '市', + `district` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '区', + `details_address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '详细地址', + `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名', + `delivery_time` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '期望送达时间', + `user_id` int(11) NULL DEFAULT NULL COMMENT '发单人id', + `commission` decimal(10, 2) NULL DEFAULT NULL COMMENT '佣金', + `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '收货码', + `status` int(11) NULL DEFAULT NULL COMMENT '状态(1待审核 2待接单 3待送达 4已完成)', + `longitude` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '经度', + `latitude` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '纬度', + `pay_type` int(11) NULL DEFAULT NULL COMMENT '支付方式 1微信 2支付宝', + `create_time` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `cause` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '拒绝原因', + `money` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '实际发布金额', + `image` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片', + `game_id` int(11) NULL DEFAULT NULL COMMENT '分类id', + `pay_way` int(11) NULL DEFAULT NULL COMMENT '支付方式 1零钱 2微信 3支付宝', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of help_order +-- ---------------------------- + +-- ---------------------------- +-- Table structure for help_take +-- ---------------------------- +DROP TABLE IF EXISTS `help_take`; +CREATE TABLE `help_take` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '接单id', + `order_id` int(11) NULL DEFAULT NULL COMMENT '订单id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `money` decimal(11, 2) NULL DEFAULT NULL COMMENT '实际收益', + `status` int(11) NULL DEFAULT NULL COMMENT '状态', + `create_time` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '接单时间', + `end_time` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '送达时间 结束时间', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of help_take +-- ---------------------------- + +-- ---------------------------- +-- Table structure for help_word +-- ---------------------------- +DROP TABLE IF EXISTS `help_word`; +CREATE TABLE `help_word` ( + `help_word_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '帮助文档id', + `help_word_title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '帮助标题', + `help_word_content` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '帮助文档内容', + `help_classify_id` int(11) NULL DEFAULT NULL COMMENT '帮助分类id', + `sort` int(11) NULL DEFAULT NULL COMMENT '排序', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`help_word_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of help_word +-- ---------------------------- +INSERT INTO `help_word` VALUES (1, '为什么提示不支持打开非业务域名', '因为所以科学道理', 2, 1, '2020-12-12 12:12:12'); +INSERT INTO `help_word` VALUES (2, '文件类课间如何保存', '不知道', 2, 2, '2020-12-12 12:12:12'); +INSERT INTO `help_word` VALUES (3, '已报名的活动可以取消吗', '可以,需要扣除百分之20', 3, 1, '2020-12-12 12:12:12'); +INSERT INTO `help_word` VALUES (7, '报名活动呀呀呀呀', '

报名活动呀呀呀呀报名活动呀呀呀呀报名活动呀呀呀呀报名活动呀呀呀呀报名活动呀呀呀呀报名活动呀呀呀呀报名活动呀呀呀呀报名活动呀呀呀呀报名活动呀呀呀呀

', 6, 0, '2022-07-05'); +INSERT INTO `help_word` VALUES (8, '怎么登录呢?', '

微信授权即可登录

', 7, 0, '2022-07-06'); +INSERT INTO `help_word` VALUES (9, '商户怎么入驻呢?', '

登录首页 点击:我要入驻

', 8, 0, '2022-07-06'); + +-- ---------------------------- +-- Table structure for invite +-- ---------------------------- +DROP TABLE IF EXISTS `invite`; +CREATE TABLE `invite` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '邀请者id', + `invitee_user_id` int(11) NULL DEFAULT NULL COMMENT '被邀请者id', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '收益', + `create_time` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `money_type` int(1) NULL DEFAULT NULL COMMENT '1会员2陪玩', + `state` int(11) NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1446 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '邀请信息' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of invite +-- ---------------------------- + +-- ---------------------------- +-- Table structure for invite_money +-- ---------------------------- +DROP TABLE IF EXISTS `invite_money`; +CREATE TABLE `invite_money` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '收益钱包id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `money_sum` decimal(10, 2) NULL DEFAULT NULL COMMENT '总获取收益', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '当前金额', + `cash_out` decimal(10, 2) NULL DEFAULT NULL COMMENT '累计提现', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of invite_money +-- ---------------------------- + +-- ---------------------------- +-- Table structure for laundry +-- ---------------------------- +DROP TABLE IF EXISTS `laundry`; +CREATE TABLE `laundry` ( + `laundry_id` bigint(20) NOT NULL AUTO_INCREMENT, + `audit_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `latitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `laundry_address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `laundry_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `laundry_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `laundry_user_id` bigint(20) NULL DEFAULT NULL, + `laundry_user_ids` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `license_front` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `license_reverse` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `longitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `sn_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `status` int(11) NULL DEFAULT NULL, + `value` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `is_open` int(11) NULL DEFAULT NULL, + `max_scope` int(11) NULL DEFAULT NULL, + `rate` decimal(19, 2) NULL DEFAULT NULL, + `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `scope` int(11) NULL DEFAULT NULL, + `sys_user_ids` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + PRIMARY KEY (`laundry_id`) USING BTREE +) ENGINE = MyISAM AUTO_INCREMENT = 33 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of laundry +-- ---------------------------- + +-- ---------------------------- +-- Table structure for member +-- ---------------------------- +DROP TABLE IF EXISTS `member`; +CREATE TABLE `member` ( + `member_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '会员特权id', + `member_img` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '特权图标', + `member_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '特权名称', + `sort` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '排序', + PRIMARY KEY (`member_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of member +-- ---------------------------- +INSERT INTO `member` VALUES (4, 'https://sac.xianmxkj.com/file/uploadPath/2021/12/26/3654c7c9d5d8eb0174d6f0356923bdd6.png', '专享九折', '1'); +INSERT INTO `member` VALUES (6, 'https://h5.canmoujiang.com/img/20210623/8a7dc8566b3046dfbb3e227ee157b7c0.png', '身份标识', '4'); + +-- ---------------------------- +-- Table structure for message_info +-- ---------------------------- +DROP TABLE IF EXISTS `message_info`; +CREATE TABLE `message_info` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '消息id', + `content` varchar(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '内容', + `create_at` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `image` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图片', + `is_see` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '0未读 2已读', + `send_state` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '暂未使用', + `send_time` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '暂未使用', + `state` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类', + `title` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '标题', + `url` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '地址', + `type` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '暂未使用', + `platform` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '暂未使用', + `user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户id', + `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名', + `audit_content` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '暂未使用', + `status` int(11) NULL DEFAULT NULL COMMENT '暂未使用', + `by_user_id` int(11) NULL DEFAULT NULL COMMENT '暂未使用', + `platform_id` int(11) NULL DEFAULT NULL COMMENT '暂未使用', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 7655 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of message_info +-- ---------------------------- + +-- ---------------------------- +-- Table structure for msg +-- ---------------------------- +DROP TABLE IF EXISTS `msg`; +CREATE TABLE `msg` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `code` varchar(255) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '短信验证码', + `phone` varchar(255) CHARACTER SET big5 COLLATE big5_chinese_ci NULL DEFAULT NULL COMMENT '电话', + PRIMARY KEY (`id`) USING BTREE, + INDEX `index_name`(`code`, `phone`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 3394 CHARACTER SET = big5 COLLATE = big5_chinese_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of msg +-- ---------------------------- + +-- ---------------------------- +-- Table structure for operators_log +-- ---------------------------- +DROP TABLE IF EXISTS `operators_log`; +CREATE TABLE `operators_log` ( + `log_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '日志id', + `user_type` int(1) NULL DEFAULT NULL COMMENT '1管理员 2商户 3用户', + `update_user_id` int(11) NULL DEFAULT NULL COMMENT '修改人id', + `update_user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人昵称', + `update_user_phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人电话号码', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户昵称', + `user_phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户电话号码', + `last_bucket` int(11) NULL DEFAULT NULL COMMENT '用户上一次压桶数', + `operator` int(1) NULL DEFAULT NULL COMMENT '1增加 2减少', + `operator_num` int(11) NULL DEFAULT NULL COMMENT '修改数量', + `next_bucket` int(1) NULL DEFAULT NULL COMMENT '修改后的压桶数', + `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间', + `status` int(1) NULL DEFAULT NULL COMMENT '0待审核 1已通过 2已拒绝', + PRIMARY KEY (`log_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 74 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of operators_log +-- ---------------------------- + +-- ---------------------------- +-- Table structure for order_taking +-- ---------------------------- +DROP TABLE IF EXISTS `order_taking`; +CREATE TABLE `order_taking` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '接单id', + `game_id` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '类型', + `my_level` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '描述', + `order_level` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '暂未使用', + `order_taking_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '暂未使用', + `order_taking_area` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '暂未使用', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '价格', + `member_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '会员价格', + `old_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '原价 发布价格', + `voice_introduce` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图', + `homepage_img` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '主页图片', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `status` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '接单状态0进行中1待审核2已下架3拒绝', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改时间', + `is_recommend` int(2) NULL DEFAULT NULL COMMENT '是否是推荐接单0是1不是', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '发布人', + `city` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `count` int(64) NULL DEFAULT NULL COMMENT '服务人数', + `order_score` double(10, 2) NULL DEFAULT NULL COMMENT '评分', + `longitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '精度', + `latitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '维度', + `isdelete` int(2) NULL DEFAULT NULL COMMENT '假删除0显示1删除', + `content` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '审核理由', + `sec` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '时长', + `classify` int(11) NULL DEFAULT NULL COMMENT '1 线上 2线下', + `unit` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '单位', + `details_img` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '详情图', + `sales_num` int(11) NULL DEFAULT NULL COMMENT '销量', + `authentication` int(11) NULL DEFAULT NULL COMMENT '审核', + `min_num` int(11) NULL DEFAULT NULL COMMENT '最低数量', + `region` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '地区', + `detailadd` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '详情地址', + `service_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '服务项目', + `is_integral` int(11) NULL DEFAULT NULL COMMENT '是否是积分商品', + `is_delete` int(1) NULL DEFAULT 0 COMMENT '-1 已删除', + `service_type` int(11) NULL DEFAULT 1 COMMENT '1送水 2其他', + `sort` int(11) NULL DEFAULT NULL COMMENT '排序', + `laundry_ids` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '站点ids', + `is_need_bucket` int(1) NULL DEFAULT 0 COMMENT '是否需要压桶 0否 1是', + `laundry_id` int(11) NULL DEFAULT NULL COMMENT '站点id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 327 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of order_taking +-- ---------------------------- + +-- ---------------------------- +-- Table structure for orders +-- ---------------------------- +DROP TABLE IF EXISTS `orders`; +CREATE TABLE `orders` ( + `orders_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '订单id', + `orders_no` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单编号', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `order_taking_id` bigint(20) NULL DEFAULT NULL COMMENT '接单id', + `pay_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '支付金额', + `state` int(4) NULL DEFAULT NULL COMMENT '订单状态0待支付1进行中2已完成3已取消', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `refund_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '退款原因', + `orders_type` int(2) NULL DEFAULT NULL COMMENT '订单种类1接单2会员', + `remarks` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注', + `order_number` int(10) NULL DEFAULT NULL COMMENT '订单数量', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新时间', + `order_score` double(10, 2) NULL DEFAULT NULL COMMENT '评分', + `vip_details_id` bigint(255) NULL DEFAULT NULL COMMENT '会员类型id', + `type` int(2) NULL DEFAULT NULL COMMENT '1会员2非会员', + `isdelete` int(2) NULL DEFAULT NULL COMMENT '假删除0显示1删除', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '市', + `district` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `details_address` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '详细地址', + `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名', + `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '电话', + `start_time` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '上门时间', + `latitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '纬度', + `longitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '经度', + `is_remind` int(11) NULL DEFAULT NULL COMMENT '是否推荐', + `rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '佣金', + `zhi_rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '直属佣金', + `zhi_user_id` int(11) NULL DEFAULT NULL COMMENT '直属用户id', + `fei_rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '非直属佣金', + `fei_user_id` int(11) NULL DEFAULT NULL COMMENT '非直属用户id', + `ping_rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '平台佣金', + `order_taking_user_id` int(11) NULL DEFAULT NULL COMMENT '接单用户id', + `code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '验收码', + `pay_way` int(11) NULL DEFAULT NULL COMMENT '支付方式 1零钱 2微信 3支付宝 4水票', + `is_shopping` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否是购物车 1是', + `sku_id` int(11) NULL DEFAULT NULL COMMENT 'sku Id', + `detail_json` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '规格详情', + `start_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '开始图片', + `end_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结束图片', + `is_transfer` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否转单 1是', + `coupon_id` int(11) NULL DEFAULT NULL COMMENT '优惠券id', + `coupon_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '优惠券金额', + `end_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结束时间', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '单价', + `is_integral` int(11) NULL DEFAULT NULL COMMENT '是否是积分订单', + `integral_num` decimal(10, 2) NULL DEFAULT NULL COMMENT '积分数量', + `role_id` int(11) NULL DEFAULT NULL COMMENT '用户水票id', + `laundry_id` int(11) NULL DEFAULT NULL COMMENT '站点id', + `laundry_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '站点收益', + `laundry_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '站点名称', + `pay_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付时间', + `laundry_rate` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '站点分成比例', + `laundry_user_id` int(11) NULL DEFAULT NULL COMMENT '站长id', + `user_type` int(1) NULL DEFAULT 1 COMMENT '下单用户类型 1用户 2师傅', + `no_code_finish_img` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '无需验证码 完成订单图片', + `is_update_bucket` int(1) NULL DEFAULT 0 COMMENT '是否已修改桶数量 0未修改 1已修改', + `is_push_meg` int(1) NULL DEFAULT 0 COMMENT '是否已推送 0否 1是', + PRIMARY KEY (`orders_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1555 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of orders +-- ---------------------------- + +-- ---------------------------- +-- Table structure for pay_details +-- ---------------------------- +DROP TABLE IF EXISTS `pay_details`; +CREATE TABLE `pay_details` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '充值id', + `classify` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类( 1app微信 2微信公众号 3微信小程序 4支付宝app 5支付宝H5)', + `order_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单编号', + `trade_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付宝支付单号', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '充值金额', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `state` int(4) NULL DEFAULT NULL COMMENT '0待支付 1支付成功 2失败', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `pay_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付时间', + `type` int(4) NULL DEFAULT NULL COMMENT '支付类型 1余额充值 2订单支付 4缴纳保证金 6购买水票 7购买优惠劵 8购买压桶', + `remark` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '备注', + `relation_id` int(11) NULL DEFAULT NULL COMMENT '关联id', + `buy_num` int(11) NULL DEFAULT NULL COMMENT '购买数量', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 663 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of pay_details +-- ---------------------------- + +-- ---------------------------- +-- Table structure for pay_order +-- ---------------------------- +DROP TABLE IF EXISTS `pay_order`; +CREATE TABLE `pay_order` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `orders_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单编号', + `trade_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付宝支付单号', + `money` decimal(11, 2) NULL DEFAULT NULL COMMENT '金币金额', + `pay_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '支付金额', + `pay_way` int(11) NULL DEFAULT NULL COMMENT '支付方式 1微信小程序 2微信公众号 3微信App 4支付宝', + `state` int(11) NULL DEFAULT NULL COMMENT '状态 0待支付 1已支付 2已退款', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `refund_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '退款原因', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新时间', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 551 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of pay_order +-- ---------------------------- + +-- ---------------------------- +-- Table structure for search +-- ---------------------------- +DROP TABLE IF EXISTS `search`; +CREATE TABLE `search` ( + `search_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '搜索id', + `search_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '搜索名称', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`search_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 135 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of search +-- ---------------------------- + +-- ---------------------------- +-- Table structure for self_coupon +-- ---------------------------- +DROP TABLE IF EXISTS `self_coupon`; +CREATE TABLE `self_coupon` ( + `coupon_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '优惠券id', + `coupon_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '优惠券名称', + `create_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `goods_ids` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品ids(多个)', + `goods_images` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品图片(多个)', + `less_money` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '优惠券面值', + `min_money` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '优惠券最低消费', + `sort` int(11) NULL DEFAULT NULL COMMENT '排序', + `status` int(11) NULL DEFAULT NULL COMMENT '状态(1开启 2关闭)', + `type` int(11) NULL DEFAULT NULL COMMENT '充值金额', + `valid_day` int(11) NULL DEFAULT NULL COMMENT '优惠券有效期限(天)', + PRIMARY KEY (`coupon_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '优惠券规则' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of self_coupon +-- ---------------------------- + +-- ---------------------------- +-- Table structure for self_coupon_issue +-- ---------------------------- +DROP TABLE IF EXISTS `self_coupon_issue`; +CREATE TABLE `self_coupon_issue` ( + `coupon_issue_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '优惠券发布id', + `coupon_id` bigint(20) NULL DEFAULT NULL COMMENT '优惠券id', + `coupon_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '优惠券名称', + `create_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `end_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '领券结束时间', + `goods_ids` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品ids(多个)', + `is_limit` int(11) NULL DEFAULT NULL COMMENT '是否限量(1限量 2不限量)', + `issue_number` int(11) NULL DEFAULT NULL COMMENT '发布数量', + `remain_number` int(11) NULL DEFAULT NULL COMMENT '剩余数量', + `start_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '领取开启时间', + `status` int(11) NULL DEFAULT NULL COMMENT '状态(1开启 2关闭)', + `type` int(11) NULL DEFAULT NULL COMMENT '优惠券类型(1通用券 2商品券)', + PRIMARY KEY (`coupon_issue_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '优惠券发布' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of self_coupon_issue +-- ---------------------------- + +-- ---------------------------- +-- Table structure for self_coupon_user +-- ---------------------------- +DROP TABLE IF EXISTS `self_coupon_user`; +CREATE TABLE `self_coupon_user` ( + `coupon_user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '优惠券用户id', + `coupon_id` bigint(20) NULL DEFAULT NULL COMMENT '优惠券id', + `coupon_issue_id` bigint(20) NULL DEFAULT NULL COMMENT '优惠券发布id', + `coupon_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '优惠券名称', + `create_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '领取时间', + `failure_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '失效时间', + `goods_ids` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品id', + `less_money` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '优惠券面值', + `min_money` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '优惠券最低消费', + `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户昵称', + `status` int(11) NULL DEFAULT NULL COMMENT '状态(1未使用 2已使用 3已过期)', + `type` int(11) NULL DEFAULT NULL COMMENT '优惠券类型(1通用券 2商品券)', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + PRIMARY KEY (`coupon_user_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1289 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '优惠券领取记录' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of self_coupon_user +-- ---------------------------- + +-- ---------------------------- +-- Table structure for sys_captcha +-- ---------------------------- +DROP TABLE IF EXISTS `sys_captcha`; +CREATE TABLE `sys_captcha` ( + `uuid` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'uuid', + `code` varchar(6) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '验证码', + `expire_time` datetime(0) NULL DEFAULT NULL COMMENT '过期时间', + PRIMARY KEY (`uuid`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统验证码' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_captcha +-- ---------------------------- + +-- ---------------------------- +-- Table structure for sys_config +-- ---------------------------- +DROP TABLE IF EXISTS `sys_config`; +CREATE TABLE `sys_config` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `param_key` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'key', + `param_value` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'value', + `status` tinyint(4) NULL DEFAULT 1 COMMENT '状态 0:隐藏 1:显示', + `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `param_key`(`param_key`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统配置信息表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_config +-- ---------------------------- +INSERT INTO `sys_config` VALUES (1, 'CLOUD_STORAGE_CONFIG_KEY', '{\"aliyunAccessKeyId\":\"\",\"aliyunAccessKeySecret\":\"\",\"aliyunBucketName\":\"\",\"aliyunDomain\":\"\",\"aliyunEndPoint\":\"\",\"aliyunPrefix\":\"\",\"qcloudBucketName\":\"\",\"qcloudDomain\":\"\",\"qcloudPrefix\":\"\",\"qcloudSecretId\":\"\",\"qcloudSecretKey\":\"\",\"qiniuAccessKey\":\"NrgMfABZxWLo5B-YYSjoE8-AZ1EISdi1Z3ubLOeZ\",\"qiniuBucketName\":\"ios-app\",\"qiniuDomain\":\"http://7xqbwh.dl1.z0.glb.clouddn.com\",\"qiniuPrefix\":\"upload\",\"qiniuSecretKey\":\"uIwJHevMRWU0VLxFvgy0tAcOdGqasdtVlJkdy6vV\",\"type\":1}', 0, '云存储配置信息'); + +-- ---------------------------- +-- Table structure for sys_dict +-- ---------------------------- +DROP TABLE IF EXISTS `sys_dict`; +CREATE TABLE `sys_dict` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字典名称', + `type` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字典类型', + `code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字典码', + `value` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字典值', + `order_num` int(11) NULL DEFAULT 0 COMMENT '排序', + `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注', + `del_flag` tinyint(4) NULL DEFAULT 0 COMMENT '删除标记 -1:已删除 0:正常', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `type`(`type`, `code`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '数据字典表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_dict +-- ---------------------------- + +-- ---------------------------- +-- Table structure for sys_log +-- ---------------------------- +DROP TABLE IF EXISTS `sys_log`; +CREATE TABLE `sys_log` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名', + `operation` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户操作', + `method` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '请求方法', + `params` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '请求参数', + `time` bigint(20) NOT NULL COMMENT '执行时长(毫秒)', + `ip` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'IP地址', + `create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 425 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统日志' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_log +-- ---------------------------- + +-- ---------------------------- +-- Table structure for sys_menu +-- ---------------------------- +DROP TABLE IF EXISTS `sys_menu`; +CREATE TABLE `sys_menu` ( + `menu_id` bigint(20) NOT NULL AUTO_INCREMENT, + `parent_id` bigint(20) NULL DEFAULT NULL COMMENT '父菜单ID,一级菜单为0', + `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '菜单名称', + `url` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '菜单URL', + `perms` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '授权(多个用逗号分隔,如:user:list,user:create)', + `type` int(11) NULL DEFAULT NULL COMMENT '类型 0:目录 1:菜单 2:按钮', + `icon` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '菜单图标', + `order_num` int(11) NULL DEFAULT NULL COMMENT '排序', + PRIMARY KEY (`menu_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 200 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '菜单管理' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_menu +-- ---------------------------- +INSERT INTO `sys_menu` VALUES (2, 102, '管理员列表', 'sys/user', NULL, 1, 'admin', 10); +INSERT INTO `sys_menu` VALUES (3, 102, '角色管理', 'sys/role', NULL, 1, 'role', 11); +INSERT INTO `sys_menu` VALUES (4, 102, '菜单管理', 'sys/menu', NULL, 1, 'menu', 12); +INSERT INTO `sys_menu` VALUES (15, 2, '查看', NULL, 'sys:user:list,sys:user:info', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (16, 2, '新增', NULL, 'sys:user:save,sys:role:select', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (17, 2, '修改', NULL, 'sys:user:update,sys:role:select', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (18, 2, '删除', NULL, 'sys:user:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (19, 3, '查看', NULL, 'sys:role:list,sys:role:info', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (20, 3, '新增', NULL, 'sys:role:save,sys:menu:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (21, 3, '修改', NULL, 'sys:role:update,sys:menu:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (22, 3, '删除', NULL, 'sys:role:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (23, 4, '查看', NULL, 'sys:menu:list,sys:menu:info', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (24, 4, '新增', NULL, 'sys:menu:save,sys:menu:select', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (25, 4, '修改', NULL, 'sys:menu:update,sys:menu:select', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (26, 4, '删除', NULL, 'sys:menu:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (32, 0, '用户中心', 'userList', '', 1, 'yonghul', 1); +INSERT INTO `sys_menu` VALUES (33, 0, '数据中心', 'home', '', 1, 'shuju', 0); +INSERT INTO `sys_menu` VALUES (34, 0, '财务中心', 'financeList', '', 1, 'caiwu', 1); +INSERT INTO `sys_menu` VALUES (35, 34, '查看', '', 'financeList:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (36, 34, '转账', '', 'financeList:transfer', 2, '', 0); +INSERT INTO `sys_menu` VALUES (37, 34, '退款', '', 'financeList:refund', 2, '', 0); +INSERT INTO `sys_menu` VALUES (39, 34, '修改', '', 'financeList:update', 2, '', 0); +INSERT INTO `sys_menu` VALUES (40, 34, '删除', '', 'financeList:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (41, 0, '消息中心', 'message', '', 1, 'xiaoxi', 2); +INSERT INTO `sys_menu` VALUES (42, 41, '查看', '', 'message:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (50, 0, '首页装修', 'bannerList', '', 1, 'shangpin', 5); +INSERT INTO `sys_menu` VALUES (51, 50, '查看', '', 'bannerList:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (52, 50, '添加', '', 'bannerList:add', 2, '', 0); +INSERT INTO `sys_menu` VALUES (53, 50, '修改', '', 'bannerList:update', 2, '', 0); +INSERT INTO `sys_menu` VALUES (54, 50, '删除', '', 'bannerList:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (57, 0, '系统配置', 'allocationList', '', 1, 'menu', 19); +INSERT INTO `sys_menu` VALUES (58, 57, '查看', '', 'allocationList:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (59, 57, '修改', '', 'allocationList:update', 2, '', 0); +INSERT INTO `sys_menu` VALUES (60, 32, '查看', '', 'userList:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (61, 32, '删除', '', 'userList:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (62, 0, '订单中心', 'orderCenter', '', 1, 'log', 1); +INSERT INTO `sys_menu` VALUES (63, 62, '查看', '', '', 2, '', 0); +INSERT INTO `sys_menu` VALUES (64, 62, '删除', '', 'orderCenter:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (72, 0, '商品列表', 'locality', '', 1, 'order', 5); +INSERT INTO `sys_menu` VALUES (73, 72, '添加', '', 'locality:add', 2, '', 0); +INSERT INTO `sys_menu` VALUES (74, 72, '查看', '', 'locality:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (75, 72, '修改', '', 'locality:update', 2, '', 0); +INSERT INTO `sys_menu` VALUES (76, 72, '删除', '', 'locality:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (77, 0, '送水工认证', 'autonym', '', 1, 'shangpin', 7); +INSERT INTO `sys_menu` VALUES (78, 77, '列表', '', 'autonym:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (79, 117, '聊天室', 'vueMchat', '', 1, 'xiaoxi', 1); +INSERT INTO `sys_menu` VALUES (90, 32, '修改余额', '', 'userList:updatejf', 2, '', 0); +INSERT INTO `sys_menu` VALUES (91, 32, '修改用户状态', '', 'userList:updateStatus', 2, '', 0); +INSERT INTO `sys_menu` VALUES (92, 77, '通过', '', 'autonym:tongguo', 2, '', 0); +INSERT INTO `sys_menu` VALUES (93, 77, '拒绝', '', 'autonym:jujue', 2, '', 0); +INSERT INTO `sys_menu` VALUES (94, 102, '升级配置', 'app', '', 1, 'sql', 1); +INSERT INTO `sys_menu` VALUES (95, 94, '查看', '', 'app:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (96, 94, '添加', '', 'app:add', 2, '', 0); +INSERT INTO `sys_menu` VALUES (97, 94, '修改', '', 'app:update', 2, '', 0); +INSERT INTO `sys_menu` VALUES (98, 94, '删除', '', 'app:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (102, 0, '系统管理', '', '', 0, 'menu', 20); +INSERT INTO `sys_menu` VALUES (108, 62, '退款', '', 'orderCenter:tuikuan', 2, '', 0); +INSERT INTO `sys_menu` VALUES (109, 62, '完成', '', 'orderCenter:wancheng', 2, '', 0); +INSERT INTO `sys_menu` VALUES (110, 32, '修改佣金', '', 'userList:updatebl', 2, '', 0); +INSERT INTO `sys_menu` VALUES (111, 117, '帮助中心', 'materialsList', '', 1, 'menu', 7); +INSERT INTO `sys_menu` VALUES (112, 111, '查看', '', 'materialsList:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (113, 111, '添加', '', 'materialsList:add', 2, '', 0); +INSERT INTO `sys_menu` VALUES (114, 111, '修改', '', 'materialsList:update', 2, '', 0); +INSERT INTO `sys_menu` VALUES (115, 111, '删除', '', 'materialsList:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (117, 0, '安全中心', '', '', 0, 'xiaoxi', 8); +INSERT INTO `sys_menu` VALUES (123, 0, '推广代理', 'recruitList', '', 1, 'mudedi', 6); +INSERT INTO `sys_menu` VALUES (124, 123, '查看', '', 'recruitList:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (125, 32, '修改保证金', '', 'userList:updatebzj', 2, '', 0); +INSERT INTO `sys_menu` VALUES (136, 0, '商品规格', 'specification', '', 1, 'renwu', 5); +INSERT INTO `sys_menu` VALUES (137, 136, '查看', '', 'specification:list', 2, '', 0); +INSERT INTO `sys_menu` VALUES (138, 136, '添加', '', 'specification:add', 2, '', 0); +INSERT INTO `sys_menu` VALUES (139, 136, '修改', '', 'specification:update', 2, '', 0); +INSERT INTO `sys_menu` VALUES (140, 136, '删除', '', 'specification:delete', 2, '', 0); +INSERT INTO `sys_menu` VALUES (141, 62, '转单', '', 'orderCenter:zhuandan', 2, '', 0); +INSERT INTO `sys_menu` VALUES (142, 0, '优惠券管理', 'couponYhq', NULL, 1, 'editor', 9); +INSERT INTO `sys_menu` VALUES (143, 142, '查看', NULL, 'couponYhq:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (144, 142, '添加', NULL, 'couponYhq:add', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (145, 142, '修改', NULL, 'couponYhq:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (146, 142, '删除', NULL, 'couponYhq:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (147, 155, '水票管理', 'waterTicket', NULL, 1, 'renwu', 0); +INSERT INTO `sys_menu` VALUES (148, 147, '查看', NULL, 'waterTicket:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (149, 147, '添加', NULL, 'waterTicket:add', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (150, 147, '修改', NULL, 'waterTicket:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (151, 147, '删除', NULL, 'waterTicket:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (152, 147, '赠送', NULL, 'waterTicket:zengsong', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (153, 0, '压桶管理', 'pressingBarrel', NULL, 1, 'peizhilb', 11); +INSERT INTO `sys_menu` VALUES (154, 153, '查看', NULL, 'pressingBarrel:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (155, 0, '水票管理', NULL, NULL, 0, 'renwu', 10); +INSERT INTO `sys_menu` VALUES (156, 155, '赠送列表', 'waterTicketList', NULL, 1, 'order', 0); +INSERT INTO `sys_menu` VALUES (157, 156, '查看', NULL, 'waterTicketList:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (158, 123, '审核', NULL, 'recruitList:shenhe', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (159, 0, '站点管理', 'laundryCertification', NULL, 1, 'shouye', 8); +INSERT INTO `sys_menu` VALUES (160, 159, '查看', NULL, 'laundryCertification:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (161, 159, '添加', NULL, 'laundryCertification:add', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (162, 159, '修改', NULL, 'laundryCertification:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (163, 159, '删除', NULL, 'laundryCertification:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (164, 0, '地图调度', 'riderScheduling', NULL, 1, 'dangdifill', 7); +INSERT INTO `sys_menu` VALUES (165, 164, '查看', NULL, 'riderScheduling:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (166, 0, '站点管理员列表', 'community', NULL, 1, 'shouye', 13); +INSERT INTO `sys_menu` VALUES (167, 166, '查看', NULL, 'community:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (168, 166, '添加', NULL, 'community:add', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (169, 166, '修改', NULL, 'community:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (170, 166, '删除', NULL, 'community:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (171, 0, '数据统计', 'homeSite', NULL, 1, 'tubiao', 14); +INSERT INTO `sys_menu` VALUES (172, 171, '查看', NULL, 'storeincomeSite:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (173, 171, '修改信息', NULL, 'storeincomeSite:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (174, 171, '提现', NULL, 'storeincomeSite:draw', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (175, 0, '订单中心', 'orderCenterSite', NULL, 1, 'order', 15); +INSERT INTO `sys_menu` VALUES (176, 175, '查看', NULL, 'orderCenterSite:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (177, 0, '商品管理', 'localitySite', NULL, 1, 'renwu', 16); +INSERT INTO `sys_menu` VALUES (178, 177, '查看', NULL, 'localitySite:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (179, 177, '添加', NULL, 'localitySite:add', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (180, 177, '修改', NULL, 'localitySite:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (181, 177, '删除', NULL, 'localitySite:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (182, 0, '地图调度', 'riderSchedulingSite', NULL, 1, 'dangdifill', 17); +INSERT INTO `sys_menu` VALUES (183, 182, '查看', NULL, 'riderSchedulingSite:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (184, 175, '转单', NULL, 'orderCenterSite:zhuandan', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (185, 175, '完成', NULL, 'orderCenterSite:wancheng', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (186, 175, '退款', NULL, 'orderCenterSite:tuikuan', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (187, 175, '删除', NULL, 'orderCenterSite:delete', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (188, 0, '库存预警', 'earlyWarning', NULL, 1, 'tixing', 5); +INSERT INTO `sys_menu` VALUES (189, 188, '查看', NULL, 'earlyWarning:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (190, 188, '修改库存', NULL, 'earlyWarning:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (191, 0, '库存预警', 'earlyWarningSite', NULL, 1, 'tixing', 18); +INSERT INTO `sys_menu` VALUES (192, 191, '查看', NULL, 'earlyWarningSite:list', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (195, 32, '修改信息', NULL, 'userList:updateXx', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (196, 77, '修改', NULL, 'autonym:update', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (197, 32, '修改会员', NULL, 'userList:updateVip', 2, NULL, 0); +INSERT INTO `sys_menu` VALUES (198, 0, '送水量排行榜', 'paihangYg', NULL, 1, 'mudedi', 6); +INSERT INTO `sys_menu` VALUES (199, 198, '查看', NULL, 'paihangYg:list', 2, NULL, 0); + +-- ---------------------------- +-- Table structure for sys_oss +-- ---------------------------- +DROP TABLE IF EXISTS `sys_oss`; +CREATE TABLE `sys_oss` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `url` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'URL地址', + `create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '文件上传' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_oss +-- ---------------------------- + +-- ---------------------------- +-- Table structure for sys_role +-- ---------------------------- +DROP TABLE IF EXISTS `sys_role`; +CREATE TABLE `sys_role` ( + `role_id` bigint(20) NOT NULL AUTO_INCREMENT, + `role_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色名称', + `remark` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注', + `create_user_id` bigint(20) NULL DEFAULT NULL COMMENT '创建者ID', + `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`role_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_role +-- ---------------------------- +INSERT INTO `sys_role` VALUES (1, '超级管理员', 'super', 10, '2021-06-04 17:38:28'); +INSERT INTO `sys_role` VALUES (4, '普通用户', '普通用户', 2, '2021-09-10 15:33:47'); +INSERT INTO `sys_role` VALUES (5, '站点管理员', '站点管理', 2, '2023-02-02 14:13:09'); + +-- ---------------------------- +-- Table structure for sys_role_menu +-- ---------------------------- +DROP TABLE IF EXISTS `sys_role_menu`; +CREATE TABLE `sys_role_menu` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `role_id` bigint(20) NULL DEFAULT NULL COMMENT '角色ID', + `menu_id` bigint(20) NULL DEFAULT NULL COMMENT '菜单ID', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 5360 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色与菜单对应关系' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_role_menu +-- ---------------------------- +INSERT INTO `sys_role_menu` VALUES (4670, 5, 171); +INSERT INTO `sys_role_menu` VALUES (4671, 5, 172); +INSERT INTO `sys_role_menu` VALUES (4672, 5, 173); +INSERT INTO `sys_role_menu` VALUES (4673, 5, 174); +INSERT INTO `sys_role_menu` VALUES (4674, 5, 175); +INSERT INTO `sys_role_menu` VALUES (4675, 5, 176); +INSERT INTO `sys_role_menu` VALUES (4676, 5, 184); +INSERT INTO `sys_role_menu` VALUES (4677, 5, 185); +INSERT INTO `sys_role_menu` VALUES (4678, 5, 186); +INSERT INTO `sys_role_menu` VALUES (4679, 5, 187); +INSERT INTO `sys_role_menu` VALUES (4680, 5, 177); +INSERT INTO `sys_role_menu` VALUES (4681, 5, 178); +INSERT INTO `sys_role_menu` VALUES (4682, 5, 179); +INSERT INTO `sys_role_menu` VALUES (4683, 5, 180); +INSERT INTO `sys_role_menu` VALUES (4684, 5, 181); +INSERT INTO `sys_role_menu` VALUES (4685, 5, 182); +INSERT INTO `sys_role_menu` VALUES (4686, 5, 183); +INSERT INTO `sys_role_menu` VALUES (4689, 5, 191); +INSERT INTO `sys_role_menu` VALUES (4690, 5, 192); +INSERT INTO `sys_role_menu` VALUES (4691, 5, -666666); +INSERT INTO `sys_role_menu` VALUES (5051, 4, 33); +INSERT INTO `sys_role_menu` VALUES (5052, 4, 60); +INSERT INTO `sys_role_menu` VALUES (5053, 4, 90); +INSERT INTO `sys_role_menu` VALUES (5054, 4, 91); +INSERT INTO `sys_role_menu` VALUES (5055, 4, 110); +INSERT INTO `sys_role_menu` VALUES (5056, 4, 125); +INSERT INTO `sys_role_menu` VALUES (5057, 4, 195); +INSERT INTO `sys_role_menu` VALUES (5058, 4, 35); +INSERT INTO `sys_role_menu` VALUES (5059, 4, 36); +INSERT INTO `sys_role_menu` VALUES (5060, 4, 37); +INSERT INTO `sys_role_menu` VALUES (5061, 4, 39); +INSERT INTO `sys_role_menu` VALUES (5062, 4, 62); +INSERT INTO `sys_role_menu` VALUES (5063, 4, 63); +INSERT INTO `sys_role_menu` VALUES (5064, 4, 64); +INSERT INTO `sys_role_menu` VALUES (5065, 4, 108); +INSERT INTO `sys_role_menu` VALUES (5066, 4, 109); +INSERT INTO `sys_role_menu` VALUES (5067, 4, 141); +INSERT INTO `sys_role_menu` VALUES (5068, 4, 41); +INSERT INTO `sys_role_menu` VALUES (5069, 4, 42); +INSERT INTO `sys_role_menu` VALUES (5070, 4, 51); +INSERT INTO `sys_role_menu` VALUES (5071, 4, 73); +INSERT INTO `sys_role_menu` VALUES (5072, 4, 74); +INSERT INTO `sys_role_menu` VALUES (5073, 4, 75); +INSERT INTO `sys_role_menu` VALUES (5074, 4, 137); +INSERT INTO `sys_role_menu` VALUES (5075, 4, 138); +INSERT INTO `sys_role_menu` VALUES (5076, 4, 139); +INSERT INTO `sys_role_menu` VALUES (5077, 4, 188); +INSERT INTO `sys_role_menu` VALUES (5078, 4, 189); +INSERT INTO `sys_role_menu` VALUES (5079, 4, 190); +INSERT INTO `sys_role_menu` VALUES (5080, 4, 123); +INSERT INTO `sys_role_menu` VALUES (5081, 4, 124); +INSERT INTO `sys_role_menu` VALUES (5082, 4, 158); +INSERT INTO `sys_role_menu` VALUES (5083, 4, 77); +INSERT INTO `sys_role_menu` VALUES (5084, 4, 78); +INSERT INTO `sys_role_menu` VALUES (5085, 4, 92); +INSERT INTO `sys_role_menu` VALUES (5086, 4, 93); +INSERT INTO `sys_role_menu` VALUES (5087, 4, 196); +INSERT INTO `sys_role_menu` VALUES (5088, 4, 164); +INSERT INTO `sys_role_menu` VALUES (5089, 4, 165); +INSERT INTO `sys_role_menu` VALUES (5090, 4, 117); +INSERT INTO `sys_role_menu` VALUES (5091, 4, 79); +INSERT INTO `sys_role_menu` VALUES (5092, 4, 111); +INSERT INTO `sys_role_menu` VALUES (5093, 4, 112); +INSERT INTO `sys_role_menu` VALUES (5094, 4, 113); +INSERT INTO `sys_role_menu` VALUES (5095, 4, 114); +INSERT INTO `sys_role_menu` VALUES (5096, 4, 115); +INSERT INTO `sys_role_menu` VALUES (5097, 4, 160); +INSERT INTO `sys_role_menu` VALUES (5098, 4, 161); +INSERT INTO `sys_role_menu` VALUES (5099, 4, 162); +INSERT INTO `sys_role_menu` VALUES (5100, 4, 142); +INSERT INTO `sys_role_menu` VALUES (5101, 4, 143); +INSERT INTO `sys_role_menu` VALUES (5102, 4, 144); +INSERT INTO `sys_role_menu` VALUES (5103, 4, 145); +INSERT INTO `sys_role_menu` VALUES (5104, 4, 146); +INSERT INTO `sys_role_menu` VALUES (5105, 4, 155); +INSERT INTO `sys_role_menu` VALUES (5106, 4, 147); +INSERT INTO `sys_role_menu` VALUES (5107, 4, 148); +INSERT INTO `sys_role_menu` VALUES (5108, 4, 149); +INSERT INTO `sys_role_menu` VALUES (5109, 4, 150); +INSERT INTO `sys_role_menu` VALUES (5110, 4, 151); +INSERT INTO `sys_role_menu` VALUES (5111, 4, 152); +INSERT INTO `sys_role_menu` VALUES (5112, 4, 156); +INSERT INTO `sys_role_menu` VALUES (5113, 4, 157); +INSERT INTO `sys_role_menu` VALUES (5114, 4, 153); +INSERT INTO `sys_role_menu` VALUES (5115, 4, 154); +INSERT INTO `sys_role_menu` VALUES (5116, 4, 167); +INSERT INTO `sys_role_menu` VALUES (5117, 4, 168); +INSERT INTO `sys_role_menu` VALUES (5118, 4, 169); +INSERT INTO `sys_role_menu` VALUES (5119, 4, 58); +INSERT INTO `sys_role_menu` VALUES (5120, 4, 95); +INSERT INTO `sys_role_menu` VALUES (5121, 4, 15); +INSERT INTO `sys_role_menu` VALUES (5122, 4, 19); +INSERT INTO `sys_role_menu` VALUES (5123, 4, 23); +INSERT INTO `sys_role_menu` VALUES (5124, 4, -666666); +INSERT INTO `sys_role_menu` VALUES (5125, 4, 32); +INSERT INTO `sys_role_menu` VALUES (5126, 4, 34); +INSERT INTO `sys_role_menu` VALUES (5127, 4, 50); +INSERT INTO `sys_role_menu` VALUES (5128, 4, 72); +INSERT INTO `sys_role_menu` VALUES (5129, 4, 136); +INSERT INTO `sys_role_menu` VALUES (5130, 4, 159); +INSERT INTO `sys_role_menu` VALUES (5131, 4, 166); +INSERT INTO `sys_role_menu` VALUES (5132, 4, 57); +INSERT INTO `sys_role_menu` VALUES (5133, 4, 102); +INSERT INTO `sys_role_menu` VALUES (5134, 4, 94); +INSERT INTO `sys_role_menu` VALUES (5135, 4, 2); +INSERT INTO `sys_role_menu` VALUES (5136, 4, 3); +INSERT INTO `sys_role_menu` VALUES (5137, 4, 4); +INSERT INTO `sys_role_menu` VALUES (5248, 1, 33); +INSERT INTO `sys_role_menu` VALUES (5249, 1, 32); +INSERT INTO `sys_role_menu` VALUES (5250, 1, 60); +INSERT INTO `sys_role_menu` VALUES (5251, 1, 61); +INSERT INTO `sys_role_menu` VALUES (5252, 1, 90); +INSERT INTO `sys_role_menu` VALUES (5253, 1, 91); +INSERT INTO `sys_role_menu` VALUES (5254, 1, 110); +INSERT INTO `sys_role_menu` VALUES (5255, 1, 125); +INSERT INTO `sys_role_menu` VALUES (5256, 1, 195); +INSERT INTO `sys_role_menu` VALUES (5257, 1, 197); +INSERT INTO `sys_role_menu` VALUES (5258, 1, 34); +INSERT INTO `sys_role_menu` VALUES (5259, 1, 35); +INSERT INTO `sys_role_menu` VALUES (5260, 1, 36); +INSERT INTO `sys_role_menu` VALUES (5261, 1, 37); +INSERT INTO `sys_role_menu` VALUES (5262, 1, 39); +INSERT INTO `sys_role_menu` VALUES (5263, 1, 40); +INSERT INTO `sys_role_menu` VALUES (5264, 1, 62); +INSERT INTO `sys_role_menu` VALUES (5265, 1, 63); +INSERT INTO `sys_role_menu` VALUES (5266, 1, 64); +INSERT INTO `sys_role_menu` VALUES (5267, 1, 108); +INSERT INTO `sys_role_menu` VALUES (5268, 1, 109); +INSERT INTO `sys_role_menu` VALUES (5269, 1, 141); +INSERT INTO `sys_role_menu` VALUES (5270, 1, 41); +INSERT INTO `sys_role_menu` VALUES (5271, 1, 42); +INSERT INTO `sys_role_menu` VALUES (5272, 1, 50); +INSERT INTO `sys_role_menu` VALUES (5273, 1, 51); +INSERT INTO `sys_role_menu` VALUES (5274, 1, 52); +INSERT INTO `sys_role_menu` VALUES (5275, 1, 53); +INSERT INTO `sys_role_menu` VALUES (5276, 1, 54); +INSERT INTO `sys_role_menu` VALUES (5277, 1, 72); +INSERT INTO `sys_role_menu` VALUES (5278, 1, 73); +INSERT INTO `sys_role_menu` VALUES (5279, 1, 74); +INSERT INTO `sys_role_menu` VALUES (5280, 1, 75); +INSERT INTO `sys_role_menu` VALUES (5281, 1, 76); +INSERT INTO `sys_role_menu` VALUES (5282, 1, 136); +INSERT INTO `sys_role_menu` VALUES (5283, 1, 137); +INSERT INTO `sys_role_menu` VALUES (5284, 1, 138); +INSERT INTO `sys_role_menu` VALUES (5285, 1, 139); +INSERT INTO `sys_role_menu` VALUES (5286, 1, 140); +INSERT INTO `sys_role_menu` VALUES (5287, 1, 188); +INSERT INTO `sys_role_menu` VALUES (5288, 1, 189); +INSERT INTO `sys_role_menu` VALUES (5289, 1, 190); +INSERT INTO `sys_role_menu` VALUES (5290, 1, 123); +INSERT INTO `sys_role_menu` VALUES (5291, 1, 124); +INSERT INTO `sys_role_menu` VALUES (5292, 1, 158); +INSERT INTO `sys_role_menu` VALUES (5293, 1, 198); +INSERT INTO `sys_role_menu` VALUES (5294, 1, 199); +INSERT INTO `sys_role_menu` VALUES (5295, 1, 77); +INSERT INTO `sys_role_menu` VALUES (5296, 1, 78); +INSERT INTO `sys_role_menu` VALUES (5297, 1, 92); +INSERT INTO `sys_role_menu` VALUES (5298, 1, 93); +INSERT INTO `sys_role_menu` VALUES (5299, 1, 196); +INSERT INTO `sys_role_menu` VALUES (5300, 1, 164); +INSERT INTO `sys_role_menu` VALUES (5301, 1, 165); +INSERT INTO `sys_role_menu` VALUES (5302, 1, 117); +INSERT INTO `sys_role_menu` VALUES (5303, 1, 79); +INSERT INTO `sys_role_menu` VALUES (5304, 1, 111); +INSERT INTO `sys_role_menu` VALUES (5305, 1, 112); +INSERT INTO `sys_role_menu` VALUES (5306, 1, 113); +INSERT INTO `sys_role_menu` VALUES (5307, 1, 114); +INSERT INTO `sys_role_menu` VALUES (5308, 1, 115); +INSERT INTO `sys_role_menu` VALUES (5309, 1, 159); +INSERT INTO `sys_role_menu` VALUES (5310, 1, 160); +INSERT INTO `sys_role_menu` VALUES (5311, 1, 161); +INSERT INTO `sys_role_menu` VALUES (5312, 1, 162); +INSERT INTO `sys_role_menu` VALUES (5313, 1, 163); +INSERT INTO `sys_role_menu` VALUES (5314, 1, 142); +INSERT INTO `sys_role_menu` VALUES (5315, 1, 143); +INSERT INTO `sys_role_menu` VALUES (5316, 1, 144); +INSERT INTO `sys_role_menu` VALUES (5317, 1, 145); +INSERT INTO `sys_role_menu` VALUES (5318, 1, 146); +INSERT INTO `sys_role_menu` VALUES (5319, 1, 155); +INSERT INTO `sys_role_menu` VALUES (5320, 1, 147); +INSERT INTO `sys_role_menu` VALUES (5321, 1, 148); +INSERT INTO `sys_role_menu` VALUES (5322, 1, 149); +INSERT INTO `sys_role_menu` VALUES (5323, 1, 150); +INSERT INTO `sys_role_menu` VALUES (5324, 1, 151); +INSERT INTO `sys_role_menu` VALUES (5325, 1, 152); +INSERT INTO `sys_role_menu` VALUES (5326, 1, 156); +INSERT INTO `sys_role_menu` VALUES (5327, 1, 157); +INSERT INTO `sys_role_menu` VALUES (5328, 1, 153); +INSERT INTO `sys_role_menu` VALUES (5329, 1, 154); +INSERT INTO `sys_role_menu` VALUES (5330, 1, 166); +INSERT INTO `sys_role_menu` VALUES (5331, 1, 167); +INSERT INTO `sys_role_menu` VALUES (5332, 1, 168); +INSERT INTO `sys_role_menu` VALUES (5333, 1, 169); +INSERT INTO `sys_role_menu` VALUES (5334, 1, 170); +INSERT INTO `sys_role_menu` VALUES (5335, 1, 57); +INSERT INTO `sys_role_menu` VALUES (5336, 1, 58); +INSERT INTO `sys_role_menu` VALUES (5337, 1, 59); +INSERT INTO `sys_role_menu` VALUES (5338, 1, 102); +INSERT INTO `sys_role_menu` VALUES (5339, 1, 94); +INSERT INTO `sys_role_menu` VALUES (5340, 1, 95); +INSERT INTO `sys_role_menu` VALUES (5341, 1, 96); +INSERT INTO `sys_role_menu` VALUES (5342, 1, 97); +INSERT INTO `sys_role_menu` VALUES (5343, 1, 98); +INSERT INTO `sys_role_menu` VALUES (5344, 1, 2); +INSERT INTO `sys_role_menu` VALUES (5345, 1, 15); +INSERT INTO `sys_role_menu` VALUES (5346, 1, 16); +INSERT INTO `sys_role_menu` VALUES (5347, 1, 17); +INSERT INTO `sys_role_menu` VALUES (5348, 1, 18); +INSERT INTO `sys_role_menu` VALUES (5349, 1, 3); +INSERT INTO `sys_role_menu` VALUES (5350, 1, 19); +INSERT INTO `sys_role_menu` VALUES (5351, 1, 20); +INSERT INTO `sys_role_menu` VALUES (5352, 1, 21); +INSERT INTO `sys_role_menu` VALUES (5353, 1, 22); +INSERT INTO `sys_role_menu` VALUES (5354, 1, 4); +INSERT INTO `sys_role_menu` VALUES (5355, 1, 23); +INSERT INTO `sys_role_menu` VALUES (5356, 1, 24); +INSERT INTO `sys_role_menu` VALUES (5357, 1, 25); +INSERT INTO `sys_role_menu` VALUES (5358, 1, 26); +INSERT INTO `sys_role_menu` VALUES (5359, 1, -666666); + +-- ---------------------------- +-- Table structure for sys_user +-- ---------------------------- +DROP TABLE IF EXISTS `sys_user`; +CREATE TABLE `sys_user` ( + `user_id` bigint(20) NOT NULL AUTO_INCREMENT, + `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名', + `password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码', + `salt` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '盐', + `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱', + `mobile` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号', + `status` tinyint(4) NULL DEFAULT NULL COMMENT '状态 0:禁用 1:正常', + `create_user_id` bigint(20) NULL DEFAULT NULL COMMENT '创建者ID', + `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `laundry_id` int(11) NULL DEFAULT NULL COMMENT '站点id', + `is_laundry` int(11) NULL DEFAULT NULL COMMENT '是否是站点管理员 1是', + PRIMARY KEY (`user_id`) USING BTREE, + UNIQUE INDEX `username`(`username`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统用户' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_user +-- ---------------------------- +INSERT INTO `sys_user` VALUES (1, 'admin', 'b1672b04628a52e4a3d7a472c691564c7b9d92e3ee38abd96f78bab92446b9a2', 'gOQpg687tI4FgraTuw2v', 'root@qq.com', '13612345678', 1, 6, '2016-11-11 11:11:11', NULL, NULL); + +-- ---------------------------- +-- Table structure for sys_user_role +-- ---------------------------- +DROP TABLE IF EXISTS `sys_user_role`; +CREATE TABLE `sys_user_role` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户ID', + `role_id` bigint(20) NULL DEFAULT NULL COMMENT '角色ID', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 34 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户与角色对应关系' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_user_role +-- ---------------------------- +INSERT INTO `sys_user_role` VALUES (2, 4, 1); +INSERT INTO `sys_user_role` VALUES (3, 5, 1); +INSERT INTO `sys_user_role` VALUES (4, 6, 1); +INSERT INTO `sys_user_role` VALUES (5, 7, 1); +INSERT INTO `sys_user_role` VALUES (7, 9, 1); +INSERT INTO `sys_user_role` VALUES (8, 8, 1); +INSERT INTO `sys_user_role` VALUES (10, 11, 1); +INSERT INTO `sys_user_role` VALUES (16, 2, 1); +INSERT INTO `sys_user_role` VALUES (17, 13, 1); +INSERT INTO `sys_user_role` VALUES (20, 10, 4); +INSERT INTO `sys_user_role` VALUES (21, 10, 1); +INSERT INTO `sys_user_role` VALUES (22, 14, 1); +INSERT INTO `sys_user_role` VALUES (23, 12, 4); +INSERT INTO `sys_user_role` VALUES (24, 15, 10); +INSERT INTO `sys_user_role` VALUES (25, 16, 10); +INSERT INTO `sys_user_role` VALUES (27, 17, 5); +INSERT INTO `sys_user_role` VALUES (29, 18, 5); +INSERT INTO `sys_user_role` VALUES (30, 1, 1); +INSERT INTO `sys_user_role` VALUES (31, 19, 5); +INSERT INTO `sys_user_role` VALUES (33, 20, 4); + +-- ---------------------------- +-- Table structure for sys_user_token +-- ---------------------------- +DROP TABLE IF EXISTS `sys_user_token`; +CREATE TABLE `sys_user_token` ( + `user_id` bigint(20) NOT NULL, + `token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'token', + `expire_time` datetime(0) NULL DEFAULT NULL COMMENT '过期时间', + `update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`user_id`) USING BTREE, + UNIQUE INDEX `token`(`token`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统用户Token' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of sys_user_token +-- ---------------------------- + +-- ---------------------------- +-- Table structure for taking_commnt +-- ---------------------------- +DROP TABLE IF EXISTS `taking_commnt`; +CREATE TABLE `taking_commnt` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '接单评论id', + `order_taking_id` bigint(20) NULL DEFAULT NULL COMMENT '接单id', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '评论内容', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `mail` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '联系方式', + `score` int(11) NULL DEFAULT NULL COMMENT '评分', + `orders_id` int(11) NULL DEFAULT NULL COMMENT '评论id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 92 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of taking_commnt +-- ---------------------------- + +-- ---------------------------- +-- Table structure for tb_coupon +-- ---------------------------- +DROP TABLE IF EXISTS `tb_coupon`; +CREATE TABLE `tb_coupon` ( + `coupon_id` int(11) NOT NULL AUTO_INCREMENT, + `coupon_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '优惠券名称', + `coupon_picture` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '优惠券图片', + `valid_days` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '有效期天数', + `min_money` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '优惠券可使用订单最低金额', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '优惠券抵扣金额', + `delete_flag` int(1) NULL DEFAULT NULL COMMENT '是否删除 0未删除 1已删除', + `is_enable` int(1) NULL DEFAULT NULL COMMENT '是否启用 0未启用 1已启用', + `buy_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '购买优惠券的价格', + `coupon_type` int(1) NULL DEFAULT NULL COMMENT '1新手赠送 2出售 3免费领取', + `max_receive` int(11) NULL DEFAULT NULL COMMENT '最多领取或购买数量(0为不限制数量)', + `coupon_num` int(11) NULL DEFAULT NULL COMMENT '优惠券数量', + PRIMARY KEY (`coupon_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of tb_coupon +-- ---------------------------- +INSERT INTO `tb_coupon` VALUES (1, '新人优惠券', 'https://img1.baidu.com/it/u=3009731526,373851691&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500', '0', '0', 10.00, 0, 1, 0.00, 1, 1, 1); +INSERT INTO `tb_coupon` VALUES (5, '超值优惠券一', 'https://kuaidi.xianmaxiong.com/file/uploadPath/2022/11/22/84e7b00eb70b9a6ba28fbac51556684c.png', '1', '10', 3.00, 0, 1, 1.99, 2, 2, 1); +INSERT INTO `tb_coupon` VALUES (6, '活动优惠券一', 'https://kuaidi.xianmaxiong.com/file/uploadPath/2022/11/23/d72cf5127bb5663d188d45af1eb052af.png', '1', '8', 5.00, 0, 1, 0.00, 3, 2, 2); +INSERT INTO `tb_coupon` VALUES (7, '新人礼包', 'https://songshui.xianmaxiong.com/file/uploadPath/2023/09/20/25f720d495bd81b1ed7e86d39ea955e3.jpg', '0', '10', 9.90, 0, 1, 0.00, 3, 2, 1); + +-- ---------------------------- +-- Table structure for tb_coupon_user +-- ---------------------------- +DROP TABLE IF EXISTS `tb_coupon_user`; +CREATE TABLE `tb_coupon_user` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `coupon_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '优惠券名称', + `coupon_picture` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '优惠券图片', + `create_time` datetime(0) NULL DEFAULT NULL COMMENT '优惠券领取时间', + `employ_time` datetime(0) NULL DEFAULT NULL COMMENT '优惠券使用时间', + `expiration_time` datetime(0) NULL DEFAULT NULL COMMENT '优惠券过期时间', + `min_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '优惠券可使用订单最低金额', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '优惠券金额', + `status` int(11) NULL DEFAULT NULL COMMENT '优惠券状态 0正常 1已使用 2已失效', + `valid_days` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '有效天数', + `coupon_id` int(11) NULL DEFAULT NULL COMMENT '优惠券id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1203 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of tb_coupon_user +-- ---------------------------- + +-- ---------------------------- +-- Table structure for tb_user +-- ---------------------------- +DROP TABLE IF EXISTS `tb_user`; +CREATE TABLE `tb_user` ( + `user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户id', + `user_name` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名', + `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号', + `avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像', + `sex` int(11) NULL DEFAULT NULL COMMENT '性别 1男 2女', + `age` int(4) NULL DEFAULT NULL COMMENT '年龄', + `open_id` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '微信小程序openId', + `wx_open_id` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '微信App openId', + `password` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新时间', + `apple_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '苹果id', + `sys_phone` int(11) NULL DEFAULT NULL COMMENT '手机类型 1安卓 2ios', + `status` int(11) NULL DEFAULT NULL COMMENT '状态 1正常 2禁用', + `platform` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源 APP 小程序 公众号', + `jifen` int(11) NULL DEFAULT NULL COMMENT '积分', + `invitation_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邀请码', + `inviter_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邀请人邀请码', + `clientid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'app消息推送', + `zhi_fu_bao_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付宝名称', + `zhi_fu_bao` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付宝账号', + `is_authentication` int(11) NULL DEFAULT NULL COMMENT '是否认证', + `shop_open_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商户小程序openId', + `details` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '简介', + `details_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '主页轮播图', + `certification_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '资质', + `wx_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '微信二维码', + `shop_img` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商铺轮播图', + `shop_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商铺名称', + `address_img` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商铺地址图', + `start_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '开始时间', + `end_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结束时间', + `shop_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商铺类型', + `longitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '经度', + `latitude` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '纬度', + `address` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '地址', + `shop_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺手机号', + `is_send_msg` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否推送消息', + `rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '佣金', + `zhi_rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '直属佣金', + `fei_rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '非直属佣金', + `is_safety_money` int(11) NULL DEFAULT NULL COMMENT '是否缴纳保证金 1是', + `is_promotion` int(11) NULL DEFAULT NULL COMMENT '是否是推广员 1是', + `is_agent` int(11) NULL DEFAULT NULL COMMENT '是否是代理商 1是', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '市', + `district` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `bucket` int(11) NULL DEFAULT 0 COMMENT '压桶数量', + `is_new_people` int(11) NULL DEFAULT 1 COMMENT '是否是新人 1是 0不是', + `laundry_id` int(11) NULL DEFAULT NULL COMMENT '站点id', + PRIMARY KEY (`user_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 116015 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of tb_user +-- ---------------------------- +INSERT INTO `tb_user` VALUES (1, '官方', '13000000000', NULL, 1, NULL, NULL, NULL, NULL, '2021-08-28 15:38:05', '2023-06-15 16:07:25', NULL, NULL, 1, 'H5', NULL, '666666', '666666', NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0.70, 0.10, 0.05, 0, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL); + +-- ---------------------------- +-- Table structure for tickets +-- ---------------------------- +DROP TABLE IF EXISTS `tickets`; +CREATE TABLE `tickets` ( + `tickets_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '水票id', + `buy_money` decimal(10, 2) NULL DEFAULT NULL COMMENT '购买价格', + `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '水票标题', + `relation_id` int(11) NULL DEFAULT NULL COMMENT '关联的商品id', + `tickets_img` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '水票图片', + `is_enable` int(1) NULL DEFAULT 1 COMMENT '是否启用 1启用 0 不启用', + `num` int(11) NULL DEFAULT NULL COMMENT '数量', + `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `is_delete` int(1) NULL DEFAULT 0 COMMENT '是否删除', + `sort` int(1) NULL DEFAULT 0 COMMENT '排序', + PRIMARY KEY (`tickets_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of tickets +-- ---------------------------- + +-- ---------------------------- +-- Table structure for tickets_give_record +-- ---------------------------- +DROP TABLE IF EXISTS `tickets_give_record`; +CREATE TABLE `tickets_give_record` ( + `record_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '记录id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `user_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户昵称', + `tickets_id` int(11) NULL DEFAULT NULL COMMENT '水票id', + `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `give_num` int(11) NULL DEFAULT NULL COMMENT '赠送数量', + `tickets_title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '水票标题', + PRIMARY KEY (`record_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of tickets_give_record +-- ---------------------------- + +-- ---------------------------- +-- Table structure for tickets_user_role +-- ---------------------------- +DROP TABLE IF EXISTS `tickets_user_role`; +CREATE TABLE `tickets_user_role` ( + `role_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '关联id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `tickets_id` int(11) NULL DEFAULT NULL COMMENT '水票id', + `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `stock` int(11) NULL DEFAULT NULL COMMENT '购买数量', + `num` int(11) NULL DEFAULT 0 COMMENT '已用数量', + PRIMARY KEY (`role_id`) USING BTREE, + INDEX `role_id`(`role_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 118 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of tickets_user_role +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_browse +-- ---------------------------- +DROP TABLE IF EXISTS `user_browse`; +CREATE TABLE `user_browse` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `by_browse_id` bigint(20) NULL DEFAULT NULL COMMENT '浏览用户id', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新时间', + `taking_id` bigint(20) NULL DEFAULT NULL COMMENT '接单id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1650 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_browse +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_certification +-- ---------------------------- +DROP TABLE IF EXISTS `user_certification`; +CREATE TABLE `user_certification` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户实名认证id', + `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '真实姓名', + `id_number` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '身份证号码', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `create_time` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `front` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '正面照', + `back` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '反面照', + `status` int(255) NULL DEFAULT NULL COMMENT '0审核中1审核成功2拒绝', + `remek` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '说明', + `update_time` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改时间', + `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '电话', + `birth` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '出生日期', + `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '性别', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 130 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_certification +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_follow +-- ---------------------------- +DROP TABLE IF EXISTS `user_follow`; +CREATE TABLE `user_follow` ( + `follow_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `follow_user_id` bigint(20) NULL DEFAULT NULL COMMENT '关注用户id', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`follow_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 161 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_follow +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_integral +-- ---------------------------- +DROP TABLE IF EXISTS `user_integral`; +CREATE TABLE `user_integral` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `integral_num` int(11) NULL DEFAULT NULL COMMENT '积分数量', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 853 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_integral +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_integral_details +-- ---------------------------- +DROP TABLE IF EXISTS `user_integral_details`; +CREATE TABLE `user_integral_details` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '积分详情id', + `content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '内容', + `classify` int(255) NULL DEFAULT NULL COMMENT '获取类型 1签到 2积分兑换优惠券 3系统赠送积分', + `type` int(255) NULL DEFAULT NULL COMMENT '分类 1增加 2减少', + `num` int(11) NULL DEFAULT NULL COMMENT '数量', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `create_time` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间', + `day` int(11) NULL DEFAULT NULL COMMENT '连续签到天数', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1337 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_integral_details +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_money +-- ---------------------------- +DROP TABLE IF EXISTS `user_money`; +CREATE TABLE `user_money` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '钱包id', + `money` decimal(10, 2) NULL COMMENT '钱包金额', + `user_id` bigint(11) NULL DEFAULT NULL COMMENT '用户id', + `safety_money` decimal(10, 2) NULL COMMENT '保证金', + `order_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单号', + `safety_money_way` int(11) NULL DEFAULT NULL COMMENT '支付方式 1微信 2支付宝', + `rate_money` decimal(10, 2) NULL COMMENT '佣金收益', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `user_id`(`user_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 998 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_money +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_money_details +-- ---------------------------- +DROP TABLE IF EXISTS `user_money_details`; +CREATE TABLE `user_money_details` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '钱包详情id', + `user_id` int(11) NULL DEFAULT NULL COMMENT '用户id', + `by_user_id` int(11) NULL DEFAULT NULL COMMENT '邀请用户id', + `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '标题', + `classify` int(11) NULL DEFAULT NULL COMMENT '1注册 2购买 3提现 5购买水票 6购买优惠券 8购买桶', + `type` int(11) NULL DEFAULT NULL COMMENT '类型(1充值 2.提现)', + `state` int(11) NULL DEFAULT 1 COMMENT '状态 1待支付 2已到账 3取消', + `money` decimal(10, 2) NULL DEFAULT NULL COMMENT '金额', + `content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '内容', + `create_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '创建时间', + `orders_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '订单编号', + `pay_type` int(1) NULL DEFAULT NULL COMMENT '支付类型 1水贝 2微信 3支付宝 4水票支付', + `relation_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '关联信息或id', + `laundry_id` int(11) NULL DEFAULT NULL COMMENT '站点id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 2346 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_money_details +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_vip +-- ---------------------------- +DROP TABLE IF EXISTS `user_vip`; +CREATE TABLE `user_vip` ( + `vip_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '会员id', + `vip_name_type` int(2) NULL DEFAULT NULL COMMENT '会员类型0月1季2年', + `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户id', + `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '购买时间', + `end_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '到期时间', + `is_vip` int(255) NULL DEFAULT NULL COMMENT '1是会员2不是', + PRIMARY KEY (`vip_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 30 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_vip +-- ---------------------------- + +-- ---------------------------- +-- Table structure for user_visitor +-- ---------------------------- +DROP TABLE IF EXISTS `user_visitor`; +CREATE TABLE `user_visitor` ( + `id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '访客id', + `user_id` bigint(32) NULL DEFAULT NULL COMMENT '用户id', + `by_user_id` bigint(32) NULL DEFAULT NULL COMMENT '访问用户id', + `update_time` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 706 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of user_visitor +-- ---------------------------- + +-- ---------------------------- +-- Table structure for vip_details +-- ---------------------------- +DROP TABLE IF EXISTS `vip_details`; +CREATE TABLE `vip_details` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `vip_name_type` int(2) NULL DEFAULT NULL COMMENT '会员类型0月1季2年', + `money` decimal(10, 0) NULL DEFAULT NULL COMMENT '会员价格', + `vip_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '会员名称', + `award` decimal(10, 2) NULL DEFAULT NULL COMMENT '邀请赏金', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of vip_details +-- ---------------------------- +INSERT INTO `vip_details` VALUES (2, 1, 3, '季会员', 0.01); +INSERT INTO `vip_details` VALUES (3, 2, 4, '年会员', 0.01); +INSERT INTO `vip_details` VALUES (8, 0, 1, '月会员', 0.01); + +-- ---------------------------- +-- Table structure for vip_discount +-- ---------------------------- +DROP TABLE IF EXISTS `vip_discount`; +CREATE TABLE `vip_discount` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', + `discount` decimal(10, 0) NULL DEFAULT NULL COMMENT '优惠金币', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of vip_discount +-- ---------------------------- +INSERT INTO `vip_discount` VALUES (1, 3); + +SET FOREIGN_KEY_CHECKS = 1; diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..af0151a --- /dev/null +++ b/pom.xml @@ -0,0 +1,496 @@ + + + 4.0.0 + com.sqx + songshui + 1.0 + jar + 送水 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.11 + + + + UTF-8 + UTF-8 + 1.8 + 3.2.0 + 8.0.17 + 4.0 + 11.2.0.3 + 1.1.13 + 2.3.0 + 2.6 + 1.2.2 + 2.5 + 1.10 + 1.10 + 1.10.1 + 0.7.0 + 0.0.9 + 7.2.23 + 3.4.0 + 4.4 + 2.7.0 + 2.9.9 + 2.8.5 + 1.2.83 + 4.1.1 + 1.18.4 + + + + + + + + + + + org + jaudiotagger + 2.0.3 + + + org.mybatis + mybatis-typehandlers-jsr310 + 1.0.1 + + + org.hibernate.validator + hibernate-validator + 6.2.3.Final + + + org.springframework + spring-websocket + 5.1.2.RELEASE + + + cn.afterturn + easypoi-spring-boot-starter + 4.0.0 + + + net.java.dev.jna + jna + 5.5.0 + + + net.java.dev.jna + jna-platform + 5.5.0 + + + + com.alibaba + druid + 1.1.10 + + + + com.auth0 + java-jwt + 3.8.3 + + + com.auth0 + jwks-rsa + 0.12.0 + + + io.jsonwebtoken + jjwt + 0.9.0 + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + + + + org.apache.poi + poi + 4.0.1 + + + + org.apache.poi + poi-ooxml + 4.0.1 + + + com.github.qcloudsms + qcloudsms + 1.0.6 + + + + com.aliyun + aliyun-java-sdk-core + 4.5.3 + + + com.aliyun.oss + aliyun-sdk-oss + 3.4.0 + + + + com.alipay.sdk + alipay-sdk-java + 4.10.29.ALL + + + com.github.wxpay + wxpay-sdk + 0.0.3 + + + com.github.liyiorg + weixin-popular + 2.8.25 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-aop + + + org.springframework + spring-context-support + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + + + + com.baomidou + mybatis-plus-boot-starter + ${mybatisplus.version} + + + com.baomidou + mybatis-plus-generator + + + + + mysql + mysql-connector-java + ${mysql.version} + + + + com.oracle + ojdbc6 + ${oracle.version} + + + + com.microsoft.sqlserver + sqljdbc4 + ${mssql.version} + + + + org.postgresql + postgresql + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + org.quartz-scheduler + quartz + ${quartz.version} + + + com.mchange + c3p0 + + + + + commons-lang + commons-lang + ${commons.lang.version} + + + commons-fileupload + commons-fileupload + ${commons.fileupload.version} + + + commons-io + commons-io + ${commons.io.version} + + + commons-codec + commons-codec + ${commons.codec.version} + + + commons-configuration + commons-configuration + ${commons.configuration.version} + + + org.apache.shiro + shiro-core + ${shiro.version} + + + org.apache.shiro + shiro-spring + ${shiro.version} + + + com.github.axet + kaptcha + ${kaptcha.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + com.qiniu + qiniu-java-sdk + ${qiniu.version} + + + com.qcloud + cos_api + ${qcloud.cos.version} + + + org.slf4j + slf4j-log4j12 + + + + + joda-time + joda-time + ${joda.time.version} + + + com.google.code.gson + gson + ${gson.version} + + + com.alibaba + fastjson + ${fastjson.version} + + + cn.hutool + hutool-all + ${hutool.version} + + + org.projectlombok + lombok + ${lombok.version} + + + + + + com.google.zxing + core + 3.3.3 + + + + com.google.zxing + javase + 3.3.3 + + + com.github.binarywang + weixin-java-mp + 3.6.0 + + + com.github.binarywang + weixin-java-pay + 3.6.0 + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.2.5 + + + mybatis-spring + org.mybatis + + + mybatis + org.mybatis + + + + + com.github.dozermapper + dozer-core + 6.4.1 + + + com.getui.push + restful-sdk + 1.0.0.1 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.gavaghan + geodesy + 1.1.3 + + + + + + + + + + ${project.artifactId} + + + org.apache.maven.wagon + wagon-ssh + 2.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + org.codehaus.mojo + wagon-maven-plugin + 1.0 + + + + + com.spotify + docker-maven-plugin + 0.4.14 + + + + + + + + + + sqx/fast + ${project.basedir} + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + + + + + + public + aliyun nexus + http://maven.aliyun.com/nexus/content/groups/public/ + + true + + + + + + public + aliyun nexus + http://maven.aliyun.com/nexus/content/groups/public/ + + true + + + false + + + + + diff --git a/src/main/java/com/sqx/SqxApplication.java b/src/main/java/com/sqx/SqxApplication.java new file mode 100644 index 0000000..4cc2fb8 --- /dev/null +++ b/src/main/java/com/sqx/SqxApplication.java @@ -0,0 +1,29 @@ +package com.sqx; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Slf4j +@EnableScheduling +@EnableAsync +@EnableTransactionManagement +@SpringBootApplication +public class SqxApplication { + + public static void main(String[] args) { + SpringApplication.run(SqxApplication.class, args); + log.info("(♥◠‿◠)ノ゙ 送水项目启动成功 ლ(´ڡ`ლ)゙ \n"+ + " _ \n" + + " | | \n" + + " ___ | | __\n" + + " / _ \\| |/ /\n" + + "| (_) | < \n" + + " \\___/|_|\\_\\"); + + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/common/annotation/SysLog.java b/src/main/java/com/sqx/common/annotation/SysLog.java new file mode 100644 index 0000000..70cec15 --- /dev/null +++ b/src/main/java/com/sqx/common/annotation/SysLog.java @@ -0,0 +1,19 @@ +package com.sqx.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 系统日志注解 + * + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface SysLog { + + String value() default ""; +} diff --git a/src/main/java/com/sqx/common/aspect/RedisAspect.java b/src/main/java/com/sqx/common/aspect/RedisAspect.java new file mode 100644 index 0000000..896c0f7 --- /dev/null +++ b/src/main/java/com/sqx/common/aspect/RedisAspect.java @@ -0,0 +1,37 @@ +package com.sqx.common.aspect; + +import com.sqx.common.exception.SqxException; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +/** + * Redis切面处理类 + * + */ +@Aspect +@Configuration +public class RedisAspect { + private Logger logger = LoggerFactory.getLogger(getClass()); + //是否开启redis缓存 true开启 false关闭 + @Value("${spring.redis.open: false}") + private boolean open; + + @Around("execution(* com.sqx.common.utils.RedisUtils.*(..))") + public Object around(ProceedingJoinPoint point) throws Throwable { + Object result = null; + if(open){ + try{ + result = point.proceed(); + }catch (Exception e){ + logger.error("redis error", e); + throw new SqxException("Redis服务异常"); + } + } + return result; + } +} diff --git a/src/main/java/com/sqx/common/aspect/SysLogAspect.java b/src/main/java/com/sqx/common/aspect/SysLogAspect.java new file mode 100644 index 0000000..b0f5ac8 --- /dev/null +++ b/src/main/java/com/sqx/common/aspect/SysLogAspect.java @@ -0,0 +1,92 @@ +package com.sqx.common.aspect; + +import com.google.gson.Gson; +import com.sqx.common.utils.HttpContextUtils; +import com.sqx.common.utils.IPUtils; +import com.sqx.common.annotation.SysLog; +import com.sqx.modules.sys.entity.SysLogEntity; +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.service.SysLogService; +import org.apache.shiro.SecurityUtils; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; +import java.util.Date; + + +/** + * 系统日志,切面处理类 + * + */ +@Aspect +@Component +public class SysLogAspect { + @Autowired + private SysLogService sysLogService; + + @Pointcut("@annotation(com.sqx.common.annotation.SysLog)") + public void logPointCut() { + + } + + @Around("logPointCut()") + public Object around(ProceedingJoinPoint point) throws Throwable { + long beginTime = System.currentTimeMillis(); + //执行方法 + Object result = point.proceed(); + //执行时长(毫秒) + long time = System.currentTimeMillis() - beginTime; + + //保存日志 + saveSysLog(point, time); + + return result; + } + + private void saveSysLog(ProceedingJoinPoint joinPoint, long time) { + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + + SysLogEntity sysLog = new SysLogEntity(); + SysLog syslog = method.getAnnotation(SysLog.class); + if(syslog != null){ + //注解上的描述 + sysLog.setOperation(syslog.value()); + } + + //请求的方法名 + String className = joinPoint.getTarget().getClass().getName(); + String methodName = signature.getName(); + sysLog.setMethod(className + "." + methodName + "()"); + + //请求的参数 + Object[] args = joinPoint.getArgs(); + try{ + String params = new Gson().toJson(args); + sysLog.setParams(params); + }catch (Exception e){ + + } + + //获取request + HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); + //设置IP地址 + sysLog.setIp(IPUtils.getIpAddr(request)); + + //用户名 + String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername(); + sysLog.setUsername(username); + + sysLog.setTime(time); + sysLog.setCreateDate(new Date()); + //保存系统日志 + sysLogService.save(sysLog); + } +} diff --git a/src/main/java/com/sqx/common/exception/SqxException.java b/src/main/java/com/sqx/common/exception/SqxException.java new file mode 100644 index 0000000..f343af5 --- /dev/null +++ b/src/main/java/com/sqx/common/exception/SqxException.java @@ -0,0 +1,52 @@ +package com.sqx.common.exception; + +/** + * 自定义异常 + * + */ +public class SqxException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private String msg; + private int code = 500; + + public SqxException(String msg) { + super(msg); + this.msg = msg; + } + + public SqxException(String msg, Throwable e) { + super(msg, e); + this.msg = msg; + } + + public SqxException(String msg, int code) { + super(msg); + this.msg = msg; + this.code = code; + } + + public SqxException(String msg, int code, Throwable e) { + super(msg, e); + this.msg = msg; + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + +} diff --git a/src/main/java/com/sqx/common/exception/SqxExceptionHandler.java b/src/main/java/com/sqx/common/exception/SqxExceptionHandler.java new file mode 100644 index 0000000..a171e7d --- /dev/null +++ b/src/main/java/com/sqx/common/exception/SqxExceptionHandler.java @@ -0,0 +1,55 @@ +package com.sqx.common.exception; + +import com.sqx.common.utils.Result; +import org.apache.shiro.authz.AuthorizationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.NoHandlerFoundException; + +/** + * 异常处理器 + * + */ +@RestControllerAdvice +public class SqxExceptionHandler { + private Logger logger = LoggerFactory.getLogger(getClass()); + + /** + * 处理自定义异常 + */ + @ExceptionHandler(SqxException.class) + public Result handleException(SqxException e){ + Result r = new Result(); + r.put("code", e.getCode()); + r.put("msg", e.getMessage()); + + return r; + } + + @ExceptionHandler(NoHandlerFoundException.class) + public Result handlerNoFoundException(Exception e) { + logger.error(e.getMessage(), e); + return Result.error(404, "路径不存在,请检查路径是否正确"); + } + + @ExceptionHandler(DuplicateKeyException.class) + public Result handleDuplicateKeyException(DuplicateKeyException e){ + logger.error(e.getMessage(), e); + return Result.error("数据库中已存在该记录"); + } + + @ExceptionHandler(AuthorizationException.class) + public Result handleAuthorizationException(AuthorizationException e){ + logger.error(e.getMessage(), e); + return Result.error("没有权限,请联系管理员授权"); + } + + @ExceptionHandler(Exception.class) + public Result handleException(Exception e){ + logger.error(e.getMessage(), e); + return Result.error(); + } +} diff --git a/src/main/java/com/sqx/common/utils/ConfigConstant.java b/src/main/java/com/sqx/common/utils/ConfigConstant.java new file mode 100644 index 0000000..6e18daf --- /dev/null +++ b/src/main/java/com/sqx/common/utils/ConfigConstant.java @@ -0,0 +1,12 @@ +package com.sqx.common.utils; + +/** + * 系统参数相关Key + * + */ +public class ConfigConstant { + /** + * 云存储配置KEY + */ + public final static String CLOUD_STORAGE_CONFIG_KEY = "CLOUD_STORAGE_CONFIG_KEY"; +} diff --git a/src/main/java/com/sqx/common/utils/Constant.java b/src/main/java/com/sqx/common/utils/Constant.java new file mode 100644 index 0000000..436bcb1 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/Constant.java @@ -0,0 +1,110 @@ +package com.sqx.common.utils; + +/** + * 常量 + * + */ +public class Constant { + /** 超级管理员ID */ + public static final int SUPER_ADMIN = 1; + /** + * 当前页码 + */ + public static final String PAGE = "page"; + /** + * 每页显示记录数 + */ + public static final String LIMIT = "limit"; + /** + * 排序字段 + */ + public static final String ORDER_FIELD = "sidx"; + /** + * 排序方式 + */ + public static final String ORDER = "order"; + /** + * 升序 + */ + public static final String ASC = "asc"; + /** + * 菜单类型 + */ + public enum MenuType { + /** + * 目录 + */ + CATALOG(0), + /** + * 菜单 + */ + MENU(1), + /** + * 按钮 + */ + BUTTON(2); + + private int value; + + MenuType(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + /** + * 定时任务状态 + */ + public enum ScheduleStatus { + /** + * 正常 + */ + NORMAL(0), + /** + * 暂停 + */ + PAUSE(1); + + private int value; + + ScheduleStatus(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + /** + * 云服务商 + */ + public enum CloudService { + /** + * 七牛云 + */ + QINIU(1), + /** + * 阿里云 + */ + ALIYUN(2), + /** + * 腾讯云 + */ + QCLOUD(3); + + private int value; + + CloudService(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + +} diff --git a/src/main/java/com/sqx/common/utils/DateUtils.java b/src/main/java/com/sqx/common/utils/DateUtils.java new file mode 100644 index 0000000..9d51649 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/DateUtils.java @@ -0,0 +1,157 @@ +package com.sqx.common.utils; + +import org.apache.commons.lang.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 日期处理 + * + */ +public class DateUtils { + /** 时间格式(yyyy-MM-dd) */ + public final static String DATE_PATTERN = "yyyy-MM-dd"; + /** 时间格式(yyyy-MM-dd HH:mm:ss) */ + public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + /** + * 日期格式化 日期格式为:yyyy-MM-dd + * @param date 日期 + * @return 返回yyyy-MM-dd格式日期 + */ + public static String format(Date date) { + return format(date, DATE_TIME_PATTERN); + } + + /** + * 日期格式化 日期格式为:yyyy-MM-dd + * @param date 日期 + * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN + * @return 返回yyyy-MM-dd格式日期 + */ + public static String format(Date date, String pattern) { + if(date != null){ + SimpleDateFormat df = new SimpleDateFormat(pattern); + return df.format(date); + } + return null; + } + + /** + * 字符串转换成日期 + * @param strDate 日期字符串 + * @param pattern 日期的格式,如:DateUtils.DATE_TIME_PATTERN + */ + public static Date stringToDate(String strDate, String pattern) { + if (StringUtils.isBlank(strDate)){ + return null; + } + + DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern); + return fmt.parseLocalDateTime(strDate).toDate(); + } + + /** + * 根据周数,获取开始日期、结束日期 + * @param week 周期 0本周,-1上周,-2上上周,1下周,2下下周 + * @return 返回date[0]开始日期、date[1]结束日期 + */ + public static Date[] getWeekStartAndEnd(int week) { + DateTime dateTime = new DateTime(); + LocalDate date = new LocalDate(dateTime.plusWeeks(week)); + + date = date.dayOfWeek().withMinimumValue(); + Date beginDate = date.toDate(); + Date endDate = date.plusDays(6).toDate(); + return new Date[]{beginDate, endDate}; + } + + /** + * 对日期的【秒】进行加/减 + * + * @param date 日期 + * @param seconds 秒数,负数为减 + * @return 加/减几秒后的日期 + */ + public static Date addDateSeconds(Date date, int seconds) { + DateTime dateTime = new DateTime(date); + return dateTime.plusSeconds(seconds).toDate(); + } + + /** + * 对日期的【分钟】进行加/减 + * + * @param date 日期 + * @param minutes 分钟数,负数为减 + * @return 加/减几分钟后的日期 + */ + public static Date addDateMinutes(Date date, int minutes) { + DateTime dateTime = new DateTime(date); + return dateTime.plusMinutes(minutes).toDate(); + } + + /** + * 对日期的【小时】进行加/减 + * + * @param date 日期 + * @param hours 小时数,负数为减 + * @return 加/减几小时后的日期 + */ + public static Date addDateHours(Date date, int hours) { + DateTime dateTime = new DateTime(date); + return dateTime.plusHours(hours).toDate(); + } + + /** + * 对日期的【天】进行加/减 + * + * @param date 日期 + * @param days 天数,负数为减 + * @return 加/减几天后的日期 + */ + public static Date addDateDays(Date date, int days) { + DateTime dateTime = new DateTime(date); + return dateTime.plusDays(days).toDate(); + } + + /** + * 对日期的【周】进行加/减 + * + * @param date 日期 + * @param weeks 周数,负数为减 + * @return 加/减几周后的日期 + */ + public static Date addDateWeeks(Date date, int weeks) { + DateTime dateTime = new DateTime(date); + return dateTime.plusWeeks(weeks).toDate(); + } + + /** + * 对日期的【月】进行加/减 + * + * @param date 日期 + * @param months 月数,负数为减 + * @return 加/减几月后的日期 + */ + public static Date addDateMonths(Date date, int months) { + DateTime dateTime = new DateTime(date); + return dateTime.plusMonths(months).toDate(); + } + + /** + * 对日期的【年】进行加/减 + * + * @param date 日期 + * @param years 年数,负数为减 + * @return 加/减几年后的日期 + */ + public static Date addDateYears(Date date, int years) { + DateTime dateTime = new DateTime(date); + return dateTime.plusYears(years).toDate(); + } +} diff --git a/src/main/java/com/sqx/common/utils/HttpContextUtils.java b/src/main/java/com/sqx/common/utils/HttpContextUtils.java new file mode 100644 index 0000000..82c860e --- /dev/null +++ b/src/main/java/com/sqx/common/utils/HttpContextUtils.java @@ -0,0 +1,24 @@ +package com.sqx.common.utils; + +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +public class HttpContextUtils { + + public static HttpServletRequest getHttpServletRequest() { + return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + } + + public static String getDomain(){ + HttpServletRequest request = getHttpServletRequest(); + StringBuffer url = request.getRequestURL(); + return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); + } + + public static String getOrigin(){ + HttpServletRequest request = getHttpServletRequest(); + return request.getHeader("Origin"); + } +} diff --git a/src/main/java/com/sqx/common/utils/IPUtils.java b/src/main/java/com/sqx/common/utils/IPUtils.java new file mode 100644 index 0000000..0fbd6c9 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/IPUtils.java @@ -0,0 +1,49 @@ +package com.sqx.common.utils; + +import com.alibaba.druid.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; + +/** + * IP地址 + * + */ +public class IPUtils { + private static Logger logger = LoggerFactory.getLogger(IPUtils.class); + + /** + * 获取IP地址 + * + * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 + * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 + */ + public static String getIpAddr(HttpServletRequest request) { + String ip = null; + try { + ip = request.getHeader("x-forwarded-for"); + if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + } + if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + } catch (Exception e) { + logger.error("IPUtils ERROR ", e); + } + + + return ip; + } + +} diff --git a/src/main/java/com/sqx/common/utils/MapUtils.java b/src/main/java/com/sqx/common/utils/MapUtils.java new file mode 100644 index 0000000..14a1558 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/MapUtils.java @@ -0,0 +1,17 @@ +package com.sqx.common.utils; + +import java.util.HashMap; + + +/** + * Map工具类 + * + */ +public class MapUtils extends HashMap { + + @Override + public MapUtils put(String key, Object value) { + super.put(key, value); + return this; + } +} diff --git a/src/main/java/com/sqx/common/utils/MetaObjectHandler.java b/src/main/java/com/sqx/common/utils/MetaObjectHandler.java new file mode 100644 index 0000000..dafd368 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/MetaObjectHandler.java @@ -0,0 +1,46 @@ +package com.sqx.common.utils; + +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.Objects; + +@Component +@Slf4j +public class MetaObjectHandler implements com.baomidou.mybatisplus.core.handlers.MetaObjectHandler { + + /** + * 插入操作时自动填充 + * createTime 和 updateTime 必须是Date类型的字段 + * + * @param metaObject + */ + @Override + public void insertFill(MetaObject metaObject) { + Object createTime = getFieldValByName("createTime", metaObject); + if (Objects.isNull(createTime)) { + //只有被FieldFill标记的字段才会执行自动填充 + setInsertFieldValByName("createTime", new Date(), metaObject); + } + Object updateTime = getFieldValByName("updateTime", metaObject); + if (Objects.isNull(updateTime)) { + setInsertFieldValByName("updateTime", new Date(), metaObject); + } + } + + /** + * 更新操作时自动填充 + * + * @param metaObject + */ + @Override + public void updateFill(MetaObject metaObject) { + Object updateTime = getFieldValByName("updateTime", metaObject); + if (Objects.isNull(updateTime)) { + //只有被FieldFill标记的字段才会执行自动填充 + setUpdateFieldValByName("updateTime", new Date(), metaObject); + } + } +} diff --git a/src/main/java/com/sqx/common/utils/PageUtils.java b/src/main/java/com/sqx/common/utils/PageUtils.java new file mode 100644 index 0000000..6e522c0 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/PageUtils.java @@ -0,0 +1,101 @@ +package com.sqx.common.utils; + +import com.baomidou.mybatisplus.core.metadata.IPage; + +import java.io.Serializable; +import java.util.List; + +/** + * 分页工具类 + * + */ +public class PageUtils implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 总记录数 + */ + private int totalCount; + /** + * 每页记录数 + */ + private int pageSize; + /** + * 总页数 + */ + private int totalPage; + /** + * 当前页数 + */ + private int currPage; + /** + * 列表数据 + */ + private List list; + + /** + * 分页 + * @param list 列表数据 + * @param totalCount 总记录数 + * @param pageSize 每页记录数 + * @param currPage 当前页数 + */ + public PageUtils(List list, int totalCount, int pageSize, int currPage) { + this.list = list; + this.totalCount = totalCount; + this.pageSize = pageSize; + this.currPage = currPage; + this.totalPage = (int)Math.ceil((double)totalCount/pageSize); + } + + /** + * 分页 + */ + public PageUtils(IPage page) { + this.list = page.getRecords(); + this.totalCount = (int)page.getTotal(); + this.pageSize = (int)page.getSize(); + this.currPage = (int)page.getCurrent(); + this.totalPage = (int)page.getPages(); + } + + public int getTotalCount() { + return totalCount; + } + + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + + public int getPageSize() { + return pageSize; + } + + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + public int getTotalPage() { + return totalPage; + } + + public void setTotalPage(int totalPage) { + this.totalPage = totalPage; + } + + public int getCurrPage() { + return currPage; + } + + public void setCurrPage(int currPage) { + this.currPage = currPage; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + +} diff --git a/src/main/java/com/sqx/common/utils/QRCodeUtil.java b/src/main/java/com/sqx/common/utils/QRCodeUtil.java new file mode 100644 index 0000000..e4d06fa --- /dev/null +++ b/src/main/java/com/sqx/common/utils/QRCodeUtil.java @@ -0,0 +1,175 @@ +package com.sqx.common.utils; + +import cn.hutool.extra.qrcode.BufferedImageLuminanceSource; +import com.google.zxing.*; +import com.google.zxing.Result; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.common.HybridBinarizer; +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.geom.RoundRectangle2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.util.Hashtable; + +/** + * 二维码生成解析工具类 + + * @date 2020/02/12 09:37 + */ +public class QRCodeUtil { + + //编码格式,采用utf-8 + private static final String UNICODE = "utf-8"; + //图片格式 + private static final String FORMAT = "JPG"; + //二维码宽度,单位:像素pixels + private static final int QRCODE_WIDTH = 300; + //二维码高度,单位:像素pixels + private static final int QRCODE_HEIGHT = 300; + //LOGO宽度,单位:像素pixels + private static final int LOGO_WIDTH = 100; + //LOGO高度,单位:像素pixels + private static final int LOGO_HEIGHT = 100; + + /** + * 生成二维码图片 + * @param content 二维码内容 + * @param logoPath 图片地址 + * @param needCompress 是否压缩 + * @return + * @throws Exception + */ + private static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception { + Hashtable hints = new Hashtable(); + hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); + hints.put(EncodeHintType.CHARACTER_SET, UNICODE); + hints.put(EncodeHintType.MARGIN, 1); + BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT, + hints); + int width = bitMatrix.getWidth(); + int height = bitMatrix.getHeight(); + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); + } + } + if (logoPath == null || "".equals(logoPath)) { + return image; + } + // 插入图片 + QRCodeUtil.insertImage(image, logoPath, needCompress); + return image; + } + + /** + * 插入LOGO + * @param source 二维码图片 + * @param logoPath LOGO图片地址 + * @param needCompress 是否压缩 + * @throws Exception + */ + private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception { + File file = new File(logoPath); + if (!file.exists()) { + throw new Exception("logo file not found."); + } + Image src = ImageIO.read(new File(logoPath)); + int width = src.getWidth(null); + int height = src.getHeight(null); + if (needCompress) { // 压缩LOGO + if (width > LOGO_WIDTH) { + width = LOGO_WIDTH; + } + if (height > LOGO_HEIGHT) { + height = LOGO_HEIGHT; + } + Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH); + BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics g = tag.getGraphics(); + g.drawImage(image, 0, 0, null); // 绘制缩小后的图 + g.dispose(); + src = image; + } + // 插入LOGO + Graphics2D graph = source.createGraphics(); + int x = (QRCODE_WIDTH - width) / 2; + int y = (QRCODE_HEIGHT - height) / 2; + graph.drawImage(src, x, y, width, height, null); + Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6); + graph.setStroke(new BasicStroke(3f)); + graph.draw(shape); + graph.dispose(); + } + + /** + * 生成二维码(内嵌LOGO) + * 调用者指定二维码文件名 + * @param content 二维码的内容 + * @param logoPath 中间图片地址 + * @param destPath 存储路径 + * @param fileName 文件名称 + * @param needCompress 是否压缩 + * @return + * @throws Exception + */ + public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception { + BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress); + mkdirs(destPath); + //文件名称通过传递 + fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length()) + + "." + FORMAT.toLowerCase(); + ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName)); + return fileName; + } + + /** + * 创建文件夹, mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常) + * @param destPath + */ + public static void mkdirs(String destPath) { + File file = new File(destPath); + if (!file.exists() && !file.isDirectory()) { + file.mkdirs(); + } + } + + /** + * 解析二维码 + * @param path 二维码图片路径 + * @return String 二维码内容 + * @throws Exception + */ + public static String decode(String path) throws Exception { + File file = new File(path); + BufferedImage image = ImageIO.read(file); + if (image == null) { + return null; + } + BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image); + BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + Result result; + Hashtable hints = new Hashtable(); + hints.put(DecodeHintType.CHARACTER_SET, UNICODE); + result = new MultiFormatReader().decode(bitmap, hints); + return result.getText(); + } + + /** + * 测试 + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + String text = "http://47.105.101.72:8088"; + //不含Logo +// QRCodeUtil.encode(text, null, "/Users/kyson/Downloads", "qrcode", true); + //含Logo,指定二维码图片名 + QRCodeUtil.encode(text, "/Users/kyson/Downloads/宋康.jpg", "/Users/kyson/Downloads", "qrcode1", true); +// System.out.println(QRCodeUtil.decode("d:\\cc\\qrcode1.jpg")); +// System.out.println(QRCodeUtil.encode(text, null, "/Users/kyson/Downloads", "qrcode", true)); + } +} diff --git a/src/main/java/com/sqx/common/utils/Query.java b/src/main/java/com/sqx/common/utils/Query.java new file mode 100644 index 0000000..bbddb66 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/Query.java @@ -0,0 +1,68 @@ +package com.sqx.common.utils; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.metadata.OrderItem; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.xss.SQLFilter; +import org.apache.commons.lang.StringUtils; + +import java.util.Map; + +/** + * 查询参数 + * + */ +public class Query { + + public IPage getPage(Map params) { + return this.getPage(params, null, false); + } + + public IPage getPage(Map params, String defaultOrderField, boolean isAsc) { + //分页参数 + long curPage = 1; + long limit = 10; + + if(params.get(Constant.PAGE) != null){ + curPage = Long.parseLong(String.valueOf(params.get(Constant.PAGE))); + } + if(params.get(Constant.LIMIT) != null){ + limit = Long.parseLong(String.valueOf(params.get(Constant.LIMIT))); + } + + //分页对象 + Page page = new Page<>(curPage, limit); + + //分页参数 + params.put(Constant.PAGE, page); + + //排序字段 + //防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险) + String orderField = SQLFilter.sqlInject((String)params.get(Constant.ORDER_FIELD)); + String order = (String)params.get(Constant.ORDER); + + + //前端字段排序 + if(StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)){ + if(Constant.ASC.equalsIgnoreCase(order)) { + return page.addOrder(OrderItem.asc(orderField)); + }else { + return page.addOrder(OrderItem.desc(orderField)); + } + } + + //没有排序字段,则不排序 + if(StringUtils.isBlank(defaultOrderField)){ + return page; + } + + //默认排序 + if(isAsc) { + page.addOrder(OrderItem.asc(defaultOrderField)); + }else { + page.addOrder(OrderItem.desc(defaultOrderField)); + } + + return page; + } +} diff --git a/src/main/java/com/sqx/common/utils/RedisKeys.java b/src/main/java/com/sqx/common/utils/RedisKeys.java new file mode 100644 index 0000000..f195413 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/RedisKeys.java @@ -0,0 +1,12 @@ +package com.sqx.common.utils; + +/** + * Redis所有Keys + * + */ +public class RedisKeys { + + public static String getSysConfigKey(String key){ + return "sys:config:" + key; + } +} diff --git a/src/main/java/com/sqx/common/utils/RedisUtils.java b/src/main/java/com/sqx/common/utils/RedisUtils.java new file mode 100644 index 0000000..30517ec --- /dev/null +++ b/src/main/java/com/sqx/common/utils/RedisUtils.java @@ -0,0 +1,90 @@ +package com.sqx.common.utils; + +import com.google.gson.Gson; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.*; +import org.springframework.stereotype.Component; + +import java.util.concurrent.TimeUnit; + +/** + * Redis工具类 + * + */ +@Component +public class RedisUtils { + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private ValueOperations valueOperations; + @Autowired + private HashOperations hashOperations; + @Autowired + private ListOperations listOperations; + @Autowired + private SetOperations setOperations; + @Autowired + private ZSetOperations zSetOperations; + /** 默认过期时长,单位:秒 */ + public final static long DEFAULT_EXPIRE = 60 * 60 * 24; + /** 不设置过期时长 */ + public final static long NOT_EXPIRE = -1; + private final static Gson Gson = new Gson(); + + public void set(String key, Object value, long expire){ + valueOperations.set(key, toJson(value)); + if(expire != NOT_EXPIRE){ + redisTemplate.expire(key, expire, TimeUnit.SECONDS); + } + } + + public void set(String key, Object value){ + set(key, value, DEFAULT_EXPIRE); + } + + public T get(String key, Class clazz, long expire) { + String value = valueOperations.get(key); + if(expire != NOT_EXPIRE){ + redisTemplate.expire(key, expire, TimeUnit.SECONDS); + } + return value == null ? null : fromJson(value, clazz); + } + + public T get(String key, Class clazz) { + return get(key, clazz, NOT_EXPIRE); + } + + public String get(String key, long expire) { + String value = valueOperations.get(key); + if(expire != NOT_EXPIRE){ + redisTemplate.expire(key, expire, TimeUnit.SECONDS); + } + return value; + } + + public String get(String key) { + return get(key, NOT_EXPIRE); + } + + public void delete(String key) { + redisTemplate.delete(key); + } + + /** + * Object转成JSON数据 + */ + private String toJson(Object object){ + if(object instanceof Integer || object instanceof Long || object instanceof Float || + object instanceof Double || object instanceof Boolean || object instanceof String){ + return String.valueOf(object); + } + return Gson.toJson(object); + } + + /** + * JSON数据,转成Object + */ + private T fromJson(String json, Class clazz){ + return Gson.fromJson(json, clazz); + } +} diff --git a/src/main/java/com/sqx/common/utils/Result.java b/src/main/java/com/sqx/common/utils/Result.java new file mode 100644 index 0000000..01f6241 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/Result.java @@ -0,0 +1,58 @@ +package com.sqx.common.utils; + +import org.apache.http.HttpStatus; + +import java.util.HashMap; +import java.util.Map; + +/** + * 返回数据 + * + */ +public class Result extends HashMap { + private static final long serialVersionUID = 1L; + + public Result () { + put("code", 0); + put("msg", "success"); + } + public static Result upStatus(Integer rows) { + return rows > 0 ? success() : error(); + } + public static Result error() { + return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员"); + } + + public static Result error(String msg) { + return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg); + } + + public static Result error(int code, String msg) { + Result r = new Result(); + r.put("code", code); + r.put("msg", msg); + return r; + } + + public static Result success(String msg) { + Result r = new Result(); + r.put("msg", msg); + return r; + } + + public static Result success(Map map) { + Result r = new Result(); + r.putAll(map); + return r; + } + + public static Result success() { + return new Result(); + } + + @Override + public Result put(String key, Object value) { + super.put(key, value); + return this; + } +} diff --git a/src/main/java/com/sqx/common/utils/ShiroUtils.java b/src/main/java/com/sqx/common/utils/ShiroUtils.java new file mode 100644 index 0000000..291a032 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/ShiroUtils.java @@ -0,0 +1,52 @@ +package com.sqx.common.utils; + +import com.sqx.common.exception.SqxException; +import com.sqx.modules.sys.entity.SysUserEntity; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; + +/** + * Shiro工具类 + * + */ +public class ShiroUtils { + + public static Session getSession() { + return SecurityUtils.getSubject().getSession(); + } + + public static Subject getSubject() { + return SecurityUtils.getSubject(); + } + + public static SysUserEntity getUserEntity() { + return (SysUserEntity)SecurityUtils.getSubject().getPrincipal(); + } + + public static Long getUserId() { + return getUserEntity().getUserId(); + } + + public static void setSessionAttribute(Object key, Object value) { + getSession().setAttribute(key, value); + } + + public static Object getSessionAttribute(Object key) { + return getSession().getAttribute(key); + } + + public static boolean isLogin() { + return SecurityUtils.getSubject().getPrincipal() != null; + } + + public static String getKaptcha(String key) { + Object kaptcha = getSessionAttribute(key); + if(kaptcha == null){ + throw new SqxException("验证码已失效"); + } + getSession().removeAttribute(key); + return kaptcha.toString(); + } + +} diff --git a/src/main/java/com/sqx/common/utils/SpringContextUtils.java b/src/main/java/com/sqx/common/utils/SpringContextUtils.java new file mode 100644 index 0000000..96a3976 --- /dev/null +++ b/src/main/java/com/sqx/common/utils/SpringContextUtils.java @@ -0,0 +1,42 @@ +package com.sqx.common.utils; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * Spring Context 工具类 + * + */ +@Component +public class SpringContextUtils implements ApplicationContextAware { + public static ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + SpringContextUtils.applicationContext = applicationContext; + } + + public static Object getBean(String name) { + return applicationContext.getBean(name); + } + + public static T getBean(String name, Class requiredType) { + return applicationContext.getBean(name, requiredType); + } + + public static boolean containsBean(String name) { + return applicationContext.containsBean(name); + } + + public static boolean isSingleton(String name) { + return applicationContext.isSingleton(name); + } + + public static Class getType(String name) { + return applicationContext.getType(name); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/common/validator/Assert.java b/src/main/java/com/sqx/common/validator/Assert.java new file mode 100644 index 0000000..3152500 --- /dev/null +++ b/src/main/java/com/sqx/common/validator/Assert.java @@ -0,0 +1,23 @@ +package com.sqx.common.validator; + +import com.sqx.common.exception.SqxException; +import org.apache.commons.lang.StringUtils; + +/** + * 数据校验 + * + */ + public class Assert { + + public static void isBlank(String str, String message) { + if (StringUtils.isBlank(str)) { + throw new SqxException(message); + } + } + + public static void isNull(Object object, String message) { + if (object == null) { + throw new SqxException(message); + } + } +} diff --git a/src/main/java/com/sqx/common/validator/ValidatorUtils.java b/src/main/java/com/sqx/common/validator/ValidatorUtils.java new file mode 100644 index 0000000..a5d83fc --- /dev/null +++ b/src/main/java/com/sqx/common/validator/ValidatorUtils.java @@ -0,0 +1,40 @@ +package com.sqx.common.validator; + +import com.sqx.common.exception.SqxException; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import java.util.Set; + +/** + * hibernate-validator校验工具类 + * + * 参考文档:http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/ + * + */ +public class ValidatorUtils { + private static Validator validator; + + static { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + /** + * 校验对象 + * @param object 待校验对象 + * @param groups 待校验的组 + * @throws SqxException 校验不通过,则报SqxException异常 + */ + public static void validateEntity(Object object, Class... groups) + throws SqxException { + Set> constraintViolations = validator.validate(object, groups); + if (!constraintViolations.isEmpty()) { + StringBuilder msg = new StringBuilder(); + for(ConstraintViolation constraint: constraintViolations){ + msg.append(constraint.getMessage()).append("
"); + } + throw new SqxException(msg.toString()); + } + } +} diff --git a/src/main/java/com/sqx/common/validator/group/AddGroup.java b/src/main/java/com/sqx/common/validator/group/AddGroup.java new file mode 100644 index 0000000..b7021b2 --- /dev/null +++ b/src/main/java/com/sqx/common/validator/group/AddGroup.java @@ -0,0 +1,8 @@ +package com.sqx.common.validator.group; + +/** + * 新增数据 Group + * + */ +public interface AddGroup { +} diff --git a/src/main/java/com/sqx/common/validator/group/AliyunGroup.java b/src/main/java/com/sqx/common/validator/group/AliyunGroup.java new file mode 100644 index 0000000..d130a82 --- /dev/null +++ b/src/main/java/com/sqx/common/validator/group/AliyunGroup.java @@ -0,0 +1,8 @@ +package com.sqx.common.validator.group; + +/** + * 阿里云 + * + */ +public interface AliyunGroup { +} diff --git a/src/main/java/com/sqx/common/validator/group/Group.java b/src/main/java/com/sqx/common/validator/group/Group.java new file mode 100644 index 0000000..76af874 --- /dev/null +++ b/src/main/java/com/sqx/common/validator/group/Group.java @@ -0,0 +1,12 @@ +package com.sqx.common.validator.group; + +import javax.validation.GroupSequence; + +/** + * 定义校验顺序,如果AddGroup组失败,则UpdateGroup组不会再校验 + * + */ +@GroupSequence({AddGroup.class, UpdateGroup.class}) +public interface Group { + +} diff --git a/src/main/java/com/sqx/common/validator/group/QcloudGroup.java b/src/main/java/com/sqx/common/validator/group/QcloudGroup.java new file mode 100644 index 0000000..323a9ce --- /dev/null +++ b/src/main/java/com/sqx/common/validator/group/QcloudGroup.java @@ -0,0 +1,8 @@ +package com.sqx.common.validator.group; + +/** + * 腾讯云 + * + */ +public interface QcloudGroup { +} diff --git a/src/main/java/com/sqx/common/validator/group/QiniuGroup.java b/src/main/java/com/sqx/common/validator/group/QiniuGroup.java new file mode 100644 index 0000000..17ab553 --- /dev/null +++ b/src/main/java/com/sqx/common/validator/group/QiniuGroup.java @@ -0,0 +1,8 @@ +package com.sqx.common.validator.group; + +/** + * 七牛 + * + */ +public interface QiniuGroup { +} diff --git a/src/main/java/com/sqx/common/validator/group/UpdateGroup.java b/src/main/java/com/sqx/common/validator/group/UpdateGroup.java new file mode 100644 index 0000000..fa0a242 --- /dev/null +++ b/src/main/java/com/sqx/common/validator/group/UpdateGroup.java @@ -0,0 +1,10 @@ +package com.sqx.common.validator.group; + +/** + * 更新数据 Group + * + */ + +public interface UpdateGroup { + +} diff --git a/src/main/java/com/sqx/common/xss/HTMLFilter.java b/src/main/java/com/sqx/common/xss/HTMLFilter.java new file mode 100644 index 0000000..1cc0e4f --- /dev/null +++ b/src/main/java/com/sqx/common/xss/HTMLFilter.java @@ -0,0 +1,526 @@ +package com.sqx.common.xss; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * + * HTML filtering utility for protecting against XSS (Cross Site Scripting). + * + * This code is licensed LGPLv3 + * + * This code is a Java port of the original work in PHP by Cal Hendersen. + * http://code.iamcal.com/php/lib_filter/ + * + * The trickiest part of the translation was handling the differences in regex handling + * between PHP and Java. These resources were helpful in the process: + * + * http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html + * http://us2.php.net/manual/en/reference.pcre.pattern.modifiers.php + * http://www.regular-expressions.info/modifiers.html + * + * A note on naming conventions: instance variables are prefixed with a "v"; global + * constants are in all caps. + * + * Sample use: + * String input = ... + * String clean = new HTMLFilter().filter( input ); + * + * The class is not thread safe. Create a new instance if in doubt. + * + * If you find bugs or have suggestions on improvement (especially regarding + * performance), please contact us. The latest version of this + * source, and our contact details, can be found at http://xss-html-filter.sf.net + * + * @author Joseph O'Connell + * @author Cal Hendersen + * @author Michael Semb Wever + */ +public final class HTMLFilter { + + /** regex flag union representing /si modifiers in php **/ + private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL; + private static final Pattern P_COMMENTS = Pattern.compile("", Pattern.DOTALL); + private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI); + private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL); + private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI); + private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); + private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); + private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); + private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI); + private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?"); + private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?"); + private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?"); + private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))"); + private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); + private static final Pattern P_END_ARROW = Pattern.compile("^>"); + private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)"); + private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)"); + private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)"); + private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)"); + private static final Pattern P_AMP = Pattern.compile("&"); + private static final Pattern P_QUOTE = Pattern.compile("<"); + private static final Pattern P_LEFT_ARROW = Pattern.compile("<"); + private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); + private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); + + // @xxx could grow large... maybe use sesat's ReferenceMap + private static final ConcurrentMap P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap(); + private static final ConcurrentMap P_REMOVE_SELF_BLANKS = new ConcurrentHashMap(); + + /** set of allowed html elements, along with allowed attributes for each element **/ + private final Map> vAllowed; + /** counts of open tags for each (allowable) html element **/ + private final Map vTagCounts = new HashMap(); + + /** html elements which must always be self-closing (e.g. "") **/ + private final String[] vSelfClosingTags; + /** html elements which must always have separate opening and closing tags (e.g. "") **/ + private final String[] vNeedClosingTags; + /** set of disallowed html elements **/ + private final String[] vDisallowed; + /** attributes which should be checked for valid protocols **/ + private final String[] vProtocolAtts; + /** allowed protocols **/ + private final String[] vAllowedProtocols; + /** tags which should be removed if they contain no content (e.g. "" or "") **/ + private final String[] vRemoveBlanks; + /** entities allowed within html markup **/ + private final String[] vAllowedEntities; + /** flag determining whether comments are allowed in input String. */ + private final boolean stripComment; + private final boolean encodeQuotes; + private boolean vDebug = false; + /** + * flag determining whether to try to make tags when presented with "unbalanced" + * angle brackets (e.g. "" becomes " text "). If set to false, + * unbalanced angle brackets will be html escaped. + */ + private final boolean alwaysMakeTags; + + /** Default constructor. + * + */ + public HTMLFilter() { + vAllowed = new HashMap<>(); + + final ArrayList a_atts = new ArrayList(); + a_atts.add("href"); + a_atts.add("target"); + vAllowed.put("a", a_atts); + + final ArrayList img_atts = new ArrayList(); + img_atts.add("src"); + img_atts.add("width"); + img_atts.add("height"); + img_atts.add("alt"); + vAllowed.put("img", img_atts); + + final ArrayList no_atts = new ArrayList(); + vAllowed.put("b", no_atts); + vAllowed.put("strong", no_atts); + vAllowed.put("i", no_atts); + vAllowed.put("em", no_atts); + + vSelfClosingTags = new String[]{"img"}; + vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; + vDisallowed = new String[]{}; + vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. + vProtocolAtts = new String[]{"src", "href"}; + vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; + vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; + stripComment = true; + encodeQuotes = true; + alwaysMakeTags = true; + } + + /** Set debug flag to true. Otherwise use default settings. See the default constructor. + * + * @param debug turn debug on with a true argument + */ + public HTMLFilter(final boolean debug) { + this(); + vDebug = debug; + + } + + /** Map-parameter configurable constructor. + * + * @param conf map containing configuration. keys match field names. + */ + public HTMLFilter(final Map conf) { + + assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; + assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; + assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; + assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; + assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; + assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; + assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; + assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; + + vAllowed = Collections.unmodifiableMap((HashMap>) conf.get("vAllowed")); + vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); + vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); + vDisallowed = (String[]) conf.get("vDisallowed"); + vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); + vProtocolAtts = (String[]) conf.get("vProtocolAtts"); + vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); + vAllowedEntities = (String[]) conf.get("vAllowedEntities"); + stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; + encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; + alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; + } + + private void reset() { + vTagCounts.clear(); + } + + private void debug(final String msg) { + if (vDebug) { + Logger.getAnonymousLogger().info(msg); + } + } + + //--------------------------------------------------------------- + // my versions of some PHP library functions + public static String chr(final int decimal) { + return String.valueOf((char) decimal); + } + + public static String htmlSpecialChars(final String s) { + String result = s; + result = regexReplace(P_AMP, "&", result); + result = regexReplace(P_QUOTE, """, result); + result = regexReplace(P_LEFT_ARROW, "<", result); + result = regexReplace(P_RIGHT_ARROW, ">", result); + return result; + } + + //--------------------------------------------------------------- + /** + * given a user submitted input String, filter out any invalid or restricted + * html. + * + * @param input text (i.e. submitted by a user) than may contain html + * @return "clean" version of input, with only valid, whitelisted html elements allowed + */ + public String filter(final String input) { + reset(); + String s = input; + + debug("************************************************"); + debug(" INPUT: " + input); + + s = escapeComments(s); + debug(" escapeComments: " + s); + + s = balanceHTML(s); + debug(" balanceHTML: " + s); + + s = checkTags(s); + debug(" checkTags: " + s); + + s = processRemoveBlanks(s); + debug("processRemoveBlanks: " + s); + + s = validateEntities(s); + debug(" validateEntites: " + s); + + debug("************************************************\n\n"); + return s; + } + + public boolean isAlwaysMakeTags(){ + return alwaysMakeTags; + } + + public boolean isStripComments(){ + return stripComment; + } + + private String escapeComments(final String s) { + final Matcher m = P_COMMENTS.matcher(s); + final StringBuffer buf = new StringBuffer(); + if (m.find()) { + final String match = m.group(1); //(.*?) + m.appendReplacement(buf, Matcher.quoteReplacement("")); + } + m.appendTail(buf); + + return buf.toString(); + } + + private String balanceHTML(String s) { + if (alwaysMakeTags) { + // + // try and form html + // + s = regexReplace(P_END_ARROW, "", s); + s = regexReplace(P_BODY_TO_END, "<$1>", s); + s = regexReplace(P_XML_CONTENT, "$1<$2", s); + + } else { + // + // escape stray brackets + // + s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); + s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); + + // + // the last regexp causes '<>' entities to appear + // (we need to do a lookahead assertion so that the last bracket can + // be used in the next pass of the regexp) + // + s = regexReplace(P_BOTH_ARROWS, "", s); + } + + return s; + } + + private String checkTags(String s) { + Matcher m = P_TAGS.matcher(s); + + final StringBuffer buf = new StringBuffer(); + while (m.find()) { + String replaceStr = m.group(1); + replaceStr = processTag(replaceStr); + m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); + } + m.appendTail(buf); + + s = buf.toString(); + + // these get tallied in processTag + // (remember to reset before subsequent calls to filter method) + for (String key : vTagCounts.keySet()) { + for (int ii = 0; ii < vTagCounts.get(key); ii++) { + s += ""; + } + } + + return s; + } + + private String processRemoveBlanks(final String s) { + String result = s; + for (String tag : vRemoveBlanks) { + if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){ + P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?>")); + } + result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); + if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){ + P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); + } + result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); + } + + return result; + } + + private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) { + Matcher m = regex_pattern.matcher(s); + return m.replaceAll(replacement); + } + + private String processTag(final String s) { + // ending tags + Matcher m = P_END_TAG.matcher(s); + if (m.find()) { + final String name = m.group(1).toLowerCase(); + if (allowed(name)) { + if (!inArray(name, vSelfClosingTags)) { + if (vTagCounts.containsKey(name)) { + vTagCounts.put(name, vTagCounts.get(name) - 1); + return ""; + } + } + } + } + + // starting tags + m = P_START_TAG.matcher(s); + if (m.find()) { + final String name = m.group(1).toLowerCase(); + final String body = m.group(2); + String ending = m.group(3); + + //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); + if (allowed(name)) { + String params = ""; + + final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); + final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); + final List paramNames = new ArrayList(); + final List paramValues = new ArrayList(); + while (m2.find()) { + paramNames.add(m2.group(1)); //([a-z0-9]+) + paramValues.add(m2.group(3)); //(.*?) + } + while (m3.find()) { + paramNames.add(m3.group(1)); //([a-z0-9]+) + paramValues.add(m3.group(3)); //([^\"\\s']+) + } + + String paramName, paramValue; + for (int ii = 0; ii < paramNames.size(); ii++) { + paramName = paramNames.get(ii).toLowerCase(); + paramValue = paramValues.get(ii); + + if (allowedAttribute(name, paramName)) { + if (inArray(paramName, vProtocolAtts)) { + paramValue = processParamProtocol(paramValue); + } + params += " " + paramName + "=\"" + paramValue + "\""; + } + } + + if (inArray(name, vSelfClosingTags)) { + ending = " /"; + } + + if (inArray(name, vNeedClosingTags)) { + ending = ""; + } + + if (ending == null || ending.length() < 1) { + if (vTagCounts.containsKey(name)) { + vTagCounts.put(name, vTagCounts.get(name) + 1); + } else { + vTagCounts.put(name, 1); + } + } else { + ending = " /"; + } + return "<" + name + params + ending + ">"; + } else { + return ""; + } + } + + // comments + m = P_COMMENT.matcher(s); + if (!stripComment && m.find()) { + return "<" + m.group() + ">"; + } + + return ""; + } + + private String processParamProtocol(String s) { + s = decodeEntities(s); + final Matcher m = P_PROTOCOL.matcher(s); + if (m.find()) { + final String protocol = m.group(1); + if (!inArray(protocol, vAllowedProtocols)) { + // bad protocol, turn into local anchor link instead + s = "#" + s.substring(protocol.length() + 1, s.length()); + if (s.startsWith("#//")) { + s = "#" + s.substring(3, s.length()); + } + } + } + + return s; + } + + private String decodeEntities(String s) { + StringBuffer buf = new StringBuffer(); + + Matcher m = P_ENTITY.matcher(s); + while (m.find()) { + final String match = m.group(1); + final int decimal = Integer.decode(match).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); + + buf = new StringBuffer(); + m = P_ENTITY_UNICODE.matcher(s); + while (m.find()) { + final String match = m.group(1); + final int decimal = Integer.valueOf(match, 16).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); + + buf = new StringBuffer(); + m = P_ENCODE.matcher(s); + while (m.find()) { + final String match = m.group(1); + final int decimal = Integer.valueOf(match, 16).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); + + s = validateEntities(s); + return s; + } + + private String validateEntities(final String s) { + StringBuffer buf = new StringBuffer(); + + // validate entities throughout the string + Matcher m = P_VALID_ENTITIES.matcher(s); + while (m.find()) { + final String one = m.group(1); //([^&;]*) + final String two = m.group(2); //(?=(;|&|$)) + m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); + } + m.appendTail(buf); + + return encodeQuotes(buf.toString()); + } + + private String encodeQuotes(final String s){ + if(encodeQuotes){ + StringBuffer buf = new StringBuffer(); + Matcher m = P_VALID_QUOTES.matcher(s); + while (m.find()) { + final String one = m.group(1); //(>|^) + final String two = m.group(2); //([^<]+?) + final String three = m.group(3); //(<|$) + m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); + } + m.appendTail(buf); + return buf.toString(); + }else{ + return s; + } + } + + private String checkEntity(final String preamble, final String term) { + + return ";".equals(term) && isValidEntity(preamble) + ? '&' + preamble + : "&" + preamble; + } + + private boolean isValidEntity(final String entity) { + return inArray(entity, vAllowedEntities); + } + + private static boolean inArray(final String s, final String[] array) { + for (String item : array) { + if (item != null && item.equals(s)) { + return true; + } + } + return false; + } + + private boolean allowed(final String name) { + return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); + } + + private boolean allowedAttribute(final String name, final String paramName) { + return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/common/xss/SQLFilter.java b/src/main/java/com/sqx/common/xss/SQLFilter.java new file mode 100644 index 0000000..b16ad39 --- /dev/null +++ b/src/main/java/com/sqx/common/xss/SQLFilter.java @@ -0,0 +1,41 @@ +package com.sqx.common.xss; + +import com.sqx.common.exception.SqxException; +import org.apache.commons.lang.StringUtils; + +/** + * SQL过滤 + * + */ +public class SQLFilter { + + /** + * SQL注入过滤 + * @param str 待验证的字符串 + */ + public static String sqlInject(String str){ + if(StringUtils.isBlank(str)){ + return null; + } + //去掉'|"|;|\字符 + str = StringUtils.replace(str, "'", ""); + str = StringUtils.replace(str, "\"", ""); + str = StringUtils.replace(str, ";", ""); + str = StringUtils.replace(str, "\\", ""); + + //转换成小写 + str = str.toLowerCase(); + + //非法字符 + String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"}; + + //判断是否包含非法字符 + for(String keyword : keywords){ + if(str.indexOf(keyword) != -1){ + throw new SqxException("包含非法字符"); + } + } + + return str; + } +} diff --git a/src/main/java/com/sqx/common/xss/XssFilter.java b/src/main/java/com/sqx/common/xss/XssFilter.java new file mode 100644 index 0000000..a200516 --- /dev/null +++ b/src/main/java/com/sqx/common/xss/XssFilter.java @@ -0,0 +1,33 @@ +package com.sqx.common.xss; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +/** + * XSS过滤 + * + */ +public class XssFilter implements Filter { + + @Override + public void init(FilterConfig config) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper( + (HttpServletRequest) request); + chain.doFilter(xssRequest, response); + String requestURI = xssRequest.getRequestURI(); + String method = xssRequest.getMethod(); + System.err.println("当前请求的方法是:" + method + ",请求地址是:" + requestURI); + + } + + @Override + public void destroy() { + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/common/xss/XssHttpServletRequestWrapper.java b/src/main/java/com/sqx/common/xss/XssHttpServletRequestWrapper.java new file mode 100644 index 0000000..d9700e9 --- /dev/null +++ b/src/main/java/com/sqx/common/xss/XssHttpServletRequestWrapper.java @@ -0,0 +1,138 @@ +package com.sqx.common.xss; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * XSS过滤处理 + * + */ +public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { + //没被包装过的HttpServletRequest(特殊场景,需要自己过滤) + HttpServletRequest orgRequest; + //html过滤 + private final static HTMLFilter HtmlFilter = new HTMLFilter(); + + public XssHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + orgRequest = request; + } + + @Override + public ServletInputStream getInputStream() throws IOException { + //非json类型,直接返回 + if(!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))){ + return super.getInputStream(); + } + + //为空,直接返回 + String json = IOUtils.toString(super.getInputStream(), "utf-8"); + if (StringUtils.isBlank(json)) { + return super.getInputStream(); + } + + //xss过滤 + json = xssEncode(json); + final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8")); + return new ServletInputStream() { + @Override + public boolean isFinished() { + return true; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener readListener) { + + } + + @Override + public int read() throws IOException { + return bis.read(); + } + }; + } + + @Override + public String getParameter(String name) { + String value = super.getParameter(xssEncode(name)); + if (StringUtils.isNotBlank(value)) { + value = xssEncode(value); + } + return value; + } + + @Override + public String[] getParameterValues(String name) { + String[] parameters = super.getParameterValues(name); + if (parameters == null || parameters.length == 0) { + return null; + } + + for (int i = 0; i < parameters.length; i++) { + parameters[i] = xssEncode(parameters[i]); + } + return parameters; + } + + @Override + public Map getParameterMap() { + Map map = new LinkedHashMap<>(); + Map parameters = super.getParameterMap(); + for (String key : parameters.keySet()) { + String[] values = parameters.get(key); + for (int i = 0; i < values.length; i++) { + values[i] = xssEncode(values[i]); + } + map.put(key, values); + } + return map; + } + + @Override + public String getHeader(String name) { + String value = super.getHeader(xssEncode(name)); + if (StringUtils.isNotBlank(value)) { + value = xssEncode(value); + } + return value; + } + + private String xssEncode(String input) { + return HtmlFilter.filter(input); + } + + /** + * 获取最原始的request + */ + public HttpServletRequest getOrgRequest() { + return orgRequest; + } + + /** + * 获取最原始的request + */ + public static HttpServletRequest getOrgRequest(HttpServletRequest request) { + if (request instanceof XssHttpServletRequestWrapper) { + return ((XssHttpServletRequestWrapper) request).getOrgRequest(); + } + + return request; + } + +} diff --git a/src/main/java/com/sqx/config/CorsConfig.java b/src/main/java/com/sqx/config/CorsConfig.java new file mode 100644 index 0000000..781ce11 --- /dev/null +++ b/src/main/java/com/sqx/config/CorsConfig.java @@ -0,0 +1,47 @@ +package com.sqx.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + + +/** + * 跨域设置 + */ +@Configuration +public class CorsConfig implements WebMvcConfigurer { + + /*private CorsConfiguration buildConfig() { + CorsConfiguration corsConfiguration = new CorsConfiguration(); + // 1允许任何域名使用 + corsConfiguration.addAllowedOrigin("*"); + // 2允许任何头 + corsConfiguration.addAllowedHeader("*"); + // 3允许任何方法(post、get等) + corsConfiguration.addAllowedMethod("*"); + return corsConfiguration; + } + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", buildConfig()); + return new CorsFilter(source); + }*/ + + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOriginPatterns("*") + .allowCredentials(true) + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") + .maxAge(3600); + } + + +} diff --git a/src/main/java/com/sqx/config/FilterConfig.java b/src/main/java/com/sqx/config/FilterConfig.java new file mode 100644 index 0000000..778e0b2 --- /dev/null +++ b/src/main/java/com/sqx/config/FilterConfig.java @@ -0,0 +1,40 @@ +package com.sqx.config; + +import com.sqx.common.xss.XssFilter; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +import javax.servlet.DispatcherType; + +/** + * Filter配置 + * + */ +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean shiroFilterRegistration() { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setFilter(new DelegatingFilterProxy("shiroFilter")); + //该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 + registration.addInitParameter("targetFilterLifecycle", "true"); + registration.setEnabled(true); + registration.setOrder(Integer.MAX_VALUE - 1); + registration.addUrlPatterns("/*"); + return registration; + } + + @Bean + public FilterRegistrationBean xssFilterRegistration() { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setDispatcherTypes(DispatcherType.REQUEST); + registration.setFilter(new XssFilter()); + registration.addUrlPatterns("/*"); + registration.setName("xssFilter"); + registration.setOrder(Integer.MAX_VALUE); + return registration; + } +} diff --git a/src/main/java/com/sqx/config/KaptchaConfig.java b/src/main/java/com/sqx/config/KaptchaConfig.java new file mode 100644 index 0000000..ea8c936 --- /dev/null +++ b/src/main/java/com/sqx/config/KaptchaConfig.java @@ -0,0 +1,30 @@ +package com.sqx.config; + +import com.google.code.kaptcha.impl.DefaultKaptcha; +import com.google.code.kaptcha.util.Config; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Properties; + + +/** + * 生成验证码配置 + * + */ +@Configuration +public class KaptchaConfig { + + @Bean + public DefaultKaptcha producer() { + Properties properties = new Properties(); + properties.put("kaptcha.border", "no"); + properties.put("kaptcha.textproducer.font.color", "black"); + properties.put("kaptcha.textproducer.char.space", "5"); + properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑"); + Config config = new Config(properties); + DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); + defaultKaptcha.setConfig(config); + return defaultKaptcha; + } +} diff --git a/src/main/java/com/sqx/config/MybatisPlusConfig.java b/src/main/java/com/sqx/config/MybatisPlusConfig.java new file mode 100644 index 0000000..97edf00 --- /dev/null +++ b/src/main/java/com/sqx/config/MybatisPlusConfig.java @@ -0,0 +1,22 @@ +package com.sqx.config; + +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * mybatis-plus配置 + * + */ +@Configuration +public class MybatisPlusConfig { + + /** + * 分页插件 + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + return new PaginationInterceptor(); + } + +} diff --git a/src/main/java/com/sqx/config/RedisConfig.java b/src/main/java/com/sqx/config/RedisConfig.java new file mode 100644 index 0000000..deb93e2 --- /dev/null +++ b/src/main/java/com/sqx/config/RedisConfig.java @@ -0,0 +1,54 @@ +package com.sqx.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.*; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** + * Redis配置 + * + */ +@Configuration +public class RedisConfig { + @Autowired + private RedisConnectionFactory factory; + + @Bean + public RedisTemplate redisTemplate() { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setKeySerializer(new StringRedisSerializer()); + redisTemplate.setHashKeySerializer(new StringRedisSerializer()); + redisTemplate.setHashValueSerializer(new StringRedisSerializer()); + redisTemplate.setValueSerializer(new StringRedisSerializer()); + redisTemplate.setConnectionFactory(factory); + return redisTemplate; + } + + @Bean + public HashOperations hashOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForHash(); + } + + @Bean + public ValueOperations valueOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForValue(); + } + + @Bean + public ListOperations listOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForList(); + } + + @Bean + public SetOperations setOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForSet(); + } + + @Bean + public ZSetOperations zSetOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForZSet(); + } +} diff --git a/src/main/java/com/sqx/config/ShiroConfig.java b/src/main/java/com/sqx/config/ShiroConfig.java new file mode 100644 index 0000000..56b95e4 --- /dev/null +++ b/src/main/java/com/sqx/config/ShiroConfig.java @@ -0,0 +1,83 @@ +package com.sqx.config; + +import com.sqx.modules.sys.oauth2.OAuth2Filter; +import com.sqx.modules.sys.oauth2.OAuth2Realm; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.spring.LifecycleBeanPostProcessor; +import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.servlet.Filter; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Shiro配置 + * + */ +@Configuration +public class ShiroConfig { + + @Bean("securityManager") + public SecurityManager securityManager(OAuth2Realm oAuth2Realm) { + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); + securityManager.setRealm(oAuth2Realm); + securityManager.setRememberMeManager(null); + return securityManager; + } + + @Bean("shiroFilter") + public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) { + ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); + shiroFilter.setSecurityManager(securityManager); + + //oauth过滤 + Map filters = new HashMap<>(); + filters.put("oauth2", new OAuth2Filter()); + shiroFilter.setFilters(filters); + + Map filterMap = new LinkedHashMap<>(); + filterMap.put("/webjars/**", "anon"); + filterMap.put("/druid/**", "anon"); + filterMap.put("/app/wxPay/notifyJsApi", "anon"); + filterMap.put("/app/wxPay/notifyMp", "anon"); + filterMap.put("/app/wxPay/notify", "anon"); + filterMap.put("/app/aliPay/notifyApp", "anon"); + filterMap.put("/app/**", "anon"); + filterMap.put("/activity/**", "anon"); + filterMap.put("/banner/**", "anon"); + filterMap.put("/courseClassification/selectCourseClassification", "anon"); + filterMap.put("/sys/login", "anon"); + filterMap.put("/swagger/**", "anon"); + filterMap.put("/v2/api-docs", "anon"); + filterMap.put("/swagger-ui.html", "anon"); + filterMap.put("/swagger-ui/*", "anon"); + filterMap.put("/swagger-resources/**", "anon"); + filterMap.put("/captcha.jpg", "anon"); + filterMap.put("/chatSocket/**", "anon"); + filterMap.put("/websocket/**", "anon"); + filterMap.put("/search/**", "anon"); + filterMap.put("/alioss/**","anon"); + filterMap.put("/**", "oauth2"); + shiroFilter.setFilterChainDefinitionMap(filterMap); + + return shiroFilter; + } + + @Bean("lifecycleBeanPostProcessor") + public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { + return new LifecycleBeanPostProcessor(); + } + + @Bean + public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { + AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); + advisor.setSecurityManager(securityManager); + return advisor; + } + +} diff --git a/src/main/java/com/sqx/config/SwaggerConfig.java b/src/main/java/com/sqx/config/SwaggerConfig.java new file mode 100644 index 0000000..fac7871 --- /dev/null +++ b/src/main/java/com/sqx/config/SwaggerConfig.java @@ -0,0 +1,53 @@ +package com.sqx.config; + +import io.swagger.annotations.ApiOperation; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.ApiKey; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.List; + +import static com.google.common.collect.Lists.newArrayList; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig implements WebMvcConfigurer { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + //加了ApiOperation注解的类,才生成接口文档 + .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) + //包下的类,才生成接口文档 + //.apis(RequestHandlerSelectors.basePackage("com.sqx.controller")) + .paths(PathSelectors.any()) + .build() + .securitySchemes(security()); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("") + .description("sqx-fast文档") + .termsOfServiceUrl("") + .version("3.0.0") + .build(); + } + + private List security() { + return newArrayList( + new ApiKey("token", "token", "header") + ); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/datasource/annotation/DataSource.java b/src/main/java/com/sqx/datasource/annotation/DataSource.java new file mode 100644 index 0000000..082da71 --- /dev/null +++ b/src/main/java/com/sqx/datasource/annotation/DataSource.java @@ -0,0 +1,14 @@ +package com.sqx.datasource.annotation; + +import java.lang.annotation.*; + +/** + * 多数据源注解 + */ +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +public @interface DataSource { + String value() default ""; +} diff --git a/src/main/java/com/sqx/datasource/aspect/DataSourceAspect.java b/src/main/java/com/sqx/datasource/aspect/DataSourceAspect.java new file mode 100644 index 0000000..b3c5d0a --- /dev/null +++ b/src/main/java/com/sqx/datasource/aspect/DataSourceAspect.java @@ -0,0 +1,61 @@ +package com.sqx.datasource.aspect; + + +import com.sqx.datasource.annotation.DataSource; +import com.sqx.datasource.config.DynamicContextHolder; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; + +/** + * 多数据源,切面处理类 + */ +@Aspect +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class DataSourceAspect { + protected Logger logger = LoggerFactory.getLogger(getClass()); + + @Pointcut("@annotation(com.sqx.datasource.annotation.DataSource) " + + "|| @within(com.sqx.datasource.annotation.DataSource)") + public void dataSourcePointCut() { + + } + + @Around("dataSourcePointCut()") + public Object around(ProceedingJoinPoint point) throws Throwable { + MethodSignature signature = (MethodSignature) point.getSignature(); + Class targetClass = point.getTarget().getClass(); + Method method = signature.getMethod(); + + DataSource targetDataSource = (DataSource)targetClass.getAnnotation(DataSource.class); + DataSource methodDataSource = method.getAnnotation(DataSource.class); + if(targetDataSource != null || methodDataSource != null){ + String value; + if(methodDataSource != null){ + value = methodDataSource.value(); + }else { + value = targetDataSource.value(); + } + + DynamicContextHolder.push(value); + logger.debug("set datasource is {}", value); + } + + try { + return point.proceed(); + } finally { + DynamicContextHolder.poll(); + logger.debug("clean datasource"); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/datasource/config/DynamicContextHolder.java b/src/main/java/com/sqx/datasource/config/DynamicContextHolder.java new file mode 100644 index 0000000..f059bf7 --- /dev/null +++ b/src/main/java/com/sqx/datasource/config/DynamicContextHolder.java @@ -0,0 +1,47 @@ +package com.sqx.datasource.config; + +import java.util.ArrayDeque; +import java.util.Deque; + +/** + * 多数据源上下文 + */ +public class DynamicContextHolder { + @SuppressWarnings("unchecked") + private static final ThreadLocal> CONTEXT_HOLDER = new ThreadLocal() { + @Override + protected Object initialValue() { + return new ArrayDeque(); + } + }; + + /** + * 获得当前线程数据源 + * + * @return 数据源名称 + */ + public static String peek() { + return CONTEXT_HOLDER.get().peek(); + } + + /** + * 设置当前线程数据源 + * + * @param dataSource 数据源名称 + */ + public static void push(String dataSource) { + CONTEXT_HOLDER.get().push(dataSource); + } + + /** + * 清空当前线程数据源 + */ + public static void poll() { + Deque deque = CONTEXT_HOLDER.get(); + deque.poll(); + if (deque.isEmpty()) { + CONTEXT_HOLDER.remove(); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/datasource/config/DynamicDataSource.java b/src/main/java/com/sqx/datasource/config/DynamicDataSource.java new file mode 100644 index 0000000..4374032 --- /dev/null +++ b/src/main/java/com/sqx/datasource/config/DynamicDataSource.java @@ -0,0 +1,15 @@ +package com.sqx.datasource.config; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +/** + * 多数据源 + */ +public class DynamicDataSource extends AbstractRoutingDataSource { + + @Override + protected Object determineCurrentLookupKey() { + return DynamicContextHolder.peek(); + } + +} diff --git a/src/main/java/com/sqx/datasource/config/DynamicDataSourceConfig.java b/src/main/java/com/sqx/datasource/config/DynamicDataSourceConfig.java new file mode 100644 index 0000000..9c1033f --- /dev/null +++ b/src/main/java/com/sqx/datasource/config/DynamicDataSourceConfig.java @@ -0,0 +1,53 @@ +package com.sqx.datasource.config; + +import com.alibaba.druid.pool.DruidDataSource; +import com.sqx.datasource.properties.DataSourceProperties; +import com.sqx.datasource.properties.DynamicDataSourceProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.HashMap; +import java.util.Map; + +/** + * 配置多数据源 + */ +@Configuration +@EnableConfigurationProperties(DynamicDataSourceProperties.class) +public class DynamicDataSourceConfig { + @Autowired + private DynamicDataSourceProperties properties; + + @Bean + @ConfigurationProperties(prefix = "spring.datasource.druid") + public DataSourceProperties dataSourceProperties() { + return new DataSourceProperties(); + } + + @Bean + public DynamicDataSource dynamicDataSource(DataSourceProperties dataSourceProperties) { + DynamicDataSource dynamicDataSource = new DynamicDataSource(); + dynamicDataSource.setTargetDataSources(getDynamicDataSource()); + + //默认数据源 + DruidDataSource defaultDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties); + dynamicDataSource.setDefaultTargetDataSource(defaultDataSource); + + return dynamicDataSource; + } + + private Map getDynamicDataSource(){ + Map dataSourcePropertiesMap = properties.getDatasource(); + Map targetDataSources = new HashMap<>(dataSourcePropertiesMap.size()); + dataSourcePropertiesMap.forEach((k, v) -> { + DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(v); + targetDataSources.put(k, druidDataSource); + }); + + return targetDataSources; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/datasource/config/DynamicDataSourceFactory.java b/src/main/java/com/sqx/datasource/config/DynamicDataSourceFactory.java new file mode 100644 index 0000000..b506b40 --- /dev/null +++ b/src/main/java/com/sqx/datasource/config/DynamicDataSourceFactory.java @@ -0,0 +1,44 @@ +package com.sqx.datasource.config; + +import com.alibaba.druid.pool.DruidDataSource; +import com.sqx.datasource.properties.DataSourceProperties; + +import java.sql.SQLException; + +/** + * DruidDataSource + * + */ +public class DynamicDataSourceFactory { + + public static DruidDataSource buildDruidDataSource(DataSourceProperties properties) { + DruidDataSource druidDataSource = new DruidDataSource(); + druidDataSource.setDriverClassName(properties.getDriverClassName()); + druidDataSource.setUrl(properties.getUrl()); + druidDataSource.setUsername(properties.getUsername()); + druidDataSource.setPassword(properties.getPassword()); + + druidDataSource.setInitialSize(properties.getInitialSize()); + druidDataSource.setMaxActive(properties.getMaxActive()); + druidDataSource.setMinIdle(properties.getMinIdle()); + druidDataSource.setMaxWait(properties.getMaxWait()); + druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); + druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); + druidDataSource.setMaxEvictableIdleTimeMillis(properties.getMaxEvictableIdleTimeMillis()); + druidDataSource.setValidationQuery(properties.getValidationQuery()); + druidDataSource.setValidationQueryTimeout(properties.getValidationQueryTimeout()); + druidDataSource.setTestOnBorrow(properties.isTestOnBorrow()); + druidDataSource.setTestOnReturn(properties.isTestOnReturn()); + druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements()); + druidDataSource.setMaxOpenPreparedStatements(properties.getMaxOpenPreparedStatements()); + druidDataSource.setSharePreparedStatements(properties.isSharePreparedStatements()); + + try { + druidDataSource.setFilters(properties.getFilters()); + druidDataSource.init(); + } catch (SQLException e) { + e.printStackTrace(); + } + return druidDataSource; + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/datasource/properties/DataSourceProperties.java b/src/main/java/com/sqx/datasource/properties/DataSourceProperties.java new file mode 100644 index 0000000..0cc4fc4 --- /dev/null +++ b/src/main/java/com/sqx/datasource/properties/DataSourceProperties.java @@ -0,0 +1,192 @@ +package com.sqx.datasource.properties; + +/** + * 多数据源属性 + * + */ +public class DataSourceProperties { + private String driverClassName; + private String url; + private String username; + private String password; + + /** + * Druid默认参数 + */ + private int initialSize = 2; + private int maxActive = 10; + private int minIdle = -1; + private long maxWait = 60 * 1000L; + private long timeBetweenEvictionRunsMillis = 60 * 1000L; + private long minEvictableIdleTimeMillis = 1000L * 60L * 30L; + private long maxEvictableIdleTimeMillis = 1000L * 60L * 60L * 7; + private String validationQuery = "select 1"; + private int validationQueryTimeout = -1; + private boolean testOnBorrow = false; + private boolean testOnReturn = false; + private boolean testWhileIdle = true; + private boolean poolPreparedStatements = false; + private int maxOpenPreparedStatements = -1; + private boolean sharePreparedStatements = false; + private String filters = "stat,wall"; + + public String getDriverClassName() { + return driverClassName; + } + + public void setDriverClassName(String driverClassName) { + this.driverClassName = driverClassName; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public int getInitialSize() { + return initialSize; + } + + public void setInitialSize(int initialSize) { + this.initialSize = initialSize; + } + + public int getMaxActive() { + return maxActive; + } + + public void setMaxActive(int maxActive) { + this.maxActive = maxActive; + } + + public int getMinIdle() { + return minIdle; + } + + public void setMinIdle(int minIdle) { + this.minIdle = minIdle; + } + + public long getMaxWait() { + return maxWait; + } + + public void setMaxWait(long maxWait) { + this.maxWait = maxWait; + } + + public long getTimeBetweenEvictionRunsMillis() { + return timeBetweenEvictionRunsMillis; + } + + public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { + this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + } + + public long getMinEvictableIdleTimeMillis() { + return minEvictableIdleTimeMillis; + } + + public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { + this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + } + + public long getMaxEvictableIdleTimeMillis() { + return maxEvictableIdleTimeMillis; + } + + public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) { + this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis; + } + + public String getValidationQuery() { + return validationQuery; + } + + public void setValidationQuery(String validationQuery) { + this.validationQuery = validationQuery; + } + + public int getValidationQueryTimeout() { + return validationQueryTimeout; + } + + public void setValidationQueryTimeout(int validationQueryTimeout) { + this.validationQueryTimeout = validationQueryTimeout; + } + + public boolean isTestOnBorrow() { + return testOnBorrow; + } + + public void setTestOnBorrow(boolean testOnBorrow) { + this.testOnBorrow = testOnBorrow; + } + + public boolean isTestOnReturn() { + return testOnReturn; + } + + public void setTestOnReturn(boolean testOnReturn) { + this.testOnReturn = testOnReturn; + } + + public boolean isTestWhileIdle() { + return testWhileIdle; + } + + public void setTestWhileIdle(boolean testWhileIdle) { + this.testWhileIdle = testWhileIdle; + } + + public boolean isPoolPreparedStatements() { + return poolPreparedStatements; + } + + public void setPoolPreparedStatements(boolean poolPreparedStatements) { + this.poolPreparedStatements = poolPreparedStatements; + } + + public int getMaxOpenPreparedStatements() { + return maxOpenPreparedStatements; + } + + public void setMaxOpenPreparedStatements(int maxOpenPreparedStatements) { + this.maxOpenPreparedStatements = maxOpenPreparedStatements; + } + + public boolean isSharePreparedStatements() { + return sharePreparedStatements; + } + + public void setSharePreparedStatements(boolean sharePreparedStatements) { + this.sharePreparedStatements = sharePreparedStatements; + } + + public String getFilters() { + return filters; + } + + public void setFilters(String filters) { + this.filters = filters; + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/datasource/properties/DynamicDataSourceProperties.java b/src/main/java/com/sqx/datasource/properties/DynamicDataSourceProperties.java new file mode 100644 index 0000000..ebd2a26 --- /dev/null +++ b/src/main/java/com/sqx/datasource/properties/DynamicDataSourceProperties.java @@ -0,0 +1,22 @@ +package com.sqx.datasource.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * 多数据源属性 + */ +@ConfigurationProperties(prefix = "dynamic") +public class DynamicDataSourceProperties { + private Map datasource = new LinkedHashMap<>(); + + public Map getDatasource() { + return datasource; + } + + public void setDatasource(Map datasource) { + this.datasource = datasource; + } +} diff --git a/src/main/java/com/sqx/modules/app/annotation/Login.java b/src/main/java/com/sqx/modules/app/annotation/Login.java new file mode 100644 index 0000000..c4a0d48 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/annotation/Login.java @@ -0,0 +1,12 @@ +package com.sqx.modules.app.annotation; + +import java.lang.annotation.*; + +/** + * app登录效验 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Login { +} diff --git a/src/main/java/com/sqx/modules/app/annotation/LoginUser.java b/src/main/java/com/sqx/modules/app/annotation/LoginUser.java new file mode 100644 index 0000000..531a9dd --- /dev/null +++ b/src/main/java/com/sqx/modules/app/annotation/LoginUser.java @@ -0,0 +1,16 @@ +package com.sqx.modules.app.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 登录用户信息 + * + */ +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface LoginUser { + +} diff --git a/src/main/java/com/sqx/modules/app/config/WebMvcConfig.java b/src/main/java/com/sqx/modules/app/config/WebMvcConfig.java new file mode 100644 index 0000000..92bc78f --- /dev/null +++ b/src/main/java/com/sqx/modules/app/config/WebMvcConfig.java @@ -0,0 +1,38 @@ +package com.sqx.modules.app.config; + +import com.sqx.modules.app.interceptor.AuthorizationInterceptor; +import com.sqx.modules.app.resolver.LoginUserHandlerMethodArgumentResolver; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +/** + * MVC配置 + * + */ +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + @Autowired + private AuthorizationInterceptor authorizationInterceptor; + @Autowired + private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(authorizationInterceptor).addPathPatterns("/app/**"); + } + + @Override + public void addArgumentResolvers(List argumentResolvers) { + argumentResolvers.add(loginUserHandlerMethodArgumentResolver); + } + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/app/controller/AddressController.java b/src/main/java/com/sqx/modules/app/controller/AddressController.java new file mode 100644 index 0000000..25245ee --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/AddressController.java @@ -0,0 +1,43 @@ +package com.sqx.modules.app.controller; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.annotation.LoginUser; +import com.sqx.modules.app.entity.Address; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.AddressService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 地址 + */ +@RestController +@RequestMapping("/address") +@Api(value = "用户地址", tags = {"用户地址"}) +public class AddressController { + + @Autowired + private AddressService addressService; + + @GetMapping("/selectAddressListById") + @ApiOperation("获取我的所有地址") + public Result selectAddressListById(Long userId,Integer page,Integer limit){ + IPage
addressIPage = addressService.page(new Page<>(page, limit), new QueryWrapper
().eq("user_id", userId)); + return Result.success().put("data",new PageUtils(addressIPage)); + } + + + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/AppUpgradeController.java b/src/main/java/com/sqx/modules/app/controller/AppUpgradeController.java new file mode 100644 index 0000000..a09d2a6 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/AppUpgradeController.java @@ -0,0 +1,70 @@ +package com.sqx.modules.app.controller; + + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.App; +import com.sqx.modules.app.service.AppService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * APP登录授权 + * + */ +@RestController +@RequestMapping("/appinfo") +@Api(value = "APP升级管理", tags = {"APP升级管理"}) +public class AppUpgradeController { + + @Autowired + private AppService iAppService; + + @RequestMapping(value = "/list", method = RequestMethod.GET) + @ApiOperation("管理平台升级详情") + @ResponseBody + public Result list(Integer page,Integer limit) { + IPage pages =new Page<>(page,limit); + return Result.success().put("data",iAppService.page(pages)); + } + + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台升级详情") + @ResponseBody + public Result getBanner(@PathVariable Long id) { + return Result.success().put("data",iAppService.selectAppById(id)); + } + + @RequestMapping(value = "/save", method = RequestMethod.POST) + @ApiOperation("管理平台添加升级信息") + @ResponseBody + public Result addBanner(@RequestBody App app) { + if(app.getId()!=null){ + iAppService.updateAppById(app); + }else{ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + app.setCreateAt(sdf.format(new Date())); + iAppService.insertApp(app); + } + return Result.success(); + } + + @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台删除升级信息") + public Result deleteBanner(@PathVariable Long id) { + iAppService.deleteAppById(id); + return Result.success(); + } + + + + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/CarController.java b/src/main/java/com/sqx/modules/app/controller/CarController.java new file mode 100644 index 0000000..c8763f1 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/CarController.java @@ -0,0 +1,61 @@ +package com.sqx.modules.app.controller; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.Address; +import com.sqx.modules.app.entity.Car; +import com.sqx.modules.app.service.AddressService; +import com.sqx.modules.app.service.CarService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; + +/** + * 用户车辆信息 + */ +@RestController +@RequestMapping("/car") +@Api(value = "用户车辆信息", tags = {"用户车辆信息"}) +public class CarController { + + @Autowired + private CarService carService; + + @PostMapping("/insertCar") + @ApiOperation("添加车辆信息") + public Result insertCar(@RequestBody Car car){ + car.setCreateTime(DateUtils.format(new Date())); + carService.save(car); + return Result.success(); + } + + @PostMapping("/updateCar") + @ApiOperation("修改车辆信息") + public Result updateCar(@RequestBody Car car){ + carService.updateById(car); + return Result.success(); + } + + @PostMapping("/deleteCar") + @ApiOperation("删除车辆信息") + public Result deleteCar(Long carId){ + carService.removeById(carId); + return Result.success(); + } + + @GetMapping("/selectCarList") + @ApiOperation("查询车辆信息") + public Result selectCarList(Integer page,Integer limit,Long userId,String userName,String phone){ + return carService.selectCarList(page, limit, userId, userName, phone); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/CityAgencyController.java b/src/main/java/com/sqx/modules/app/controller/CityAgencyController.java new file mode 100644 index 0000000..2dbe3ec --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/CityAgencyController.java @@ -0,0 +1,61 @@ +package com.sqx.modules.app.controller; + + +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.CityAgency; +import com.sqx.modules.app.service.CityAgencyService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; + +/** + * @author fang + * @date 2021/5/19 + */ +@Slf4j +@RestController +@Api(value = "代理申请", tags = {"代理申请"}) +@RequestMapping(value = "/cityAgency") +public class CityAgencyController { + + @Autowired + private CityAgencyService cityAgencyService; + + @GetMapping("/selectCityAgencyList") + @ApiOperation("查询城市代理") + public Result selectCityAgencyList(Integer page,Integer limit,String userName,String phone,Integer classify){ + return cityAgencyService.selectCityAgencyList(page, limit, userName, phone, classify); + } + + + @PostMapping("/insertCityAgency") + @ApiOperation("添加城市代理") + public Result insertCityAgency(@RequestBody CityAgency cityAgency){ + cityAgency.setCreateTime(DateUtils.format(new Date())); + cityAgencyService.save(cityAgency); + return Result.success(); + } + + @PostMapping("/updateCityAgency") + @ApiOperation("修改城市代理") + public Result updateCityAgency(@RequestBody CityAgency cityAgency){ + cityAgencyService.updateById(cityAgency); + return Result.success(); + } + + @PostMapping("/deleteCityAgency") + @ApiOperation("删除城市代理") + public Result deleteCityAgency(Long id){ + cityAgencyService.removeById(id); + return Result.success(); + } + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/app/controller/UserBrowseController.java b/src/main/java/com/sqx/modules/app/controller/UserBrowseController.java new file mode 100644 index 0000000..9b600d7 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/UserBrowseController.java @@ -0,0 +1,45 @@ +package com.sqx.modules.app.controller; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.service.UserBrowseService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +@RestController +@AllArgsConstructor +@RequestMapping("/userBrowse") +@Api(value = "访客|浏览", tags = {"访客|浏览"}) +public class UserBrowseController { + private UserBrowseService userBrowseService; + + @ApiOperation("查询我的访客") + @RequestMapping(value = "/myVisitor", method = RequestMethod.GET) + public Result selectMyVisitor(@ApiParam("用户id") Long userId, @ApiParam("页") Long page, @ApiParam("行") Long limit) { + return userBrowseService.selectMyVisitor(userId, page, limit); + } + + @RequestMapping(value = "/myBrowse", method = RequestMethod.GET) + @ApiOperation("浏览足迹") + public Result selectMyBrowse(Long userId, Long page, Long limit) { + return userBrowseService.selectMyBrowse(userId, page, limit); + } + + @ApiOperation("删除我的访客") + @RequestMapping(value = "/deleteMyVisitor", method = RequestMethod.POST) + public Result deleteMyVisitor(Long id) { + + return userBrowseService.deleteMyVisitor(id); + } + @ApiOperation(("删除足迹")) + @RequestMapping(value = "/deleteMyBrowse", method = RequestMethod.POST) + public Result deleteMyBrowse(Long id) { + + return userBrowseService.deleteMyBrowse(id); + } + + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/UserCertificationController.java b/src/main/java/com/sqx/modules/app/controller/UserCertificationController.java new file mode 100644 index 0000000..f4ee865 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/UserCertificationController.java @@ -0,0 +1,67 @@ +package com.sqx.modules.app.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserCertification; +import com.sqx.modules.app.service.UserCertificationService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@AllArgsConstructor +@RequestMapping("/userCertification") +@Api("实 名 认 证") +public class UserCertificationController { + private UserCertificationService userCertificationService; + + + /** + * 实名列表 + */ + @RequestMapping("/queryCertification") + @ApiOperation("实名列表") + public Result queryCertification(Long page, Long limit, @ApiParam("状态") String status, @ApiParam("姓名") String name) { + + return userCertificationService.queryCertification(page, limit, status, name); + } + + /** + * 查询已经进行实名的用户 + */ + @RequestMapping("/queryUserCertification") + @ApiOperation("查询已经进行实名的用户") + public Result queryUserCertification(Long page, Long limit, String name,String phone) { + if (page == null || limit == null) { + return Result.error("分页条件为空"); + } else { + IPage iPage = new Page<>(page, limit); + + return userCertificationService.queryUserCertification(iPage,name,phone); + } + } + + /** + * 审核实名认证 + */ + @RequestMapping("/auditorUserCertification") + @ApiOperation("审核实名认证") + public Result auditorUserCertification(Integer status, Long id, String remek) { + return userCertificationService.auditorUserCertification(status, id, remek); + } + + + @PostMapping("/updateUserCertification") + @ApiOperation("修改实名认证信息") + public Result updateUserCertification(@RequestBody UserCertification userCertification){ + userCertificationService.updateById(userCertification); + return Result.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/app/controller/UserController.java b/src/main/java/com/sqx/modules/app/controller/UserController.java new file mode 100644 index 0000000..8a47847 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/UserController.java @@ -0,0 +1,500 @@ +package com.sqx.modules.app.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserMoneyDao; +import com.sqx.modules.app.entity.UserCertification; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.response.HomeMessageResponse; +import com.sqx.modules.app.response.UserMessageResponse; +import com.sqx.modules.app.service.UserCertificationService; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.pay.service.PayDetailsService; +import com.sqx.modules.utils.EasyPoi.ExcelUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author fang + * @date 2020/7/30 + */ +@Slf4j +@RestController +@Api(value = "用户管理", tags = {"用户管理"}) +@RequestMapping(value = "/user") +public class UserController { + + @Autowired + private UserService userService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private PayDetailsService payDetailsService; + @Autowired + private OrdersService ordersService; + @Autowired + private LaundryRepository laundryRepository; + @Autowired + private UserCertificationService certificationService; + @Autowired + private OrdersDao ordersDao; + + @GetMapping("/selectShopList") + @ApiOperation("查询师傅列表") + public Result selectShopList(String userName, String phone, Long laundryId) { + return userService.selectShopList(userName, phone, laundryId); + } + + + @RequestMapping(value = "/{userId}", method = RequestMethod.GET) + @ApiOperation("获取用户详细信息") + @ResponseBody + public Result selectUserById(@ApiParam("用户id") @PathVariable Long userId) { + Map map = new HashMap<>(); + UserEntity userEntity = userService.queryByUserId(userId); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + Double money = 0.0; + BigDecimal safetyMoney = BigDecimal.ZERO; + if (userMoney != null) { + money = userMoney.getMoney().doubleValue(); + safetyMoney = userMoney.getSafetyMoney(); + } + //查询用户钱包 + Double m = money; + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = simpleDateFormat.format(new Date()); + //查询本月充值 + Double consume = payDetailsService.instantselectSumPay(date, userId); + //查询本月提现 + Double income = userMoneyDetailsService.monthIncome(date, userId); + //查询邀请人数 + int count = userService.queryInviterCount(userEntity.getInvitationCode()); + //本月接单 + int takeOrdersCount = ordersService.selectTakeOrdersCount(userId, date); + //本月订单 + int myOrdersCount = ordersService.selectMyOrdersCount(userId, date); + if (userEntity.getLaundryId() != null) { + Laundry laundry = laundryRepository.findById(userEntity.getLaundryId()).orElse(null); + if (laundry != null) { + userEntity.setLaundryName(laundry.getLaundryName()); + } + + } + int rideSumBucketCount = ordersDao.sumOrderBucketCount(userId, null, null); + + map.put("userEntity", userEntity); + map.put("money", m); + map.put("safetyMoney", safetyMoney); + map.put("consume", consume); + map.put("income", income); + map.put("count", count); + map.put("takeOrdersCount", takeOrdersCount); + map.put("myOrdersCount", myOrdersCount); + map.put("rideSumBucketCount", rideSumBucketCount); + return Result.success().put("data", map); + } + + @PostMapping("/updateSafetyMoney") + @ApiOperation("修改") + public Result updateSafetyMoney(Long userId, Integer type, BigDecimal money) { + userMoneyService.updateSafetyMoney(type, userId, money); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setClassify(4); + userMoneyDetails.setUserId(userId); + if (type == 1) { + userMoneyDetails.setTitle("[保证金]增加保证金"); + userMoneyDetails.setContent("系统增加保证金"); + } else { + userMoneyDetails.setTitle("[保证金]减少保证金"); + userMoneyDetails.setContent("系统减少保证金"); + } + userMoneyDetails.setType(type); + userMoneyDetails.setMoney(money); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + if (userMoney.getSafetyMoney().doubleValue() > 0) { + UserEntity userEntity = userService.selectUserById(userId); + userEntity.setIsSafetyMoney(1); + userService.updateById(userEntity); + } else { + UserEntity userEntity = userService.selectUserById(userId); + userEntity.setIsSafetyMoney(2); + userService.updateById(userEntity); + } + return Result.success(); + } + + + @RequestMapping(value = "/addCannotMoney/{userId}/{money}/{type}", method = RequestMethod.POST) + @ApiOperation("修改金额") + @ResponseBody + public Result addCannotMoney(@PathVariable("userId") Long userId, @PathVariable("money") Double money, @PathVariable("type") Integer type) { + if (type == 1) { + userMoneyService.updateMoney(1, userId, BigDecimal.valueOf(money)); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(BigDecimal.valueOf(money)); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setContent("管理端充值:" + money); + userMoneyDetails.setTitle("管理端充值金额"); + userMoneyDetails.setType(1); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + } else { + userMoneyService.updateMoney(2, userId, BigDecimal.valueOf(money)); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(BigDecimal.valueOf(money)); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setContent("管理端减少:" + money); + userMoneyDetails.setTitle("管理端减少金额"); + userMoneyDetails.setType(2); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + } + return Result.success(); + } + + @RequestMapping(value = "/selectUserList", method = RequestMethod.GET) + @ApiOperation("查询所有用户列表") + @ResponseBody + public Result selectUserList(Integer page, Integer limit, + + @ApiParam("用户id 手机号 昵称 模糊搜索") String phone, + @ApiParam("性别 1男 2女") Integer sex, + @ApiParam("来源") String platform, + @ApiParam("手机终端") String sysPhone, + @ApiParam("状态 1正常 2封禁") Integer status, + Integer isAuthentication, Integer isPromotion, + Integer isAgent, + String userName, + Long laundryId, + String isSafetyMoney, + Integer isVip, + String invitationCode, + String inviterCode, Integer hasTicket) { + return Result.success().put("data", userService.selectUserPage(page, limit, phone, sex, platform, sysPhone, + status, isAuthentication, isPromotion, isAgent, userName, laundryId, isSafetyMoney, isVip, invitationCode, inviterCode, hasTicket)); + } + + + @RequestMapping(value = "/deleteUserByUserId/{userId}", method = RequestMethod.POST) + @ApiOperation("删除用户") + @ResponseBody + public Result deleteUserByUserId(@PathVariable("userId") Long userId) { + userService.removeById(userId); + return Result.success(); + } + + @RequestMapping(value = "/updateUserByUserId", method = RequestMethod.POST) + @ApiOperation("修改用户") + @ResponseBody + public Result updateUserByUserId(@RequestBody UserEntity userEntity) { + if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(userEntity.getInvitationCode())) { + UserEntity byId = userService.getById(userEntity.getUserId()); + userService.update(null, Wrappers.lambdaUpdate() + .set(UserEntity::getInviterCode, userEntity.getInvitationCode()) + .eq(UserEntity::getInviterCode, byId.getInvitationCode())); + } + if (StringUtils.isNotEmpty(userEntity.getInviterCode())) { + UserEntity userEntity1 = userService.queryByInvitationCode(userEntity.getInviterCode()); + if (userEntity1 == null) { + return Result.error("邀请码用户不存在!"); + } + } + if (userEntity.getIsAgent() != null && userEntity.getIsAgent() != 1) { + userEntity.setProvince(null); + userEntity.setCity(null); + userEntity.setDistrict(null); + userService.cancelArea(userEntity); + + } + userService.updateById(userEntity); + return Result.success(); + } + + @ResponseBody + @PostMapping(value = "/updateAgent") + @ApiOperation("修改用户代理") + public Result updateAgent(@RequestBody UserEntity userEntity) { + int count = 0; + //代理省级单位 + if (StringUtils.isNotBlank(userEntity.getProvince()) && StringUtils.isBlank(userEntity.getCity()) && StringUtils.isBlank(userEntity.getDistrict())) { + count += userService.count(new QueryWrapper().eq("province", userEntity.getProvince())); + } + //代理市级单位 + if (StringUtils.isNotBlank(userEntity.getProvince()) && StringUtils.isNotBlank(userEntity.getCity()) && StringUtils.isBlank(userEntity.getDistrict())) { + count += userService.count(new QueryWrapper().eq("province", userEntity.getProvince()).eq("city", userEntity.getCity())); + } + //代理区/县级单位 + if (StringUtils.isNotBlank(userEntity.getProvince()) && StringUtils.isNotBlank(userEntity.getCity()) && StringUtils.isNotBlank(userEntity.getDistrict())) { + count += userService.count(new QueryWrapper().eq("province", userEntity.getProvince()).eq("city", userEntity.getCity()).eq("district", userEntity.getDistrict())); + count += userService.count(new QueryWrapper().eq("province", userEntity.getProvince()).eq("city", userEntity.getCity()).isNull("district")); + count += userService.count(new QueryWrapper().eq("province", userEntity.getProvince()).isNull("city").isNull("district")); + } + if (count > 0) { + return Result.error("当前区域已有代理"); + } + if (StringUtils.isBlank(userEntity.getProvince())) { + userEntity.setProvince(null); + } + if (StringUtils.isBlank(userEntity.getCity())) { + userEntity.setCity(null); + } + if (StringUtils.isBlank(userEntity.getDistrict())) { + userEntity.setDistrict(null); + } + return Result.upStatus(userService.cancelArea(userEntity)); + + } + + @RequestMapping(value = "/updateUserAuthentication", method = RequestMethod.POST) + @ApiOperation("改为师傅或取消师傅") + @ResponseBody + public Result updateUserAuthentication(@RequestBody UserEntity userEntity) { + userService.update(null, Wrappers.lambdaUpdate() + .set(UserEntity::getIsAuthentication, userEntity.getIsAuthentication()) + .eq(UserEntity::getUserId, userEntity.getUserId())); + return Result.success(); + } + + + @RequestMapping(value = "/updateUserStatusByUserId", method = RequestMethod.GET) + @ApiOperation("禁用或启用用户") + @ResponseBody + public Result updateUserByUserId(Long userId) { + UserEntity byId = userService.getById(userId); + if (byId.getStatus().equals(1)) { + byId.setStatus(2); + } else { + byId.setStatus(1); + } + userService.updateById(byId); + return Result.success(); + } + + + /** + * 获取openid + * + * @param code 微信code + * @return openid + */ + @GetMapping("/openId/{code:.+}/{userId}") + @ApiOperation("根据code获取openid") + public Result getOpenid(@PathVariable("code") String code, @PathVariable("userId") Long userId) { + return userService.getOpenId(code, userId); + } + + /** + * 信息分析 + * + * @return + */ + @GetMapping("/homeMessage") + @ApiOperation("信息分析") + public Result homeMessage() { + HomeMessageResponse homeMessageResponse = new HomeMessageResponse(); + // 0查总 1查天 2查月 3查年 + //设置总用户人数 + homeMessageResponse.setTotalUsers(userService.queryUserCount(0, null, null, null)); + //设置今日新增 + homeMessageResponse.setNewToday(userService.queryUserCount(1, null, null, null)); + //设置本月新增 + homeMessageResponse.setNewMonth(userService.queryUserCount(2, null, null, null)); + //设置本年新增 + homeMessageResponse.setNewYear(userService.queryUserCount(3, null, null, null)); + + //设置总收入 + homeMessageResponse.setTotalRevenue(userService.queryPayMoney(0)); + //设置今日收入 + homeMessageResponse.setTodayRevenue(userService.queryPayMoney(1)); + //设置本月收入 + homeMessageResponse.setMonthRevenue(userService.queryPayMoney(2)); + //设置本年收入 + homeMessageResponse.setYearRevenue(userService.queryPayMoney(3)); + + return Result.success().put("data", homeMessageResponse); + } + + /** + * 接单分析 + * + * @return + */ + @GetMapping("/takingOrdersMessage") + @ApiOperation("接单分析") + public Result takingOrdersMessage(Long page, Long limit, String date, Long type) { + Page> iPage = new Page<>(page, limit); + return userService.takingOrdersMessage(iPage, type, date); + } + + /** + * 用户分析 + */ + @GetMapping("/userMessage") + @ApiOperation("用户分析") + public Result userMessage(String date, Integer flag) { + int sumUserCount = userService.queryUserCount(flag, date, null, null); + int h5Count = userService.queryUserCount(flag, date, "H5", null); + int appCount = userService.queryUserCount(flag, date, "app", null); + int wxCount = userService.queryUserCount(flag, date, "小程序", null); + int memberCount = userService.userMessage(date, flag); + int userCount = sumUserCount - memberCount; + int sumAuthUserCount = userService.queryUserCount(flag, date, null, 1); + int h5AuthCount = userService.queryUserCount(flag, date, "H5", 1); + int appAuthCount = userService.queryUserCount(flag, date, "app", 1); + int wxAuthCount = userService.queryUserCount(flag, date, "小程序", 1); + Map result = new HashMap<>(); + result.put("sumUserCount", sumUserCount); + result.put("h5Count", h5Count); + result.put("appCount", appCount); + result.put("wxCount", wxCount); + result.put("memberCount", memberCount); + result.put("userCount", userCount); + result.put("sumAuthUserCount", sumAuthUserCount); + result.put("h5AuthCount", h5AuthCount); + result.put("appAuthCount", appAuthCount); + result.put("wxAuthCount", wxAuthCount); + return Result.success().put("data", result); + } + + @PostMapping(value = "/updateUserBucket") + @ApiOperation("修改用户压桶数") + public Result updateUserBucket(Long updateUserId, Long userId, Integer num, Long ordersId) { + return userService.updateUserBucket(1, updateUserId, userId, num, ordersId); + } + + @PostMapping("/updateUserLaundry") + @ApiOperation("修改师傅站点") + public Result updateUserLaundry(Long userId, Long laundryId) { + Laundry laundry = laundryRepository.findById(laundryId).orElse(null); + UserEntity userInfo = userService.getById(userId); + if (userInfo.getLaundryId() != null && !userInfo.getLaundryId().equals(laundry.getLaundryId())) { + Laundry oldLaundry = laundryRepository.findById(userInfo.getLaundryId()).orElse(null); + if (oldLaundry != null) { + StringBuilder stringBuilders = new StringBuilder(); + for (String userIds : oldLaundry.getLaundryUserIds().split(",")) { + if (!userIds.equals(String.valueOf(userId))) { + stringBuilders.append(userIds).append(","); + } + } + String str = stringBuilders.toString(); + if (StringUtils.isNotEmpty(str) && stringBuilders.charAt(stringBuilders.length() - 1) == ',') { + str = stringBuilders.substring(0, stringBuilders.length() - 1); + } + oldLaundry.setLaundryUserIds(str); + laundryRepository.save(oldLaundry); + } + } + StringBuilder stringBuilders = new StringBuilder(); + for (String userIds : laundry.getLaundryUserIds().split(",")) { + stringBuilders.append(userIds).append(","); + } + stringBuilders.append(userId); + laundry.setLaundryUserIds(stringBuilders.toString()); + laundryRepository.save(laundry); + userInfo.setLaundryId(laundryId); + userService.updateById(userInfo); + return Result.success(); + } + + @ApiOperation("赠送用户会员") + @PostMapping("/giveUserVip") + public Result giveUserVip(Long userId, Integer day) { + return userService.giveUserVip(userId, day); + } + + + @ApiOperation("取消用户会员") + @PostMapping("/cancelUserVip") + public Result cancelUserVip(Long userId) { + return userService.cancelUserVip(userId); + } + + @ApiOperation("修改用户实名信息") + @PostMapping("/updateCertification") + public Result updateCertification(@RequestBody UserCertification userCertification) { + return certificationService.updateCertification(userCertification); + } + + @ApiOperation("保证金统计") + @GetMapping("/safetyMoneyStatistics") + public Result safetyMoneyStatistics() { + return Result.success().put("data", certificationService.safetyMoneyStatistics()); + } + @ApiOperation(value = "用户信息--导入") + @PostMapping(value = "/userExcelIn") + public Result userExcelIn(@ApiParam(name = "file", value = "excel文件") @RequestPart MultipartFile file) throws Exception { + try { + if (file == null) { + return Result.error("文件不能为空!"); + } + return userService.userExcelIn(file); + } catch (Exception e) { + log.error("用户息列表--导入异常:", e); + } + + // 返回结果 + return Result.error("导入失败"); + } + + + @ApiOperation("科室信息列表--导出") + @GetMapping("/departmentExcelOut") + public void departmentExcelOut(String phone, + Integer sex, + String platform, + String sysPhone, + Integer status, + Integer isAuthentication, Integer isPromotion, + Integer isAgent, + String userName, + Long laundryId, + String isSafetyMoney, + Integer isVip, + String invitationCode, + String search, + String inviterCode, Integer hasTicket, HttpServletResponse response) throws IOException { + List list = userService.userEntityExcelOut(search, phone, sex, platform, sysPhone, + status, isAuthentication, isPromotion, isAgent, userName, laundryId, isSafetyMoney, isVip, invitationCode, inviterCode, hasTicket); + ExcelUtils.exportExcel(list, "用户统计表", "用户统计Sheet", UserEntity.class, "用户统计表", response); + } + + @ApiOperation("获取桶数统计") + @GetMapping("/getUserBucket") + public Result getUserBucket(Integer flag, String date) { + return Result.success().put("data", userService.getUserBucket(flag, date)); + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/app/controller/UserFollowController.java b/src/main/java/com/sqx/modules/app/controller/UserFollowController.java new file mode 100644 index 0000000..b2e143e --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/UserFollowController.java @@ -0,0 +1,47 @@ +package com.sqx.modules.app.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.service.UserFollowService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@AllArgsConstructor +@RequestMapping("/userFollow") +@Api(value = "关注|粉丝", tags = {"关注|粉丝"}) +public class UserFollowController { + private UserFollowService userFollowService; + + + /** + * 查看我的关注 + */ + @GetMapping("/selectMyFollow") + @ApiOperation("查看我的关注") + public Result selectMyFollow(Long userId, Long page, Long limit) { + return userFollowService.selectMyFollow(userId, page, limit); + } + + /** + * 查看我的粉丝 + */ + @GetMapping("/selectFans") + @ApiOperation("查看我的粉丝") + public Result selectFans(Long userId, Long page, Long limit) { + return userFollowService.selectFans(userId, page, limit); + } + + /** + * 关注 / 取消关注 + **/ + + @PostMapping("/insert") + @ApiOperation("关注/取消关注") + public Result insert(Long userId, Long followUserId) { + return userFollowService.insert(userId, followUserId); + } + +} diff --git a/src/main/java/com/sqx/modules/app/controller/UserMoneyController.java b/src/main/java/com/sqx/modules/app/controller/UserMoneyController.java new file mode 100644 index 0000000..e1b4452 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/UserMoneyController.java @@ -0,0 +1,22 @@ +package com.sqx.modules.app.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/admin/userMoney/") +@Api("app 钱包 ") +public class UserMoneyController { + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private UserMoneyService userMoneyService; + +} diff --git a/src/main/java/com/sqx/modules/app/controller/UserMoneyDetailsController.java b/src/main/java/com/sqx/modules/app/controller/UserMoneyDetailsController.java new file mode 100644 index 0000000..fab3411 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/UserMoneyDetailsController.java @@ -0,0 +1,57 @@ +package com.sqx.modules.app.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/Details") +@Api("钱包明细") +public class UserMoneyDetailsController { + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private UserService userService; + @Autowired + private LaundryRepository laundryRepository; + + @ApiOperation("钱包明细") + @GetMapping("/queryUserMoneyDetails") + public Result queryUserMoneyDetails(Integer page, Integer limit, Long userId,Integer classify,Integer type,String phone,String ordersNo,String userName) { + + return userMoneyDetailsService.queryUserMoneyDetails(page, limit, userId,classify,type,phone,ordersNo, userName); + } + + @ApiOperation("站点累计收益") + @GetMapping("/selectLaundrySumMoney") + public Result selectLaundrySumMoney(Long userId){ + UserEntity userById = userService.selectUserById(userId); + Laundry laundry = laundryRepository.findById(userById.getLaundryId()).orElse(null); + if(laundry==null){ + return Result.success(); + } + Double sumMoney = userMoneyDetailsService.selectLaundrySumMoney(laundry.getLaundryUserId()); + return Result.success().put("data",sumMoney); + } + + + @ApiOperation("钱包明细") + @GetMapping("/selectLaundryMoneyDetails") + public Result selectLaundryMoneyDetails(Integer page, Integer limit, Long userId,Integer classify,String phone,String ordersNo,String userName) { + UserEntity userById = userService.selectUserById(userId); + Laundry laundry = laundryRepository.findById(userById.getLaundryId()).orElse(null); + if(laundry==null){ + return Result.success(); + } + return userMoneyDetailsService.queryUserMoneyDetails(page, limit, laundry.getLaundryUserId(),classify,null,phone,ordersNo,userName); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/VipDetailsController.java b/src/main/java/com/sqx/modules/app/controller/VipDetailsController.java new file mode 100644 index 0000000..381d5b5 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/VipDetailsController.java @@ -0,0 +1,48 @@ +package com.sqx.modules.app.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.VipDetails; +import com.sqx.modules.app.service.VipDetailsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "会员管理", tags = {"会员管理"}) +@RequestMapping(value = "/vipDetails") +public class VipDetailsController { + + @Autowired + private VipDetailsService vipDetailsService; + + @ApiParam("添加会员的详情信息") + @PostMapping("/insertVipDetails") + public Result insertVipDetails(@RequestBody VipDetails vipDetails) { + return vipDetailsService.insertVipDetails(vipDetails); + } + + + @ApiParam("修改会员的详情信息") + @PostMapping("/updateVipDetails") + public Result updateVipDetails(@RequestBody VipDetails vipDetails) { + vipDetailsService.updateById(vipDetails); + return Result.success(); + } + + @ApiParam("删除的详情信息") + @PostMapping("/deleteVipDetails") + public Result deleteVipDetails(Long id) { + vipDetailsService.removeById(id); + return Result.success(); + } + + @ApiParam("查询会员列表") + @GetMapping("/selectVipDetailsList") + public Result selectVipDetailsList(Integer page,Integer limit) { + return Result.success().put("data",new PageUtils(vipDetailsService.page(new Page<>(page,limit)))); + } + +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppAddressController.java b/src/main/java/com/sqx/modules/app/controller/app/AppAddressController.java new file mode 100644 index 0000000..3ec0437 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppAddressController.java @@ -0,0 +1,105 @@ +package com.sqx.modules.app.controller.app; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.annotation.LoginUser; +import com.sqx.modules.app.entity.Address; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.AddressService; +import com.sqx.modules.app.service.AppService; +import com.sqx.modules.app.service.UserService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 地址 + */ +@RestController +@RequestMapping("/app/address") +@Api(value = "用户地址", tags = {"用户地址"}) +public class AppAddressController { + + @Autowired + private AddressService addressService; + + @Login + @PostMapping("/insertAddress") + @ApiOperation("添加地址") + public Result insertAddress(@LoginUser UserEntity user,@RequestBody Address address){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + address.setCreateTime(sdf.format(new Date())); + if(address.getIsDefault()==1){ + addressService.updateAddressIsDefault(user.getUserId()); + } + address.setUserId(user.getUserId()); + addressService.save(address); + return Result.success(); + } + + @Login + @PostMapping("/updateAddress") + @ApiOperation("修改地址") + public Result updateAddress(@LoginUser UserEntity user,@RequestBody Address address){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + address.setCreateTime(sdf.format(new Date())); + if(address.getIsDefault()==1){ + addressService.updateAddressIsDefault(user.getUserId()); + } + address.setUserId(user.getUserId()); + addressService.updateById(address); + return Result.success(); + } + + @Login + @PostMapping("/deleteAddress") + @ApiOperation("删除我的地址") + public Result deleteAddress(Long addressId){ + addressService.removeById(addressId); + return Result.success(); + } + + + @Login + @GetMapping("/selectAddressListById") + @ApiOperation("获取我的所有地址") + public Result selectAddressListById(@LoginUser UserEntity user,Integer page,Integer limit){ + IPage
addressIPage = addressService.page(new Page<>(page, limit), new QueryWrapper
().eq("user_id", user.getUserId())); + return Result.success().put("data",new PageUtils(addressIPage)); + } + + @Login + @GetMapping("/selectAddressById") + @ApiOperation("获取我的默认地址") + public Result selectAddressById(@LoginUser UserEntity user){ + Address one = addressService.getOne(new QueryWrapper
().eq("user_id", user.getUserId()).orderByDesc("is_default").last(" limit 1")); + return Result.success().put("data",one); + } + + + @Login + @GetMapping("selectAddressByAddressId") + @ApiOperation("根据地址id查询地址详细信息") + public Result selectAddressByAddressId(Long addressId){ + return Result.success().put("data",addressService.getById(addressId)); + } + + + + + + + + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppCityAgencyController.java b/src/main/java/com/sqx/modules/app/controller/app/AppCityAgencyController.java new file mode 100644 index 0000000..c644ca4 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppCityAgencyController.java @@ -0,0 +1,66 @@ +package com.sqx.modules.app.controller.app; + + +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.CityAgency; +import com.sqx.modules.app.service.CityAgencyService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; + +/** + * @author fang + * @date 2021/5/19 + */ +@Slf4j +@RestController +@Api(value = "代理申请", tags = {"代理申请"}) +@RequestMapping(value = "/app/cityAgency") +public class AppCityAgencyController { + + @Autowired + private CityAgencyService cityAgencyService; + + @Login + @GetMapping("/selectCityAgencyList") + @ApiOperation("查询城市代理") + public Result selectCityAgencyList(Integer page,Integer limit,String userName,String phone,Integer classify){ + return cityAgencyService.selectCityAgencyList(page, limit, userName, phone, classify); + } + + @Login + @PostMapping("/insertCityAgency") + @ApiOperation("添加城市代理") + public Result insertCityAgency(@RequestBody CityAgency cityAgency,@RequestAttribute Long userId){ + cityAgency.setUserId(userId); + cityAgency.setCreateTime(DateUtils.format(new Date())); + cityAgencyService.save(cityAgency); + return Result.success(); + } + + @Login + @PostMapping("/updateCityAgency") + @ApiOperation("修改城市代理") + public Result updateCityAgency(@RequestBody CityAgency cityAgency){ + cityAgencyService.updateById(cityAgency); + return Result.success(); + } + + @Login + @PostMapping("/deleteCityAgency") + @ApiOperation("删除城市代理") + public Result deleteCityAgency(Long id){ + cityAgencyService.removeById(id); + return Result.success(); + } + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppController.java b/src/main/java/com/sqx/modules/app/controller/app/AppController.java new file mode 100644 index 0000000..7718d14 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppController.java @@ -0,0 +1,170 @@ +package com.sqx.modules.app.controller.app; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.annotation.LoginUser; +import com.sqx.modules.app.dao.UserCertificationDao; +import com.sqx.modules.app.entity.UserCertification; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.AppService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.utils.MD5Util; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +/** + * APP登录授权 + */ +@RestController +@RequestMapping("/app/user") +@Api(value = "APP管理", tags = {"APP管理"}) +public class AppController { + + @Autowired + private UserService userService; + @Autowired + private AppService appService; + @Autowired + private CommonInfoService commonInfoService; + + @RequestMapping(value = "/selectUserByIds", method = RequestMethod.GET) + @ApiOperation("获取用户详细信息") + @ResponseBody + public Result selectUserByIds(Long userId) { + return Result.success().put("data", userService.selectUserById(userId)); + } + + @Login + @RequestMapping(value = "/updatePwd", method = RequestMethod.POST) + @ResponseBody + @ApiOperation("用户端修改密码") + public Result updatePwd(@LoginUser UserEntity user, String pwd, String oldPwd) { + if (!user.getPassword().equals(DigestUtils.sha256Hex(oldPwd))) { + return Result.error("原始密码不正确!"); + } + if (pwd.equals(oldPwd)) { + return Result.error("新密码不能与旧密码相同!"); + } + user.setPassword(DigestUtils.sha256Hex(pwd)); + userService.updateById(user); + return Result.success(); + } + + @Login + @RequestMapping(value = "/updatePhone", method = RequestMethod.POST) + @ApiOperation("用户端换绑手机号") + @ResponseBody + public Result updatePhone(@RequestAttribute("userId") Long userId, @RequestParam String phone, @RequestParam String msg) { + return userService.updatePhone(phone, msg, userId); + } + + @Login + @RequestMapping(value = "/updateUser", method = RequestMethod.POST) + @ApiOperation("用户修改个人信息") + @ResponseBody + public Result updateUser(@RequestBody UserEntity userEntity, @RequestAttribute("userId") Long userId) { + userEntity.setUserId(userId); + userService.updateById(userEntity); + return Result.success(); + } + + @Login + @RequestMapping(value = "/updateUserImageUrl", method = RequestMethod.POST) + @ApiOperation("用户修改头像") + @ResponseBody + public Result updateUserImageUrl(@LoginUser UserEntity user, String avatar) { + user.setAvatar(avatar); + userService.updateById(user); + return Result.success(); + } + + @Login + @RequestMapping(value = "/updateUserName", method = RequestMethod.POST) + @ApiOperation("用户修改昵称") + @ResponseBody + public Result updateUserName(@LoginUser UserEntity user, String userName) { + user.setUserName(userName); + userService.updateById(user); + return Result.success(); + } + + @Login + @RequestMapping(value = "/selectUserById", method = RequestMethod.GET) + @ApiOperation("获取用户详细信息") + @ResponseBody + public Result selectUserById(@LoginUser UserEntity user) { + if (user != null) { + if (user.getRate() == null) { + user.setRate(new BigDecimal(commonInfoService.findOne(206).getValue())); + userService.updateById(user); + } + if (user.getZhiRate() == null) { + user.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue())); + userService.updateById(user); + } + if (user.getFeiRate() == null) { + user.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue())); + userService.updateById(user); + } + } + + return Result.success().put("data", user); + } + + + @RequestMapping(value = "/selectNewApp", method = RequestMethod.GET) + @ApiOperation("升级检测") + @ResponseBody + public Result selectNewApp() { + return Result.success().put("data", appService.selectNewApp()); + } + + @RequestMapping(value = "/updateClientId", method = RequestMethod.GET) + @ApiOperation("绑定ClientId") + @ResponseBody + public Result updateClientId(String clientId, Long userId) { + UserEntity userEntity = new UserEntity(); + userEntity.setUserId(userId); + userEntity.setClientid(clientId); + return Result.success(); + } + + + @Login + @GetMapping(value = "/updateUserBucket") + @ApiOperation("修改用户压桶数") + public Result updateUserBucket(@RequestAttribute("userId") Long updateUserId, Long userId, Integer num,Long ordersId) { + return userService.updateUserBucket(2, updateUserId, userId, num, ordersId); + } + + + @ApiOperation("获取附近师傅列表") + @GetMapping("getNearbyWorker") + public Result getNearbyWorker(Integer page, Integer limit, Double lng, Double lat) { + return Result.success().put("data", userService.getNearbyWorker(page, limit, lng, lat)); + } + + @Login + @ApiOperation("购买桶") + @PostMapping("buyBucket") + public Result buyBucket(@RequestAttribute("userId") Long userId, Integer num) { + return userService.buyBucket(userId, num); + } + +// @Login +// @ApiOperation("退桶") +// @PostMapping("backBucket") +// public Result backBucket(@RequestAttribute("userId") Long userId, Integer num) { +// return userService.backBucket(userId, num); +// } +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppLoginController.java b/src/main/java/com/sqx/modules/app/controller/app/AppLoginController.java new file mode 100644 index 0000000..ed87869 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppLoginController.java @@ -0,0 +1,243 @@ +package com.sqx.modules.app.controller.app; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.IAppleService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.app.utils.UserConstantInterface; +import com.sqx.modules.app.utils.WxPhone; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.utils.HttpClientUtil; +import com.sqx.modules.utils.MD5Util; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import weixin.popular.api.SnsAPI; +import weixin.popular.bean.sns.SnsToken; + +import java.util.HashMap; +import java.util.Map; + +/** + * APP登录授权 + * + */ +@RestController +@RequestMapping("/app/Login") +@Api("APP登录接口") +@Slf4j +public class AppLoginController { + @Autowired + private UserService userService; + @Autowired + private IAppleService appleService; + @Autowired + private CommonInfoService commonInfoService; + + + @ApiOperation("微信小程序登陆") + @RequestMapping(value = "/wxLogin", method = RequestMethod.GET) + public Result wxLogin(@ApiParam("小程序code码") String code, Integer type) { + return userService.wxLogin(code, type); + } + + + @ApiOperation("小程序登录新增或修改个人信息") + @RequestMapping(value = "/insertWxUser", method = RequestMethod.POST) + public Result insertWxUser(@RequestBody UserEntity userInfo) { + return userService.wxRegister(userInfo); + } + + + @RequestMapping(value = "/appleLogin", method = RequestMethod.GET) + @ApiOperation("苹果登陆获取appleUserId") + public Result loginVerify(@RequestParam("identityToken") String identityToken) { + try { + log.info("苹果token:{}", identityToken); + JSONObject jsonObject = JSON.parseObject(identityToken); + JSONObject userInfo = jsonObject.getJSONObject("userInfo"); + String identityTokens = userInfo.getString("identityToken"); + return appleService.getAppleUserInfo(identityTokens); + } catch (Exception e) { + log.error("苹果token校验失败:{}", identityToken, e); + return Result.error("苹果账号验证失败,请退出重试!"); + } + } + + + @ApiOperation("苹果登录") + @RequestMapping(value = "/insertAppleUser", method = RequestMethod.GET) + public Result insertAppleUser(@RequestParam String appleId) { + return userService.iosRegister(appleId); + } + + @RequestMapping(value = "/iosBindMobile", method = RequestMethod.POST) + @ApiOperation("苹果登录绑定手机号") + @ResponseBody + public Result iosBindMobile(@RequestParam String phone, @RequestParam String code, @RequestParam String appleId, @RequestParam String platform, @RequestParam Integer sysPhone) { + return userService.iosBindMobile(phone, code, appleId, platform, sysPhone); + } + + + @RequestMapping(value = "/wxAppLogin", method = RequestMethod.POST) + @ApiOperation("微信APP登录") + @ResponseBody + public Result wxAppLogin(@RequestParam String wxOpenId, @RequestParam String token) { + return userService.wxAppLogin(wxOpenId, token); + } + + + @RequestMapping(value = "/wxBindMobile", method = RequestMethod.POST) + @ApiOperation("微信登录绑定手机号") + @ResponseBody + public Result wxBindMobile(@RequestParam String phone, @RequestParam String code, @RequestParam String wxOpenId, @RequestParam String token, @RequestParam String platform, @RequestParam Integer sysPhone) { + return userService.wxBindMobile(phone, code, wxOpenId, token, platform, sysPhone); + } + + @ApiOperation("用户端openid登录呢") + @RequestMapping(value = "/openid/login", method = RequestMethod.GET) + @ResponseBody + public Result loginByOpenId(@RequestParam String openId) { + return userService.loginByOpenId(openId); + } + + + @RequestMapping(value = "/registerCode", method = RequestMethod.POST) + @ApiOperation("app或h5注册或登录") + @ResponseBody + public Result registerCode(String phone, String msg, String platform, Integer sysPhone, String openId, String inviterCode, Integer courseType) { + return userService.registerCode(phone, msg, platform, sysPhone, openId, inviterCode, courseType); + } + + @ApiOperation("用户端发送验证码") + @RequestMapping(value = "/sendMsg/{phone}/{state}", method = RequestMethod.GET) + @ResponseBody + public Result sendMsg(@PathVariable String phone, @PathVariable String state) { + return userService.sendMsg(phone, state); + } + + @ApiOperation("解密手机号") + @RequestMapping(value = "/selectPhone", method = RequestMethod.POST) + public Result getPhoneNumberBeanS5(@RequestBody WxPhone wxPhone) { + return UserConstantInterface.decryptS5(wxPhone.getDecryptData(), wxPhone.getKey(), wxPhone.getIv()); + } + + @ApiParam("登录app") + @RequestMapping(value = "/loginApp", method = RequestMethod.POST) + public Result loginApp(@RequestParam String phone, @RequestParam String password) { + return userService.loginApp(phone, password); + } + + @CrossOrigin + @ApiParam("注册app") + @RequestMapping(value = "/registApp", method = RequestMethod.POST) + public Result registApp(@RequestParam String userName, @RequestParam String phone, @RequestParam String password, String msg, @RequestParam String platform, String invitation, Integer courseType) { + return userService.registApp(userName, phone, password, msg, platform, invitation, courseType); + } + + @ApiOperation("用户端忘记密码") + @RequestMapping(value = "/forgetPwd", method = RequestMethod.POST) + @ResponseBody + public Result forgetPwd(String pwd, String phone, String msg) { + return userService.forgetPwd(pwd, phone, msg); + } + + + @GetMapping("/selectCity") + @ApiOperation("根据经纬度获取城市") + public Result selectCity(String lat, String lng) { + String way = commonInfoService.findOne(414).getValue(); + if ("1".equals(way)) { + CommonInfo one = commonInfoService.findOne(217); + String url = "https://apis.map.qq.com/ws/geocoder/v1/"; + Map maps = new HashMap<>(); + maps.put("location", lat + "," + lng); + maps.put("key", one.getValue()); + String data = HttpClientUtil.doGet(url, maps); + JSONObject jsonObject = JSON.parseObject(data); + String status = jsonObject.getString("status"); + if ("0".equals(status)) { + JSONObject result = jsonObject.getJSONObject("result"); + JSONObject adInfo = result.getJSONObject("ad_info"); + return Result.success().put("data", adInfo); + } else { + log.error("转换失败!!!原因:" + jsonObject.getString("message")); + } + return Result.error("获取定位失败!"); + } else { + String value = commonInfoService.findOne(415).getValue(); + String url="http://api.tianditu.gov.cn/geocoder"; + Map param=new HashMap<>(); + JSONObject postStr=new JSONObject(); + postStr.put("lon",lng); + postStr.put("lat",lat); + postStr.put("ver","1"); + param.put("postStr",postStr.toJSONString()); + param.put("type","geocode"); + param.put("tk",value); + String s = HttpClientUtil.doGet(url,param); + JSONObject jsonObject = JSONObject.parseObject(s); + String status = jsonObject.getString("status"); + if ("0".equals(status)) { + JSONObject result = jsonObject.getJSONObject("result"); + JSONObject addressComponent = result.getJSONObject("addressComponent"); + String province = addressComponent.getString("province"); + String city = addressComponent.getString("city"); + String county = addressComponent.getString("county"); + if (StringUtils.isEmpty(city)) { + if ("新疆维吾尔自治区".equals(province) || "台湾省".equals(province)) { + city = addressComponent.getString("county"); + } else { + city = addressComponent.getString("province"); + } + } + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("province", province); + jsonObject1.put("city", city); + jsonObject1.put("district", county); + return Result.success().put("data", jsonObject1); + } + return Result.error("获取定位失败!"); + } + } + + + @GetMapping("/getOpenId") + @ApiOperation("公众号根据code换取openId") + public Result getOpenId(String code, Long userId) { + try { + //微信appid + CommonInfo one = commonInfoService.findOne(5); + //微信秘钥 + CommonInfo two = commonInfoService.findOne(21); + SnsToken snsToken = SnsAPI.oauth2AccessToken(one.getValue(), two.getValue(), code); + String openid = snsToken.getOpenid(); + return Result.success().put("data", openid); + } catch (Exception e) { + throw new RuntimeException("GET_OPENID_FAIL"); + } + + } + + + @GetMapping("/bindOpenId") + @ApiOperation("用户绑定公众号openId") + public Result bindOpenId(Long userId, String openId) { + UserEntity userEntity = new UserEntity(); + userEntity.setUserId(userId); + userEntity.setOpenId(openId); + userService.updateById(userEntity); + return Result.success(); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppUserBrowseController.java b/src/main/java/com/sqx/modules/app/controller/app/AppUserBrowseController.java new file mode 100644 index 0000000..3cba3e9 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppUserBrowseController.java @@ -0,0 +1,55 @@ +package com.sqx.modules.app.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.UserBrowse; +import com.sqx.modules.app.service.UserBrowseService; +import com.sqx.modules.app.service.UserFollowService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@AllArgsConstructor +@RequestMapping("/app/userBrowse") +@Api(value = "app 访问 | 浏览 ", tags = {"app 访问 | 浏览 "}) +public class AppUserBrowseController { + private UserBrowseService userBrowseService; + + @ApiOperation("查询我的访客") + @Login + @RequestMapping("/myVisitor") + public Result selectMyVisitor(@RequestAttribute Long userId, Long page, Long limit) { + return userBrowseService.selectMyVisitor(userId, page, limit); + } + + @Login + @RequestMapping("/myBrowse") + @ApiOperation("浏览足迹") + public Result selectMyBrowse(@RequestAttribute Long userId, Long page, Long limit) { + return userBrowseService.selectMyBrowse(userId, page, limit); + } + + @Login + @RequestMapping("/selectAmount") + @ApiOperation("粉丝量 关注量 访客量 足迹量") + public Result selectAmount(@RequestAttribute Long userId) { + return userBrowseService.selectAmount(userId); + } + + @ApiOperation("删除我的访客") + @RequestMapping(value = "/deleteMyVisitor", method = RequestMethod.POST) + public Result deleteMyVisitor(Long id) { + return userBrowseService.deleteMyVisitor(id); + } + + @ApiOperation(("删除我的足迹")) + @RequestMapping(value = "/deleteMyBrowse", method = RequestMethod.POST) + public Result deleteMyBrowse(Long id) { + + return userBrowseService.deleteMyBrowse(id); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppUserCertificationController.java b/src/main/java/com/sqx/modules/app/controller/app/AppUserCertificationController.java new file mode 100644 index 0000000..539af4d --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppUserCertificationController.java @@ -0,0 +1,54 @@ +package com.sqx.modules.app.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.UserCertification; +import com.sqx.modules.app.service.UserCertificationService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +@RestController +@AllArgsConstructor +@RequestMapping("/app/userCertification") +@Api("app实 名 认 证") +public class AppUserCertificationController { + + private UserCertificationService userCertificationService; + + /** + * 实名认证 + **/ + @RequestMapping("/insert") + @Login + @ApiOperation("实名认证") + public Result insert(@RequestAttribute Long userId, @RequestBody UserCertification userCertification) { + userCertification.setUserId(userId); + return userCertificationService.insert(userCertification); + } + + /** + * 是否进行实名 + */ + @RequestMapping("/isInsert") + @Login + @ApiOperation("是否进行实名") + public Result isInsert(@RequestAttribute Long userId) { + return userCertificationService.isInsert(userId); + } + + /** + * 查询自己的实名信息 + */ + @RequestMapping("/queryInsert") + @Login + @ApiOperation("查询自己的实名信息") + public Result queryInsert(@RequestAttribute Long userId) { + + return userCertificationService.queryInsert(userId); + } +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppUserFollowController.java b/src/main/java/com/sqx/modules/app/controller/app/AppUserFollowController.java new file mode 100644 index 0000000..471da7c --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppUserFollowController.java @@ -0,0 +1,56 @@ +package com.sqx.modules.app.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.UserFollow; +import com.sqx.modules.app.service.UserFollowService; +import io.swagger.annotations.Api; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@AllArgsConstructor +@RequestMapping("/app/userFollow") +@Api("app 关注") +public class AppUserFollowController { + private UserFollowService userFollowService; + + /** + * 关注 / 取消关注 + **/ + + @RequestMapping("/insert") + @Login + public Result insert(@RequestAttribute Long userId, @RequestParam Long followUserId) { + return userFollowService.insert(userId, followUserId); + } + + /** + * 查看我的关注 + */ + @RequestMapping("/selectMyFollow") + @Login + public Result selectMyFollow(@RequestAttribute Long userId,Long page,Long limit) { + return userFollowService.selectMyFollow(userId,page,limit); + } + /** + * 查看我的粉丝 + */ + @RequestMapping("/selectFans") + @Login + public Result selectFans(@RequestAttribute Long userId,Long page,Long limit) { + return userFollowService.selectFans(userId,page,limit); + } + /** + * 查看我是否关注 + */ + @RequestMapping("/selectFollowUser") + @Login + public Result selectFollowUser(@RequestAttribute Long userId,@RequestParam Long followUserId) { + return userFollowService.selectFollowUser(userId,followUserId); + } + +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppUserMoneyController.java b/src/main/java/com/sqx/modules/app/controller/app/AppUserMoneyController.java new file mode 100644 index 0000000..2999abf --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppUserMoneyController.java @@ -0,0 +1,127 @@ +package com.sqx.modules.app.controller.app; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/app/userMoney") +@Api("app 钱包 ") +public class AppUserMoneyController { + + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private UserService userService; + @Autowired + private LaundryRepository laundryRepository; + + + @Login + @ApiOperation("站点累计收益") + @GetMapping("/selectLaundrySumMoney") + public Result selectLaundrySumMoney(@RequestAttribute Long userId) { + UserEntity userById = userService.selectUserById(userId); + Laundry laundry = laundryRepository.findById(userById.getLaundryId()).orElse(null); + if (laundry == null) { + return Result.success(); + } + Double sumMoney = userMoneyDetailsService.selectLaundrySumMoney(laundry.getLaundryUserId()); + return Result.success().put("data", sumMoney); + } + + + @Login + @ApiOperation("钱包明细") + @GetMapping("/queryUserMoneyDetails") + public Result queryUserMoneyDetails(Integer page, Integer limit,@RequestAttribute Long userId,Integer classify,Integer type,String phone,String ordersNo,String userName) { + + return userMoneyDetailsService.queryUserMoneyDetails(page, limit, userId,classify,type,phone,ordersNo, userName); + } + + + @GetMapping("/selectMyMoney") + @Login + @ApiOperation("我的钱包余额") + public Result selectMyMoney(@RequestAttribute Long userId) { + return Result.success().put("data", userMoneyService.selectUserMoneyByUserId(userId)); + } + + /** + * 我的收益 + */ + @GetMapping("/selectMyProfit") + @Login + @ApiOperation("我的收益") + public Result selectMyProfit(@RequestAttribute Long userId) { + return Result.success().put("data", userMoneyService.selectMyProfit(userId)); + } + + /** + * 付款接单 + */ + @GetMapping("/payTakingOrder") + @Login + @ApiOperation("付款接单或会员") + public Result payTakingOrder(@RequestAttribute Long userId, Long orderId) { + return Result.success().put("data", userMoneyService.payTakingOrder(userId, orderId)); + } + + + + /** + * 余额明细 + */ + @GetMapping("/balanceDetailed") + @Login + @ApiOperation("余额明细") + public Result balanceDetailed(@RequestAttribute Long userId, Long page, Long limit) { + Page pages = new Page<>(page, limit); + return Result.success().put("data", userMoneyService.balanceDetailed(userId, pages)); + } + + + /** + * 收益明细 + */ + @GetMapping("/profitDetailed") + @Login + @ApiOperation("收益明细") + public Result profitDetailed(@RequestAttribute Long userId, Long page, Long limit) { + if (page != null || limit != null) { + return Result.error("分页条件为空"); + } else { + IPage ipage = new Page(page, limit); + return Result.success().put("data", userMoneyService.profitDetailed(userId, ipage)); + } + } + + @Login + @PostMapping("/paySafetyMoney") + @ApiOperation("缴纳保证金") + public Result paySafetyMoney(@RequestAttribute Long userId){ + return userMoneyService.paySafetyMoney(userId); + } + + @Login + @PostMapping("/refundSafetMoney") + @ApiOperation("退款保证金") + public Result refundSafetMoney(@RequestAttribute Long userId){ + return userMoneyService.refundSafetMoney(userId); + } + +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppUserVipController.java b/src/main/java/com/sqx/modules/app/controller/app/AppUserVipController.java new file mode 100644 index 0000000..af64f6f --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppUserVipController.java @@ -0,0 +1,37 @@ +package com.sqx.modules.app.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.service.UserVipService; +import com.sqx.modules.sys.controller.AbstractController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Api(value = "app 用户会员信息", tags = {"app 用户会员信息"}) +@RequestMapping(value = "/app/UserVip") +public class AppUserVipController extends AbstractController { + @Autowired + private UserVipService userVipService; + + @Login + @GetMapping("/selectUserVip") + @ApiOperation("查询用户会员信息") + public Result selectUserVip(@RequestAttribute Long userId) { + return Result.success().put("data", userVipService.selectUserVipByUserId(userId)); + } + + @Login + @GetMapping("/isUserVip") + @ApiOperation("查询用户是否是会员") + public Result isUserVip(@RequestAttribute Long userId) { + return userVipService.isUserVip(userId); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/controller/app/AppVipDetailsController.java b/src/main/java/com/sqx/modules/app/controller/app/AppVipDetailsController.java new file mode 100644 index 0000000..b36db45 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/controller/app/AppVipDetailsController.java @@ -0,0 +1,46 @@ +package com.sqx.modules.app.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.VipDetails; +import com.sqx.modules.app.service.VipDetailsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiParam; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/app/VipDetails") +@AllArgsConstructor +@Api("app 会员详情信息") +public class AppVipDetailsController { + private VipDetailsService appVipDetailsService; + /** + * 查询会员的详情信息 + * + * @return + */ + @Login + @ApiParam("查询会员的详情信息") + @GetMapping("/selectVipDetails") + public Result selectVipDetails() { + return appVipDetailsService.selectVipDetails(); + } + + /** + * 添加会员的详情信息 + * + * @return + */ + @Login + @ApiParam("添加会员的详情信息") + @GetMapping("/insertVipDetails") + public Result insertVipDetails(VipDetails vipDetails) { + return appVipDetailsService.insertVipDetails(vipDetails); + + } +} + + diff --git a/src/main/java/com/sqx/modules/app/dao/AddressDao.java b/src/main/java/com/sqx/modules/app/dao/AddressDao.java new file mode 100644 index 0000000..10f368d --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/AddressDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.app.entity.Address; +import com.sqx.modules.app.entity.App; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * 地址 + * + */ +@Mapper +public interface AddressDao extends BaseMapper
{ + + int updateAddressIsDefault(@Param("userId") Long userId); + +} diff --git a/src/main/java/com/sqx/modules/app/dao/AppDao.java b/src/main/java/com/sqx/modules/app/dao/AppDao.java new file mode 100644 index 0000000..c8fe80e --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/AppDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.app.entity.App; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 用户升级 + * + */ +@Mapper +public interface AppDao extends BaseMapper { + + List selectNewApp(); + + + +} diff --git a/src/main/java/com/sqx/modules/app/dao/CarDao.java b/src/main/java/com/sqx/modules/app/dao/CarDao.java new file mode 100644 index 0000000..fa448d3 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/CarDao.java @@ -0,0 +1,17 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.app.entity.Car; +import com.sqx.modules.app.entity.Msg; +import org.apache.ibatis.annotations.Mapper; + + +@Mapper +public interface CarDao extends BaseMapper { + + IPage selectCarList(Page page, Long userId, String userName, String phone); + + +} diff --git a/src/main/java/com/sqx/modules/app/dao/CityAgencyDao.java b/src/main/java/com/sqx/modules/app/dao/CityAgencyDao.java new file mode 100644 index 0000000..af41c57 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/CityAgencyDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.app.entity.CityAgency; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + + +/** + * @author fang + * @date 2021/7/19 + */ +@Mapper +public interface CityAgencyDao extends BaseMapper { + + IPage selectCityAgencyList(Page page,@Param("userName") String userName,@Param("phone") String phone,@Param("classify") Integer classify); + +} diff --git a/src/main/java/com/sqx/modules/app/dao/MsgDao.java b/src/main/java/com/sqx/modules/app/dao/MsgDao.java new file mode 100644 index 0000000..cc0c790 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/MsgDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.app.entity.Msg; +import org.apache.ibatis.annotations.Mapper; + +/** + * 用户 + * + */ +@Mapper +public interface MsgDao extends BaseMapper { + + Msg findByPhone(String phone); + + Msg findByPhoneAndCode(String phone, String msg); + + + +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserBrowseDao.java b/src/main/java/com/sqx/modules/app/dao/UserBrowseDao.java new file mode 100644 index 0000000..da35b9f --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserBrowseDao.java @@ -0,0 +1,23 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.modules.app.entity.UserBrowse; +import com.sqx.modules.app.response.UserFollowResponse; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface UserBrowseDao extends BaseMapper { + + IPage> selectMyBrowse(IPage iPage, Long userId); + + List selectMyVisitor1(Long userId); + + List selectMyBrowse1(Long userId); + + Integer selectUserBrowseCountByUserId(Long userId,String startTime,String endTime); + +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserCertificationDao.java b/src/main/java/com/sqx/modules/app/dao/UserCertificationDao.java new file mode 100644 index 0000000..fc5d175 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserCertificationDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserCertification; +import com.sqx.modules.app.entity.UserEntity; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface UserCertificationDao extends BaseMapper { + + IPage> queryCertification(IPage iPage, @Param("status") String status, @Param("name") String name); + + IPage> queryUserCertification(IPage iPage, @Param("name") String name,@Param("phone")String phone); +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserDao.java b/src/main/java/com/sqx/modules/app/dao/UserDao.java new file mode 100644 index 0000000..02ef657 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserDao.java @@ -0,0 +1,57 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.app.entity.UserEntity; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +/** + * 用户 + */ +@Mapper +public interface UserDao extends BaseMapper { + + + IPage selectUserPage(Page page, String search, Integer sex, String platform, + String sysPhone, Integer status, Integer isAuthentication, Integer isPromotion, + Integer isAgent, String userName, Long laundryId, String isSafetyMoney, Integer isVip, String invitationCode, String inviterCode, Integer hasTicket); + + int queryInviterCount(@Param("inviterCode") String inviterCode); + + int queryUserCount(@Param("type") int type, @Param("date") String date,String platform,Integer isAuthentication); + + Double queryPayMoney(@Param("type") int type, @Param("date") String date); + + IPage> queryCourseOrder(Page iPage, @Param("type") int type, @Param("date") String date); + + int userMessage(String date, int type); + + int insertUser(UserEntity userEntity); + + IPage> takingOrdersMessage(Page> iPage, @Param("type") Long type, @Param("date") String date); + + UserEntity queryAgentUser(String province,String city,String district); + + Integer getAllBucket(); + + int updateUserInfoLaundryIdIsNull(Long laundryId); + + List selectShopUserByDistance(Long laundryId); + + List selectShopList(String userName,String phone,Long laundryId); + + IPage> selectUserOrdersList(Page> page,Long laundryId,String userName,String phone,String time,Integer flag); + + + IPage getNearbyWorker(@Param("pages") Page pages, @Param("lng") double lng, @Param("lat") double lat,String distance); + + int cancelArea(@Param("userEntity") UserEntity userEntity); + + int setUserLaundry(Long userId); +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserFollowDao.java b/src/main/java/com/sqx/modules/app/dao/UserFollowDao.java new file mode 100644 index 0000000..01d9eb3 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserFollowDao.java @@ -0,0 +1,26 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserFollow; +import com.sqx.modules.app.response.UserFollowResponse; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface UserFollowDao extends BaseMapper { + + IPage> selectMyFollow(IPage iPage, Long userId); + + IPage> selectFans(IPage iPage, Long userId); + + List selectMyFollow1(Long userId); + + List selectFans1(Long userId); + + +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserMoneyDao.java b/src/main/java/com/sqx/modules/app/dao/UserMoneyDao.java new file mode 100644 index 0000000..2d5831d --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserMoneyDao.java @@ -0,0 +1,22 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.modules.app.entity.UserMoney; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.data.domain.Page; + +import java.math.BigDecimal; +import java.util.HashMap; + +@Mapper +public interface UserMoneyDao extends BaseMapper { + + void updateMayMoney(@Param("type") Integer type, @Param("userId") Long userId, @Param("money") BigDecimal money); + + void updateSafetyMoney(@Param("type") Integer type, @Param("userId") Long userId, @Param("money") BigDecimal money); + + + BigDecimal sumHasSafetyMoney(); +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserMoneyDetailsDao.java b/src/main/java/com/sqx/modules/app/dao/UserMoneyDetailsDao.java new file mode 100644 index 0000000..0711116 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserMoneyDetailsDao.java @@ -0,0 +1,25 @@ +package com.sqx.modules.app.dao; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.app.entity.UserMoneyDetails; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.math.BigDecimal; + +@Mapper +public interface UserMoneyDetailsDao extends BaseMapper { + + Double monthIncome(@Param("date") String date,@Param("userId") Long userId); + + Double selectMyProfit(Long userId); + + Double selectLaundrySumMoney(Long userId); + + Double selectCardSumMoney(String time, Integer flag,Integer classify); + + IPage queryUserMoneyDetails(@Param("pages") Page pages, @Param("userId") Long userId, @Param("classify") Integer classify, @Param("type") Integer type, @Param("phone") String phone, @Param("ordersNo") String ordersNo, String userName); + + BigDecimal safetyMoneyStatistics(); +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserVipDao.java b/src/main/java/com/sqx/modules/app/dao/UserVipDao.java new file mode 100644 index 0000000..20e6ffe --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserVipDao.java @@ -0,0 +1,9 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.app.entity.UserVip; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface UserVipDao extends BaseMapper { +} diff --git a/src/main/java/com/sqx/modules/app/dao/UserVisitorDao.java b/src/main/java/com/sqx/modules/app/dao/UserVisitorDao.java new file mode 100644 index 0000000..2e51012 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/UserVisitorDao.java @@ -0,0 +1,17 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.modules.app.entity.UserVisitor; +import com.sqx.modules.app.response.UserFollowResponse; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface UserVisitorDao extends BaseMapper { + IPage> selectMyVisitor(IPage iPage, Long userId); + + List selectMyVisitor1(Long userId); +} diff --git a/src/main/java/com/sqx/modules/app/dao/VipDetailsDao.java b/src/main/java/com/sqx/modules/app/dao/VipDetailsDao.java new file mode 100644 index 0000000..ef194b4 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/VipDetailsDao.java @@ -0,0 +1,9 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.app.entity.VipDetails; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface VipDetailsDao extends BaseMapper { +} diff --git a/src/main/java/com/sqx/modules/app/dao/VipDiscountDao.java b/src/main/java/com/sqx/modules/app/dao/VipDiscountDao.java new file mode 100644 index 0000000..56cb27a --- /dev/null +++ b/src/main/java/com/sqx/modules/app/dao/VipDiscountDao.java @@ -0,0 +1,11 @@ +package com.sqx.modules.app.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.app.entity.VipDiscount; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface VipDiscountDao extends BaseMapper { + + +} diff --git a/src/main/java/com/sqx/modules/app/entity/Address.java b/src/main/java/com/sqx/modules/app/entity/Address.java new file mode 100644 index 0000000..9cc26c8 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/Address.java @@ -0,0 +1,74 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description address + * @author fang + * @date 2021-11-10 + */ +@Data +@TableName("address") +public class Address implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 地址id + */ + private Integer addressId; + + /** + * 姓名 + */ + private String name; + + /** + * 电话 + */ + private String phone; + + /** + * 省 + */ + private String province; + + /** + * 市 + */ + private String city; + + /** + * 区 + */ + private String district; + + /** + * 详细地址 + */ + private String detailsAddress; + + /** + * 是否是默认地址 + */ + private Integer isDefault; + + /** + * 时间 + */ + private String createTime; + + private Long userId; + + private String longitude; + + private String latitude; + + public Address() {} +} diff --git a/src/main/java/com/sqx/modules/app/entity/App.java b/src/main/java/com/sqx/modules/app/entity/App.java new file mode 100644 index 0000000..cdb7c94 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/App.java @@ -0,0 +1,35 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * 广告位 + */ +@Data +@TableName("app") +public class App implements Serializable { + @TableId + private Long id; + + private String createAt; + + private String androidWgtUrl; + + private String iosWgtUrl; + + private String wgtUrl; + + private String version; + + private String iosVersion; + + private String method; + + private String des; + +} + diff --git a/src/main/java/com/sqx/modules/app/entity/AppUserInfo.java b/src/main/java/com/sqx/modules/app/entity/AppUserInfo.java new file mode 100644 index 0000000..11691cb --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/AppUserInfo.java @@ -0,0 +1,23 @@ +package com.sqx.modules.app.entity; + +import lombok.Data; + +import java.util.List; + +@Data +public class AppUserInfo { + + + + private String openid; + private String nickname; + private int sex; + private String province; + private String city; + private String country; + private String headimgurl; + private String unionid; + private List privilege; + + +} diff --git a/src/main/java/com/sqx/modules/app/entity/Car.java b/src/main/java/com/sqx/modules/app/entity/Car.java new file mode 100644 index 0000000..0087823 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/Car.java @@ -0,0 +1,75 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description car + * @author fang + * @date 2022-07-25 + */ +@Data +public class Car implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 车辆id + */ + @TableId(type = IdType.AUTO) + private Long carId; + + /** + * 车辆型号 + */ + private String carType; + + /** + * 车辆类型 + */ + private String carClassify; + + /** + * 车辆号码 + */ + private String carNo; + + /** + * 车辆颜色 + */ + private String carColor; + + /** + * 车主名称 + */ + private String carName; + + /** + * 车主电话 + */ + private String carPhone; + + /** + * 用户id + */ + private Long userId; + + /** + * 创建时间 + */ + private String createTime; + + private String carLogo; + + @TableField(exist = false) + private String userName; + + @TableField(exist = false) + private String phone; + + public Car() {} +} diff --git a/src/main/java/com/sqx/modules/app/entity/CityAgency.java b/src/main/java/com/sqx/modules/app/entity/CityAgency.java new file mode 100644 index 0000000..3b2e640 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/CityAgency.java @@ -0,0 +1,58 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description city_agency + * @author fang + * @date 2021-07-19 + */ +@Data +public class CityAgency implements Serializable { + + private static final long serialVersionUID = 1L; + + + /** + * 代理id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 用户id + */ + private Long userId; + + /** + * 意向代理城市 + */ + private String city; + + + /** + * 姓名 + */ + private String userName; + + /** + * 电话 + */ + private String phone; + + /** + * 1 职位招聘 2招商加盟 + */ + private Integer classify; + + /** + * 创建时间 + */ + private String createTime; + + public CityAgency() {} +} diff --git a/src/main/java/com/sqx/modules/app/entity/Msg.java b/src/main/java/com/sqx/modules/app/entity/Msg.java new file mode 100644 index 0000000..58a67ad --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/Msg.java @@ -0,0 +1,27 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author fang + * @date 2020/7/10 + */ +@Data +@TableName("msg") +public class Msg implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId + private Long id; + + private String code; + + private String phone; + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/app/entity/UserBrowse.java b/src/main/java/com/sqx/modules/app/entity/UserBrowse.java new file mode 100644 index 0000000..2326a02 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserBrowse.java @@ -0,0 +1,54 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description user_browse + * @author liyuan + * @date 2021-08-12 + */ +@Data +@ApiModel("user_browse") +public class UserBrowse implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 浏览访客id + */ + @ApiModelProperty("浏览访客id") + private Long id; + + /** + * 用户id + */ + @ApiModelProperty("用户id") + private Long userId; + + /** + * 被浏览id + */ + @ApiModelProperty("被浏览id") + private Long byBrowseId; + + + /** + * 接单id + */ + @ApiModelProperty("接单id") + private Long takingId; + /** + * 更新时间 + */ + @ApiModelProperty("更新时间") + private String updateTime; + + public UserBrowse() {} +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserCertification.java b/src/main/java/com/sqx/modules/app/entity/UserCertification.java new file mode 100644 index 0000000..2bf270b --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserCertification.java @@ -0,0 +1,91 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author liyuan + * @description user_certification + * @date 2021-08-13 + */ +@Data +@ApiModel("user_certification") +public class UserCertification implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 用户实名认证id + */ + @ApiModelProperty("用户实名认证id") + private Long id; + + /** + * 真实姓名 + */ + @ApiModelProperty("真实姓名") + private String name; + + /** + * 身份证号码 + */ + @ApiModelProperty("身份证号码") + private String idNumber; + + /** + * 用户id + */ + @ApiModelProperty("用户id") + private Long userId; + + @TableField(exist = false) + private UserEntity userEntity; + + /** + * 创建时间 + */ + @ApiModelProperty("创建时间") + private String createTime; + /** + * 正面 + */ + private String front; + /** + * 反面 + */ + private String back; + + /** + * 状态 + */ + private Integer status; + + /** + * 说明 + */ + private String remek; + + /** + * 修改时间 + */ + private String updateTime; + + + private String phone; + + private String birth; + + private String sex; + + + + public UserCertification() { + } +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserDetails.java b/src/main/java/com/sqx/modules/app/entity/UserDetails.java new file mode 100644 index 0000000..77ee340 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserDetails.java @@ -0,0 +1,27 @@ +package com.sqx.modules.app.entity; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class UserDetails { + /** + * 本月订单数量 + */ + private int monthlyOrderNum; + /** + * 本月充值金额 + */ + private BigDecimal monthlyRechargeMoney; + /** + *本月提现数量 + */ + private int monthWithdrawalNum; + /** + * 本月提现金额 + */ + private BigDecimal monthlyWithdrawalMoney; + + +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserEntity.java b/src/main/java/com/sqx/modules/app/entity/UserEntity.java new file mode 100644 index 0000000..0f97a8e --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserEntity.java @@ -0,0 +1,287 @@ +package com.sqx.modules.app.entity; + +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + + +/** + * 用户 + */ +@Data +@ApiModel("用户") +@TableName("tb_user") +public class UserEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 用户ID + */ + @ApiModelProperty("用户id") + @TableId(type = IdType.AUTO, value = "user_id") + @Excel(name = "编号") + private Long userId; + /** + * 用户名 + */ + @ApiModelProperty("用户名") + @TableField("user_name") + @Excel(name = "昵称") + private String userName; + + /** + * 手机号 + */ + @Excel(name = "手机号") + @ApiModelProperty("手机号") + private String phone; + + /** + * 头像 + */ + @Excel(name = "头像") + @ApiModelProperty("头像") + private String avatar; + + /** + * 性别 1男 2女 + */ + @Excel(name = "性别", replace = {"男_1", "女_2"," _null"}) + @ApiModelProperty("性别 1男 2女") + private Integer sex; + /** + * 年龄 + */ + @Excel(name = "年龄") + @ApiModelProperty("年龄") + private Integer age; + + /** + * 微信小程序openid + */ + @ApiModelProperty("微信小程序openid") + @TableField("open_id") + private String openId; + + /** + * 微信app openid + */ + @ApiModelProperty("微信公众号openid") + @TableField("wx_open_id") + private String wxOpenId; + + /** + * 密码 + */ + @Excel(name = "密码") + private String password; + + /** + * 创建时间 + */ + @TableField("create_time") + private String createTime; + + /** + * 更新时间 + */ + @TableField("update_time") + private String updateTime; + + /** + * 苹果id + */ + @TableField("apple_id") + private String appleId; + + /** + * 手机类型 1安卓 2ios + */ + @Excel(name = "手机类型", replace = {"安卓_1", "ios_2"} ,isColumnHidden=true) + @TableField("sys_phone") + private Integer sysPhone; + + /** + * 状态 1正常 2禁用 + */ + @Excel(name = "状态", replace = {"正常_1", "禁用_2"}) + private Integer status; + + /** + * 来源 app 小程序 公众号 + */ + @Excel(name = "来源") + private String platform; + + /** + * 积分 + */ + private Integer jifen; + + /** + * 邀请码 + */ + @Excel(name = "邀请码") + @TableField("invitation_code") + private String invitationCode; + + /** + * 邀请人邀请码 + */ + @Excel(name = "邀请人邀请码") + @TableField("inviter_code") + private String inviterCode; + private String clientid; + @Excel(name = "支付宝账号") + private String zhiFuBao; + @Excel(name = "支付宝名称") + private String zhiFuBaoName; + + /** + * 是否认证 状态值 1用户认证 2企业认证 3用户企业都认证 + */ + private Integer isAuthentication; + + /** + * 商家小程序openId + */ + private String shopOpenId; + + @TableField(exist = false) + private Integer type; + + /** + * 介绍 + */ + private String details; + + /** + * 轮播图 + */ + private String detailsImg; + + /** + * 资质 + */ + private String certificationImg; + @Excel(name = "收款二维码") + private String wxImg; + private String address; + + private String shopPhone; + + private String shopImg; + + private String shopName; + + private String addressImg; + + private String startTime; + + private String endTime; + + private String shopType; + + private String longitude; + + private String latitude; + + /** + * 是否接受消息推送 1是 2否 + */ + private Integer isSendMsg; + + @Excel(name = "师傅佣金比例") + private BigDecimal rate; + + /** + * 直属佣金比例 + */ + @Excel(name = "推广员佣金比例") + private BigDecimal zhiRate; + + /** + * 非直属佣金比例 + */ + @Excel(name = "代理商佣金比例") + private BigDecimal feiRate; + + /** + * 是否缴纳保证金 1缴纳 其他未缴纳 + */ + private Integer isSafetyMoney; + + /** + * 是否是推广员 1是 + */ + private Integer isPromotion; + + /** + * 是否是代理商 + */ + private Integer isAgent; + + /** + * 省 + */ + private String province; + + /** + * 市 + */ + private String city; + + /** + * 区 + */ + private String district; + /** + * 压桶数量 + */ + @Excel(name = "压桶数量") + private Integer bucket; + + private Integer isNewPeople; + + /** + * 站点id + */ + private Long laundryId; + + @TableField(exist = false) + @Excel(name = "站点名称") + private String laundryName; + + @TableField(exist = false) + private Integer ordersCount; + + @TableField(exist = false) + private String vipEndTime; + + /** + * 是否是会员 2是 + */ + @TableField(exist = false) + private Integer isVip; + @Excel(name = "水票数量") + @TableField(exist = false) + private Integer ticketsCount; + /** + * 1表示是从师傅端注册 + */ + @TableField(exist = false) + private Integer courseType; + /** + * 送水量 + */ + @TableField(exist = false) + private Integer bucketCount; +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserFollow.java b/src/main/java/com/sqx/modules/app/entity/UserFollow.java new file mode 100644 index 0000000..3bcff60 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserFollow.java @@ -0,0 +1,48 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description user_follow + * @author liyuan + * @date 2021-08-12 + */ +@Data +@ApiModel("user_follow") +public class UserFollow implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * id + */ + @ApiModelProperty("id") + private Long followId; + + /** + * 用户id + */ + @ApiModelProperty("用户id") + private Long userId; + + /** + * 关注用户id + */ + @ApiModelProperty("关注用户id") + private Long followUserId; + + /** + * 创建时间 + */ + @ApiModelProperty("创建时间") + private String createTime; + + public UserFollow() {} +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserMoney.java b/src/main/java/com/sqx/modules/app/entity/UserMoney.java new file mode 100644 index 0000000..5fbbb28 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserMoney.java @@ -0,0 +1,50 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("user_money") +@ApiModel("用户钱包") +public class UserMoney implements Serializable { + /** + * 主键id + */ + @ApiModelProperty("主键id") + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 钱包金额 + */ + @ApiModelProperty("钱包金额") + private BigDecimal money; + + @ApiModelProperty("保证金") + private BigDecimal safetyMoney; + + @ApiModelProperty("保证金支付方式 1微信 2支付宝") + private Integer safetyMoneyWay; + @ApiModelProperty("佣金收益") + private BigDecimal rateMoney; + /** + * 用户id + */ + @ApiModelProperty("用户id") + @TableField("user_id") + private Long userId; + + private String orderNo; +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserMoneyDetails.java b/src/main/java/com/sqx/modules/app/entity/UserMoneyDetails.java new file mode 100644 index 0000000..a98d0c1 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserMoneyDetails.java @@ -0,0 +1,96 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("user_money_details") +@ApiModel("钱包详情") +public class UserMoneyDetails implements Serializable { + /** + * 钱包详情id + */ + @ApiModelProperty("钱包详情id") + @TableId(type = IdType.AUTO) + private Long id; + /** + * 用户id + */ + @TableField("user_id") + @ApiModelProperty("用户id") + private Long userId; + /** + * 对应用户id + */ + @TableField("by_user_id") + @ApiModelProperty("对应用户id") + private Long byUserId; + /** + * 标题 + */ + @ApiModelProperty("标题") + private String title; + /** + * 1注册 2购买 4提现 + */ + @ApiModelProperty("1注册 2购买 3提现") + private Integer classify; + /** + * 类型 + */ + @ApiModelProperty("类型1充值 2.提现") + private Integer type; + /** + * 状态 1待支付 2已到账 3取消 + */ + @ApiModelProperty("状态 1待支付 2已到账 3取消") + private Integer state; + /** + * 金额 + */ + @ApiModelProperty("金额") + private BigDecimal money; + /** + * 内容 + */ + @ApiModelProperty("内容") + private String content; + /** + * 关联信息或id + */ + @ApiModelProperty("关联信息或id") + private String relationId; + /** + * 关联信息或id + */ + @ApiModelProperty("站点id") + private Long laundryId; + /** + * 创建时间 + */ + @TableField("create_time") + @ApiModelProperty("创建时间") + private String createTime; + + private String ordersNo; + /** + * 支付类型 1水贝 2微信 3支付宝 + */ + + private Integer payType; + @TableField(exist = false) + private UserEntity userEntity; + +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserVip.java b/src/main/java/com/sqx/modules/app/entity/UserVip.java new file mode 100644 index 0000000..0c0421c --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserVip.java @@ -0,0 +1,42 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; +@Data +public class UserVip implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 用户会员ID + */ + @TableId + private Long vipId; + /** + * 会员类型 + */ + private Integer vipNameType; + @TableField(exist = false) + private VipDetails vipDetails; + + /** + * 用户ID + */ + private Long userId; + + /** + * 购买时间 + */ + private String createTime; + /** + * 到期时间 + */ + private String endTime; + + /** + *是否是会员 + */ + private Integer isVip; + public UserVip() {} +} diff --git a/src/main/java/com/sqx/modules/app/entity/UserVisitor.java b/src/main/java/com/sqx/modules/app/entity/UserVisitor.java new file mode 100644 index 0000000..132cba6 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/UserVisitor.java @@ -0,0 +1,41 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description user_visitor + * @author liyuan + * @date 2021-08-23 + */ +@Data +public class UserVisitor implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 访客id + */ + private Long id; + + /** + * 用户id + */ + private Long userId; + + /** + * 访问用户id + */ + private Long byUserId; + + /** + * 更新时间 + */ + private String updateTime; + + public UserVisitor() {} +} diff --git a/src/main/java/com/sqx/modules/app/entity/VipDetails.java b/src/main/java/com/sqx/modules/app/entity/VipDetails.java new file mode 100644 index 0000000..b26d1da --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/VipDetails.java @@ -0,0 +1,38 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import weixin.popular.bean.card.Discount; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("vip_details") +@ApiModel("会员详情") +public class VipDetails implements Serializable { + + @TableId(type = IdType.AUTO) + private Long id; + + @ApiModelProperty("会员类型") + @TableField("vip_name_type") + private Integer vipNameType; + + @ApiModelProperty("会员价格") + private BigDecimal money; + + @TableField + private String vipName; + + private BigDecimal award; +} diff --git a/src/main/java/com/sqx/modules/app/entity/VipDiscount.java b/src/main/java/com/sqx/modules/app/entity/VipDiscount.java new file mode 100644 index 0000000..58587c8 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/entity/VipDiscount.java @@ -0,0 +1,32 @@ +package com.sqx.modules.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +@ApiModel("vip_discount") +public class VipDiscount implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * id + */ + @ApiModelProperty("id") + private Integer id; + + /** + * 优惠金币 + */ + @ApiModelProperty("优惠金币") + private BigDecimal discount; + + public VipDiscount() {} +} diff --git a/src/main/java/com/sqx/modules/app/form/LoginForm.java b/src/main/java/com/sqx/modules/app/form/LoginForm.java new file mode 100644 index 0000000..1fe61c3 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/form/LoginForm.java @@ -0,0 +1,24 @@ +package com.sqx.modules.app.form; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * 登录表单 + * + */ +@Data +@ApiModel(value = "登录表单") +public class LoginForm { + @ApiModelProperty(value = "手机号") + @NotBlank(message="手机号不能为空") + private String mobile; + + @ApiModelProperty(value = "密码") + @NotBlank(message="密码不能为空") + private String password; + +} diff --git a/src/main/java/com/sqx/modules/app/form/RegisterForm.java b/src/main/java/com/sqx/modules/app/form/RegisterForm.java new file mode 100644 index 0000000..5d8d11e --- /dev/null +++ b/src/main/java/com/sqx/modules/app/form/RegisterForm.java @@ -0,0 +1,24 @@ +package com.sqx.modules.app.form; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * 注册表单 + * + */ +@Data +@ApiModel(value = "注册表单") +public class RegisterForm { + @ApiModelProperty(value = "手机号") + @NotBlank(message="手机号不能为空") + private String mobile; + + @ApiModelProperty(value = "密码") + @NotBlank(message="密码不能为空") + private String password; + +} diff --git a/src/main/java/com/sqx/modules/app/interceptor/AuthorizationInterceptor.java b/src/main/java/com/sqx/modules/app/interceptor/AuthorizationInterceptor.java new file mode 100644 index 0000000..b694392 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/interceptor/AuthorizationInterceptor.java @@ -0,0 +1,70 @@ +package com.sqx.modules.app.interceptor; + + +import com.sqx.common.exception.SqxException; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.app.utils.JwtUtils; +import io.jsonwebtoken.Claims; +import com.sqx.modules.app.annotation.Login; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * 权限(Token)验证 + * + */ +@Component +public class AuthorizationInterceptor extends HandlerInterceptorAdapter { + @Autowired + private JwtUtils jwtUtils; + @Autowired + private UserService userService; + public static final String USER_KEY = "userId"; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + Login annotation; + if(handler instanceof HandlerMethod) { + annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class); + }else{ + return true; + } + + if(annotation == null){ + return true; + } + + //获取用户凭证 + String token = request.getHeader(jwtUtils.getHeader()); + if(StringUtils.isBlank(token)){ + token = request.getParameter(jwtUtils.getHeader()); + } + + //凭证为空 + if(StringUtils.isBlank(token)){ + throw new SqxException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value()); + } + + Claims claims = jwtUtils.getClaimByToken(token); + if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){ + throw new SqxException(jwtUtils.getHeader() + "失效,请重新登录", HttpStatus.UNAUTHORIZED.value()); + } + //账号被禁用 + UserEntity userEntity = userService.getById(claims.getSubject()); + if (userEntity != null && userEntity.getStatus() != 1) { + throw new SqxException("账号已被禁用", HttpStatus.UNAUTHORIZED.value()); + } + //设置userId到request里,后续根据userId,获取用户信息 + request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject())); + + return true; + } +} diff --git a/src/main/java/com/sqx/modules/app/resolver/LoginUserHandlerMethodArgumentResolver.java b/src/main/java/com/sqx/modules/app/resolver/LoginUserHandlerMethodArgumentResolver.java new file mode 100644 index 0000000..3ae6a96 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/resolver/LoginUserHandlerMethodArgumentResolver.java @@ -0,0 +1,44 @@ +package com.sqx.modules.app.resolver; + +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.interceptor.AuthorizationInterceptor; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.app.annotation.LoginUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.MethodParameter; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +/** + * 有@LoginUser注解的方法参数,注入当前登录用户 + * + */ +@Component +public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { + @Autowired + private UserService userService; + + @Override + public boolean supportsParameter(MethodParameter parameter) { + return parameter.getParameterType().isAssignableFrom(UserEntity.class) && parameter.hasParameterAnnotation(LoginUser.class); + } + + @Override + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, + NativeWebRequest request, WebDataBinderFactory factory) throws Exception { + //获取用户ID + Object object = request.getAttribute(AuthorizationInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST); + if(object == null){ + return null; + } + + //获取用户信息 + UserEntity user = userService.getById((Long)object); + + return user; + } +} diff --git a/src/main/java/com/sqx/modules/app/response/CourseOrderResponse.java b/src/main/java/com/sqx/modules/app/response/CourseOrderResponse.java new file mode 100644 index 0000000..aec06ea --- /dev/null +++ b/src/main/java/com/sqx/modules/app/response/CourseOrderResponse.java @@ -0,0 +1,25 @@ +package com.sqx.modules.app.response; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CourseOrderResponse implements Serializable { + /** + * 课程名称 + */ + private String coursename; + /** + * 售卖笔数 + */ + private int coursenum; + /** + * 售卖金额 + */ + private Double coursemoney; +} diff --git a/src/main/java/com/sqx/modules/app/response/HomeMessageResponse.java b/src/main/java/com/sqx/modules/app/response/HomeMessageResponse.java new file mode 100644 index 0000000..fa1d58c --- /dev/null +++ b/src/main/java/com/sqx/modules/app/response/HomeMessageResponse.java @@ -0,0 +1,52 @@ +package com.sqx.modules.app.response; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * 首页信息返回实体 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +public class HomeMessageResponse implements Serializable { + /** + * 总用户数 + */ + private int totalUsers; + /** + *今日新增 + */ + private int newToday; + /** + *本月新增 + */ + private int newMonth; + /** + * 本年新增 + */ + private int newYear; + /** + * 总收入 + */ + private Double totalRevenue; + /** + * 今日收入 + */ + private Double todayRevenue; + /** + * 本月收入 + */ + private Double monthRevenue; + /** + * 本年收入 + */ + private Double yearRevenue; + +} diff --git a/src/main/java/com/sqx/modules/app/response/TakingOrderResponse.java b/src/main/java/com/sqx/modules/app/response/TakingOrderResponse.java new file mode 100644 index 0000000..c925ed4 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/response/TakingOrderResponse.java @@ -0,0 +1,20 @@ +package com.sqx.modules.app.response; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class TakingOrderResponse implements Serializable { + + private int orderNumber; + private String gameName; + private double payMoney; + + + + + + + +} diff --git a/src/main/java/com/sqx/modules/app/response/UserFollowResponse.java b/src/main/java/com/sqx/modules/app/response/UserFollowResponse.java new file mode 100644 index 0000000..c66f31e --- /dev/null +++ b/src/main/java/com/sqx/modules/app/response/UserFollowResponse.java @@ -0,0 +1,55 @@ +package com.sqx.modules.app.response; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.sqx.modules.taking.entity.OrderTaking; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +@Data +public class UserFollowResponse implements Serializable { + + /** + * id + */ + private Long id; + + /** + * 用户ID + */ + @ApiModelProperty("用户id") + private Long userId; + /** + * 用户名 + */ + @ApiModelProperty("用户名") + private String userName; + /** + * 头像 + */ + @ApiModelProperty("头像") + private String avatar; + /** + * 关注状态 + */ + private int status; + /** + * 时间 + */ + private String updateTime; + + private Integer sex; + + private Integer age; + + /** + * 接单id + */ + @TableField(exist = false) + private Long takingId; + @TableField(exist = false) + private OrderTaking orderTaking; +} diff --git a/src/main/java/com/sqx/modules/app/response/UserMessageResponse.java b/src/main/java/com/sqx/modules/app/response/UserMessageResponse.java new file mode 100644 index 0000000..f0e0962 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/response/UserMessageResponse.java @@ -0,0 +1,25 @@ +package com.sqx.modules.app.response; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class UserMessageResponse implements Serializable { + /** + * 总人数 + */ + private int totalNumber; + /** + * 普通用户人数 + */ + private int userNumber; + /** + * 会员人数 + */ + private int vipUserNumber; +} diff --git a/src/main/java/com/sqx/modules/app/service/AddressService.java b/src/main/java/com/sqx/modules/app/service/AddressService.java new file mode 100644 index 0000000..79858d5 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/AddressService.java @@ -0,0 +1,19 @@ +package com.sqx.modules.app.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.app.entity.Address; +import com.sqx.modules.app.entity.App; + +import java.util.List; + +/** + * 地址 + * + */ +public interface AddressService extends IService
{ + + int updateAddressIsDefault(Long userId); + + +} diff --git a/src/main/java/com/sqx/modules/app/service/AppService.java b/src/main/java/com/sqx/modules/app/service/AppService.java new file mode 100644 index 0000000..d22a259 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/AppService.java @@ -0,0 +1,25 @@ +package com.sqx.modules.app.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.app.entity.App; + +import java.util.List; + +/** + * 升级 + * + */ +public interface AppService extends IService { + + App selectAppById(Long id); + + int insertApp(App app); + + int updateAppById(App app); + + int deleteAppById(Long id); + + List selectNewApp(); + +} diff --git a/src/main/java/com/sqx/modules/app/service/CarService.java b/src/main/java/com/sqx/modules/app/service/CarService.java new file mode 100644 index 0000000..6d0a813 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/CarService.java @@ -0,0 +1,14 @@ +package com.sqx.modules.app.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.Car; +import com.sqx.modules.app.entity.Msg; + + +public interface CarService extends IService { + + Result selectCarList(Integer page, Integer limit, Long userId, String userName, String phone); + +} diff --git a/src/main/java/com/sqx/modules/app/service/CityAgencyService.java b/src/main/java/com/sqx/modules/app/service/CityAgencyService.java new file mode 100644 index 0000000..bb32491 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/CityAgencyService.java @@ -0,0 +1,12 @@ +package com.sqx.modules.app.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.CityAgency; + +public interface CityAgencyService extends IService { + + Result selectCityAgencyList(Integer page,Integer limit,String userName,String phone,Integer classify); + +} diff --git a/src/main/java/com/sqx/modules/app/service/IAppleService.java b/src/main/java/com/sqx/modules/app/service/IAppleService.java new file mode 100644 index 0000000..7879163 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/IAppleService.java @@ -0,0 +1,10 @@ +package com.sqx.modules.app.service; + + +import com.sqx.common.utils.Result; + +public interface IAppleService { + + Result getAppleUserInfo(String identityToken) throws Exception; + +} diff --git a/src/main/java/com/sqx/modules/app/service/MsgService.java b/src/main/java/com/sqx/modules/app/service/MsgService.java new file mode 100644 index 0000000..b422b2c --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/MsgService.java @@ -0,0 +1,17 @@ +package com.sqx.modules.app.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.app.entity.Msg; + +/** + * 验证码 + * + */ +public interface MsgService extends IService { + + Msg findByPhone(String phone); + + Msg findByPhoneAndCode(String phone, String msg); + +} diff --git a/src/main/java/com/sqx/modules/app/service/UserBrowseService.java b/src/main/java/com/sqx/modules/app/service/UserBrowseService.java new file mode 100644 index 0000000..146804c --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/UserBrowseService.java @@ -0,0 +1,32 @@ +package com.sqx.modules.app.service; + +import com.sqx.common.utils.Result; +import org.springframework.web.bind.annotation.RequestAttribute; + +public interface UserBrowseService { + Result selectMyVisitor(Long userId, Long page, Long limit); + + Result selectMyBrowse(Long userId, Long page, Long limit); + + Result selectAmount(Long userId); + + Result addAmount(Long userId, Long byBrowseId, Long takingId); + + Result addVisitor(Long userId, Long byBrowseId); + + /** + * 删除我的访客 + * + * @param id + * @return + */ + Result deleteMyVisitor(Long id); + + /** + * 删除浏览足迹 + * + * @param id + * @return + */ + Result deleteMyBrowse(Long id); +} diff --git a/src/main/java/com/sqx/modules/app/service/UserCertificationService.java b/src/main/java/com/sqx/modules/app/service/UserCertificationService.java new file mode 100644 index 0000000..51a2aae --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/UserCertificationService.java @@ -0,0 +1,28 @@ +package com.sqx.modules.app.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserCertification; +import io.swagger.annotations.ApiParam; +import org.springframework.web.bind.annotation.RequestAttribute; + +import java.util.HashMap; + +public interface UserCertificationService extends IService { + Result insert(UserCertification userCertification); + + Result isInsert(Long userId); + + Result queryCertification(Long page, Long limit, String status, String name); + + Result queryUserCertification(IPage iPage, String name,String phone); + + Result auditorUserCertification(Integer status, Long id, String remek); + + Result queryInsert(Long userId); + + Result updateCertification(UserCertification userCertification); + + HashMap safetyMoneyStatistics(); +} diff --git a/src/main/java/com/sqx/modules/app/service/UserFollowService.java b/src/main/java/com/sqx/modules/app/service/UserFollowService.java new file mode 100644 index 0000000..6c388e2 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/UserFollowService.java @@ -0,0 +1,32 @@ +package com.sqx.modules.app.service; +import com.sqx.common.utils.Result; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author liyuan + * @description user_follow + * @date 2021-08-12 + */ +public interface UserFollowService { + + /** + * 关注 / 取消关注 + */ + Result insert(Long userId, Long followUserId); + + /** + * 查看我的关注 + */ + Result selectMyFollow(Long userId,Long page,Long limit); + + /** + * 查看我的粉丝 + */ + Result selectFans(Long userId,Long page,Long limit); + + Result selectFollowUser( Long userId, Long followUserId); + /** + * 查询用户的最好 + */ +} diff --git a/src/main/java/com/sqx/modules/app/service/UserMoneyDetailsService.java b/src/main/java/com/sqx/modules/app/service/UserMoneyDetailsService.java new file mode 100644 index 0000000..3c97bff --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/UserMoneyDetailsService.java @@ -0,0 +1,19 @@ +package com.sqx.modules.app.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserMoneyDetails; + +import java.math.BigDecimal; + +public interface UserMoneyDetailsService extends IService { + + Result queryUserMoneyDetails(Integer page, Integer limit, Long userId, Integer classify, Integer type, String phone, String ordersNo, String userName); + + Double monthIncome(String date, Long userId); + + Double selectLaundrySumMoney(Long userId); + + + BigDecimal safetyMoneyStatistics(); +} diff --git a/src/main/java/com/sqx/modules/app/service/UserMoneyService.java b/src/main/java/com/sqx/modules/app/service/UserMoneyService.java new file mode 100644 index 0000000..81626c1 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/UserMoneyService.java @@ -0,0 +1,38 @@ +package com.sqx.modules.app.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import org.springframework.web.bind.annotation.RequestAttribute; + +import java.math.BigDecimal; +import java.util.HashMap; + +public interface UserMoneyService extends IService { + + UserMoney selectUserMoneyByUserId(Long userId); + + void updateSafetyMoneyWay(Long id, Integer safetyMoneyWay, String orderNo); + + void updateMoney(int i, Long userId, BigDecimal money); + + void updateSafetyMoney(int i, Long userId, BigDecimal money); + + Double selectMyProfit(Long userId); + + Result payTakingOrder(Long userId, Long orderId); + + PageUtils balanceDetailed(@RequestAttribute Long userId, Page ipage); + + Result profitDetailed(@RequestAttribute Long userId, IPage ipage); + + Result refundSafetMoney(Long userId); + + Result paySafetyMoney(Long userId); + + BigDecimal sumHasSafetyMoney(); +} diff --git a/src/main/java/com/sqx/modules/app/service/UserService.java b/src/main/java/com/sqx/modules/app/service/UserService.java new file mode 100644 index 0000000..ad54fcb --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/UserService.java @@ -0,0 +1,256 @@ +package com.sqx.modules.app.service; + + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 用户 + * + * @author fang + * @date 2021/2/27 + */ +public interface UserService extends IService { + + Result selectShopList(String userName,String phone,Long laundryId); + + /** + * 根据手机号查询用户 + * + * @param phone 手机号 + * @return + */ + UserEntity queryByPhone(String phone); + + /** + * 根据小程序微信openId查询用户 + * + * @param openId 微信小程序openId + * @return + */ + UserEntity queryByOpenId(String openId); + + UserEntity queryByShopOpenId(String shopOpenId); + + /** + * 根据微信APP openId查询用户 + * + * @param openId 微信APP openId + * @return + */ + UserEntity queryByWxOpenId(String openId); + + /** + * 根据userId查询用户 + * + * @param userId userId + * @return + */ + UserEntity queryByUserId(Long userId); + + UserEntity queryAgentUser(String province,String city,String district); + + UserEntity queryByInvitationCode(String invitationCode); + + List selectShopUserByDistance(Long laundryId); + + /** + * 根据用户appleId查询用户 + * + * @param appleId + * @return + */ + UserEntity queryByAppleId(String appleId); + + + Result wxLogin(String code,Integer type); + + /** + * 注册或更新用户信息 + * + * @param userInfo1 用户信息 + * @return 用户信息 + */ + Result wxRegister(UserEntity userInfo1); + + /** + * 注册或更新用户信息 + * + * @param appleId 苹果账号id + * @return 用户信息 + */ + Result iosRegister(String appleId); + + /** + * 发送验证码 + * + * @param phone 手机号 + * @param state 验证码类型 + * @return + */ + Result sendMsg(String phone, String state); + + Result sendMsg(String phone, String state,Integer code); + + /** + * 绑定手机号 + * + * @param phone 手机号 + * @param code 验证码 + * @return + */ + Result wxBindMobile(String phone, String code, String wxOpenId, String token, String platform, Integer sysPhone); + + /** + * @param phone + * @param code + * @param appleId + * @param platform + * @param sysPhone + * @return + */ + Result iosBindMobile(String phone, String code, String appleId, String platform, Integer sysPhone); + + /** + * 换绑手机号 + * + * @param phone 手机号 + * @param msg 验证码 + * @param userId 用户id + * @return + */ + Result updatePhone(String phone, String msg, Long userId); + + /** + * 登录token + * + * @param user 用户信息 + * @return + */ + Result getResult(UserEntity user); + + /** + * app注册或h5注册 + * + * @param pwd 密码 + * @param phone 手机号 + * @param msg 验证按 + * @param platform 来源 app h5 + * @param courseType + * @return + */ + Result registerCode(String phone, String msg, String platform, Integer sysPhone, String openId, String inviterCode, Integer courseType); + + + Result loginByOpenId(String openId); + + + Result wxAppLogin(String wxOpenId, String token); + + + + void sendNewPeopleCoupon(Long userId); + + /** + * app或h5登录 + * + * @param phone 手机号 + * @param pwd 密码 + * @return + */ + Result login(String phone, String pwd); + + + /** + * 根据 code 获取openId + * + * @param code + * @param userId + * @return + */ + Result getOpenId(String code, Long userId); + + + /** + * 根据用户id查询用户 + * + * @param userId 用户id + * @return + */ + UserEntity selectUserById(Long userId); + + void pushToSingle(String title, String content, String clientId); + + PageUtils selectUserPage(Integer page, Integer limit, String search, Integer sex, String platform, String sysPhone, + Integer status, Integer isAuthentication, Integer isPromotion, Integer isAgent, String userName, Long laundryId, String isSafetyMoney, Integer isVip, String invitationCode, String inviterCode, Integer hasTicket); + + int queryInviterCount(String inviterCode); + + int queryUserCount(int type,String date,String platform,Integer isAuthentication); + + Double queryPayMoney(int type); + + IPage> queryCourseOrder(Page> iPage, int type, String date); + + int userMessage(String date, int type); + + Result loginApp(String phone, String password); + + Result registApp(String userName, String phone, String password, String msg, String platform, String inviterCode, Integer courseType); + + Result takingOrdersMessage(Page> iPage, Long type, String date); + + Result forgetPwd(String pwd, String phone, String msg); + + /** + * + * @param updateUserId 修改人id + * @param userId 被修改的用户id + * @param num 修改数量 + * @return + */ + Result updateUserBucket(Integer userType, Long updateUserId, Long userId, Integer num, Long ordersId); + + Integer getAllBucket(); + + int updateUserInfoLaundryIdIsNull(Long laundryId); + + Result selectUserOrdersList(Integer page,Integer limit,Long laundryId,String userName,String phone,String time,Integer flag); + + + IPage getNearbyWorker(Integer page, Integer limit, Double lng, Double lat); + + Result giveUserVip(Long userId, Integer day); + + Result cancelUserVip(Long userId); + + Result bucketCallback(Long userId, Integer num, BigDecimal payMoney,Integer classify); + + Result buyBucket(Long userId, Integer num); + + Result backBucket(Long userId, Integer num); + + + int cancelArea(UserEntity userEntity); + + int setUserLaundry(Long userId); + + + Result userExcelIn(MultipartFile file) throws IOException; + + List userEntityExcelOut(String search,String phone, Integer sex, String platform, String sysPhone, Integer status, Integer isAuthentication, Integer isPromotion, Integer isAgent, String userName, Long laundryId, String isSafetyMoney, Integer isVip, String invitationCode, String inviterCode, Integer hasTicket); + + List> getUserBucket(Integer flag, String date); + +} diff --git a/src/main/java/com/sqx/modules/app/service/UserVipService.java b/src/main/java/com/sqx/modules/app/service/UserVipService.java new file mode 100644 index 0000000..f50765e --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/UserVipService.java @@ -0,0 +1,12 @@ +package com.sqx.modules.app.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserVip; +import org.springframework.web.bind.annotation.RequestAttribute; + +public interface UserVipService extends IService { + + UserVip selectUserVipByUserId(Long UserId); + Result isUserVip(@RequestAttribute Long userId); +} diff --git a/src/main/java/com/sqx/modules/app/service/VipDetailsService.java b/src/main/java/com/sqx/modules/app/service/VipDetailsService.java new file mode 100644 index 0000000..3c436f3 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/VipDetailsService.java @@ -0,0 +1,23 @@ +package com.sqx.modules.app.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.VipDetails; + +public interface VipDetailsService extends IService { + /** + * 查询会员的详情信息 + * + * @return + */ + Result selectVipDetails(); + + /** + * 添加会员的详情信息 + * + * @return + */ + Result insertVipDetails(VipDetails vipDetails); + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/AddressServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/AddressServiceImpl.java new file mode 100644 index 0000000..b39f1a3 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/AddressServiceImpl.java @@ -0,0 +1,27 @@ +package com.sqx.modules.app.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.app.dao.AddressDao; +import com.sqx.modules.app.dao.AppDao; +import com.sqx.modules.app.entity.Address; +import com.sqx.modules.app.entity.App; +import com.sqx.modules.app.service.AddressService; +import com.sqx.modules.app.service.AppService; +import org.apache.ibatis.annotations.Param; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + + +@Service("AddressService") +public class AddressServiceImpl extends ServiceImpl implements AddressService { + + @Override + public int updateAddressIsDefault(Long userId){ + return baseMapper.updateAddressIsDefault(userId); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/AppServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/AppServiceImpl.java new file mode 100644 index 0000000..8a56382 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/AppServiceImpl.java @@ -0,0 +1,45 @@ +package com.sqx.modules.app.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.app.dao.AppDao; +import com.sqx.modules.app.entity.App; +import com.sqx.modules.app.service.AppService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + + +@Service("AppService") +public class AppServiceImpl extends ServiceImpl implements AppService { + + @Autowired + private AppDao appDao; + + + @Override + public App selectAppById(Long id) { + return appDao.selectById(id); + } + + @Override + public int insertApp(App app) { + return appDao.insert(app); + } + + @Override + public int updateAppById(App app) { + return appDao.updateById(app); + } + + @Override + public int deleteAppById(Long id) { + return appDao.deleteById(id); + } + + @Override + public List selectNewApp() { + return appDao.selectNewApp(); + } +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/AppleServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/AppleServiceImpl.java new file mode 100644 index 0000000..60a89d3 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/AppleServiceImpl.java @@ -0,0 +1,156 @@ +package com.sqx.modules.app.service.impl; + + +import com.auth0.jwk.Jwk; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.service.IAppleService; +import io.jsonwebtoken.*; +import lombok.extern.slf4j.Slf4j; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; +import org.apache.tomcat.util.codec.binary.Base64; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.security.PublicKey; + +/** + * @Description 苹果登录service + * @author fang + * @date 2020/11/4 + */ + +@Slf4j +@Component +public class AppleServiceImpl implements IAppleService { + + @Override + public Result getAppleUserInfo(String identityToken) throws Exception { + //验证identityToken + if (!verify(identityToken)) { + log.error("苹果解析失败!"); + return Result.error("苹果账号验证失败,请退出重试!"); + } + //对identityToken解码 + JSONObject json = parserIdentityToken(identityToken); + if (json == null) { + return Result.error("苹果账号验证失败,请退出重试!"); + } + String appleUserId = String.valueOf(json.get("sub")); + log.error("苹果账号解析成功:"+appleUserId); + System.err.println(appleUserId); + return Result.success().put("data",appleUserId); + } + + /** + * 对前端传来的JWT字符串identityToken的第二部分进行解码 + * 主要获取其中的aud和sub,aud大概对应ios前端的包名,sub大概对应当前用户的授权的openID + * + * @param identityToken 身份token + * @return {"aud":"com.xkj.****","sub":"000***.8da764d3f9e34d2183e8da08a1057***.0***","c_hash":"UsKAuEoI-****","email_verified":"true","auth_time":1574673481,"iss":"https://appleid.apple.com","exp":1574674081,"iat":1574673481,"email":"****@qq.com"} + */ + private JSONObject parserIdentityToken(String identityToken) { + String[] arr = identityToken.split("\\."); + String decode = new String(Base64.decodeBase64(arr[1])); + String substring = decode.substring(0, decode.indexOf("}") + 1); + return JSONObject.fromObject(substring); + } + + + public Boolean verify(String jwt) throws Exception { + JSONArray arr = getAuthKeys(); + if (arr == null) { + log.error("获取不到苹果的验证秘钥!!"); + return false; + } + + JSONObject authKey = null; + //先取苹果第一个key进行校验 + if(arr.size()==2){ + authKey = JSONObject.fromObject(arr.getString(0)); + if (verifyExc(jwt, authKey)) { + log.error("苹果解析成功!1"); + return true; + } else { + //再取第二个key校验 + authKey = JSONObject.fromObject(arr.getString(1)); + return verifyExc(jwt, authKey); + } + }else{ + authKey = JSONObject.fromObject(arr.getString(0)); + if (verifyExc(jwt, authKey)) { + log.error("苹果解析成功!1"); + return true; + } + //再取第二个key校验 + authKey = JSONObject.fromObject(arr.getString(1)); + if(verifyExc(jwt, authKey)){ + log.error("苹果解析成功!2"); + return true; + }else{ + authKey = JSONObject.fromObject(arr.getString(2)); + return verifyExc(jwt, authKey); + } + } + } + + + /** + * 对前端传来的identityToken进行验证 + * + * @param jwt 对应前端传来的 identityToken + * @param authKey 苹果的公钥 authKey + * @return + * @throws Exception + */ + private static Boolean verifyExc(String jwt, JSONObject authKey) throws Exception { + + Jwk jwa = Jwk.fromValues(authKey); + PublicKey publicKey = jwa.getPublicKey(); + + String aud = ""; + String sub = ""; + if (jwt.split("\\.").length > 1) { + String claim = new String(Base64.decodeBase64(jwt.split("\\.")[1])); + aud = JSONObject.fromObject(claim).get("aud").toString(); + sub = JSONObject.fromObject(claim).get("sub").toString(); + } + JwtParser jwtParser = Jwts.parser().setSigningKey(publicKey); + jwtParser.requireIssuer("https://appleid.apple.com"); + jwtParser.requireAudience(aud); + jwtParser.requireSubject(sub); + + try { + Jws claim = jwtParser.parseClaimsJws(jwt); + if (claim != null && claim.getBody().containsKey("auth_time")) { + System.out.println(claim); + return true; + } + return false; + } catch (ExpiredJwtException e) { + log.error("[AppleServiceImpl.verifyExc] [error] [apple identityToken expired]", e); + return false; + } catch (Exception e) { + log.error("[AppleServiceImpl.verifyExc] [error] [apple identityToken illegal]", e); + return false; + } + } + + + /** + * 获取苹果的公钥 + * + * @return + */ + private static JSONArray getAuthKeys() { + String url = "https://appleid.apple.com/auth/keys"; + RestTemplate restTemplate = new RestTemplate(); + JSONObject json = restTemplate.getForObject(url, JSONObject.class); + if (json != null) { + return json.getJSONArray("keys"); + } + return null; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/app/service/impl/CarServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/CarServiceImpl.java new file mode 100644 index 0000000..c97376c --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/CarServiceImpl.java @@ -0,0 +1,30 @@ +package com.sqx.modules.app.service.impl; + + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.CarDao; +import com.sqx.modules.app.dao.MsgDao; +import com.sqx.modules.app.entity.Car; +import com.sqx.modules.app.entity.Msg; +import com.sqx.modules.app.service.CarService; +import com.sqx.modules.app.service.MsgService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +@Service("CarService") +public class CarServiceImpl extends ServiceImpl implements CarService { + + + @Override + public Result selectCarList(Integer page, Integer limit, Long userId, String userName, String phone){ + return Result.success().put("data",baseMapper.selectCarList(new Page<>(page,limit),userId,userName,phone)); + } + + + + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/CityAgencyServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/CityAgencyServiceImpl.java new file mode 100644 index 0000000..5c875e0 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/CityAgencyServiceImpl.java @@ -0,0 +1,26 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.CityAgencyDao; +import com.sqx.modules.app.entity.CityAgency; +import com.sqx.modules.app.service.CityAgencyService; +import org.springframework.stereotype.Service; + +/** + * 商户 + */ +@Service +public class CityAgencyServiceImpl extends ServiceImpl implements CityAgencyService { + + + @Override + public Result selectCityAgencyList(Integer page,Integer limit,String userName,String phone,Integer classify){ + Page pages=new Page<>(page,limit); + return Result.success().put("data",new PageUtils(baseMapper.selectCityAgencyList(pages,userName,phone,classify))); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/MsgServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/MsgServiceImpl.java new file mode 100644 index 0000000..f7912d7 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/MsgServiceImpl.java @@ -0,0 +1,30 @@ +package com.sqx.modules.app.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.app.dao.MsgDao; +import com.sqx.modules.app.entity.Msg; +import com.sqx.modules.app.service.MsgService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +@Service("MsgService") +public class MsgServiceImpl extends ServiceImpl implements MsgService { + + @Autowired + private MsgDao msgDao; + + @Override + public Msg findByPhone(String phone){ + return msgDao.findByPhone(phone); + } + + @Override + public Msg findByPhoneAndCode(String phone, String msg){ + return msgDao.findByPhoneAndCode(phone,msg); + } + + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/UserBrowseServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/UserBrowseServiceImpl.java new file mode 100644 index 0000000..322eacc --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/UserBrowseServiceImpl.java @@ -0,0 +1,149 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserBrowseDao; +import com.sqx.modules.app.dao.UserFollowDao; +import com.sqx.modules.app.dao.UserVisitorDao; +import com.sqx.modules.app.entity.UserBrowse; +import com.sqx.modules.app.entity.UserFollow; +import com.sqx.modules.app.entity.UserVisitor; +import com.sqx.modules.app.response.UserFollowResponse; +import com.sqx.modules.app.service.UserBrowseService; +import com.sqx.modules.taking.dao.GameDao; +import com.sqx.modules.taking.dao.OrderTakingDao; +import com.sqx.modules.taking.entity.Game; +import com.sqx.modules.taking.entity.OrderTaking; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +@AllArgsConstructor +public class UserBrowseServiceImpl extends ServiceImpl implements UserBrowseService { + private UserFollowDao userFollowDao; + private OrderTakingDao orderTakingDao; + private UserVisitorDao userVisitorDao; + private GameDao gameDao; + private UserBrowseDao userBrowseDao; + + @Override + public Result selectMyVisitor(Long userId, Long page, Long limit) { + //查询我的访客 + IPage iPage = new Page(page, limit); + return Result.success().put("data", new PageUtils(userVisitorDao.selectMyVisitor(iPage, userId))); + } + + @Override + public Result selectMyBrowse(Long userId, Long page, Long limit) { + //查询我的浏览 + IPage iPage = new Page(page, limit); + IPage iPage1 = baseMapper.selectMyBrowse(iPage, userId); + List lists = iPage1.getRecords(); + for (UserFollowResponse userFollowResponse : lists) { + if (userFollowResponse != null) { + OrderTaking orderTaking = orderTakingDao.selectById(userFollowResponse.getTakingId()); + if(orderTaking!=null){ + userFollowResponse.setOrderTaking(orderTaking); + } + } + } + return Result.success().put("data", new PageUtils(iPage1)); + } + + @Override + public Result selectAmount(Long userId) { + Map map = new HashMap<>(); + baseMapper.selectMyVisitor1(userId); + map.put("fans", userFollowDao.selectFans1(userId).size()); + map.put("follow", userFollowDao.selectMyFollow1(userId).size()); + map.put("visitor", userVisitorDao.selectMyVisitor1(userId).size()); + map.put("browse", baseMapper.selectMyBrowse1(userId).size()); + return Result.success().put("data", map); + } + + @Override + public Result addAmount(Long userId, Long byBrowseId, Long takingId) { + + UserBrowse userBrowse = baseMapper.selectOne(new QueryWrapper().eq("user_id", userId).eq("taking_id", takingId)); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if (userBrowse != null) { + userBrowse.setUpdateTime(simpleDateFormat.format(new Date())); + baseMapper.updateById(userBrowse); + } else { + UserBrowse userBrowse1 = new UserBrowse(); + userBrowse1.setUserId(userId); + userBrowse1.setByBrowseId(byBrowseId); + userBrowse1.setTakingId(takingId); + userBrowse1.setUpdateTime(simpleDateFormat.format(new Date())); + baseMapper.insert(userBrowse1); + } + return Result.success(); + } + + @Override + public Result addVisitor(Long userId, Long byBrowseId) { + if (userId.equals(byBrowseId)) { + return Result.success(); + } else if (byBrowseId == null) { + return Result.success(); + } else { + UserVisitor userVisitor = userVisitorDao.selectOne(new QueryWrapper().eq("user_id", userId).eq("by_user_id", byBrowseId)); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if (userVisitor != null) { + userVisitor.setUpdateTime(simpleDateFormat.format(new Date())); + userVisitorDao.updateById(userVisitor); + } else { + UserVisitor userVisitor1 = new UserVisitor(); + userVisitor1.setUserId(userId); + userVisitor1.setByUserId(byBrowseId); + userVisitor1.setUpdateTime(simpleDateFormat.format(new Date())); + userVisitorDao.insert(userVisitor1); + } + return Result.success(); + } + } + + @Override + public Result deleteMyVisitor(Long id) { + UserVisitor userVisitor = userVisitorDao.selectById(id); + if (userVisitor == null) { + return Result.error("访客已被删除!"); + } else { + int i = userVisitorDao.deleteById(userVisitor.getId()); + if (i > 0) { + return Result.success(); + } else { + return Result.error(); + } + } + + } + + @Override + public Result deleteMyBrowse(Long id) { + + UserBrowse userBrowse = userBrowseDao.selectById(id); + if (userBrowse == null) { + return Result.error("足迹已被删除!"); + } else { + int i = userBrowseDao.deleteById(id); + if (i > 0) { + return Result.success(); + } else { + return Result.error(); + } + } + } + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/UserCertificationImpl.java b/src/main/java/com/sqx/modules/app/service/impl/UserCertificationImpl.java new file mode 100644 index 0000000..5709c43 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/UserCertificationImpl.java @@ -0,0 +1,174 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserCertificationDao; +import com.sqx.modules.app.dao.UserDao; +import com.sqx.modules.app.entity.UserCertification; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserCertificationService; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import io.swagger.annotations.ApiParam; +import lombok.AllArgsConstructor; +import org.apache.catalina.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +@Service +@AllArgsConstructor +public class UserCertificationImpl extends ServiceImpl implements UserCertificationService { + private UserDao userDao; + @Autowired + private UserMoneyService moneyService; + @Autowired + private UserMoneyDetailsService moneyDetailsService; + + @Override + public Result insert(UserCertification userCertification) { + //查询身份证是否被绑定 + UserCertification oldUserCertification = baseMapper.selectOne(new QueryWrapper().eq("id_number", userCertification.getIdNumber()).eq("status", 1)); + if (oldUserCertification != null) { + return Result.error("身份证号已经被绑定"); + } else { + //查询是否实名过 + UserCertification userCertification1 = baseMapper.selectOne(new QueryWrapper().eq("user_id", userCertification.getUserId())); + if (userCertification1 == null) { + userCertification.setCreateTime(DateUtils.format(new Date())); + userCertification.setStatus(0); + baseMapper.insert(userCertification); + } else { + userCertification.setStatus(0); + userCertification.setId(userCertification1.getId()); + userCertification.setUpdateTime(DateUtils.format(new Date())); + baseMapper.updateById(userCertification); + } + return Result.success(); + } + } + + @Override + public Result isInsert(Long userId) { + UserCertification userCertification = baseMapper.selectOne(new QueryWrapper().eq("user_id", userId).eq("status", 1)); + if (userCertification != null) { + return Result.success(); + } else { + return Result.error(); + } + } + + public static Integer getAgeByCertId(String certId) { + String birthday = ""; + if (certId.length() == 18) { + birthday = certId.substring(6, 10) + "/" + + certId.substring(10, 12) + "/" + + certId.substring(12, 14); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); + Date now = new Date(); + Date birth = new Date(); + try { + birth = sdf.parse(birthday); + } catch (ParseException e) { + } + long intervalMilli = now.getTime() - birth.getTime(); + int age = (int) (intervalMilli / (24 * 60 * 60 * 1000)) / 365; + return age; + } + + + @Override + public Result queryCertification(Long page, Long limit, String status, String name) { + + if (page == null || limit == null) { + return Result.error("分页参数为空"); + } else { + IPage iPage = new Page(page, limit); + String nname = null; + if (name != null && !(name.equals(""))) { + nname = "%" + name + "%"; + } + IPage iPage1 = baseMapper.queryCertification(iPage, status, nname); + List userCertifications = iPage1.getRecords(); + for (UserCertification userCertification : userCertifications) { + if (userCertification != null) { + //关联用户 + userCertification.setUserEntity(userDao.selectById(userCertification.getUserId())); + } + } + return Result.success().put("data", new PageUtils(iPage1)); + } + } + + @Override + public Result queryUserCertification(IPage iPage, String name, String phone) { + String nname = null; + if (name != null && !(name.equals(""))) { + nname = "%" + name + "%"; + } + String nphone = null; + if (phone != null && !(phone.equals(""))) { + nphone = "%" + phone + "%"; + } + + return Result.success().put("data", baseMapper.queryUserCertification(iPage, nname, nphone)); + } + + @Override + public Result auditorUserCertification(Integer status, Long id, String remek) { + UserCertification userCertification = baseMapper.selectById(id); + if (userCertification != null) { + if (status == 1) { + UserEntity userEntity = userDao.selectById(userCertification.getUserId()); + userEntity.setIsAuthentication(1); + userEntity.setShopPhone(userCertification.getPhone()); + userDao.updateById(userEntity); + } + userCertification.setStatus(status); + userCertification.setRemek(remek); + baseMapper.updateById(userCertification); + return Result.success(); + } else { + return Result.error("要审核的信息不存在!"); + } + } + + @Override + public Result queryInsert(Long userId) { + return Result.success().put("data", baseMapper.selectOne(new QueryWrapper().eq("user_id", userId))); + } + + @Override + public Result updateCertification(UserCertification userCertification) { + if (userCertification.getUserId() == null) { + return Result.error("用户id不能为空"); + } + return Result.upStatus(baseMapper.update(userCertification, new QueryWrapper().eq("user_id", userCertification.getUserId()))); + + } + + @Override + public HashMap safetyMoneyStatistics() { + HashMap hashMap = new HashMap<>(); + //在线保证金 + BigDecimal hasSafetyMoney = moneyService.sumHasSafetyMoney(); + //已退保证金 + BigDecimal retMoney = moneyDetailsService.safetyMoneyStatistics(); + hashMap.put("hasSafetyMoney", hasSafetyMoney); + hashMap.put("retMoney", retMoney); + hashMap.put("allMoney", hasSafetyMoney.add(retMoney)); + return hashMap; + } +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/UserFollowServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/UserFollowServiceImpl.java new file mode 100644 index 0000000..ee1e230 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/UserFollowServiceImpl.java @@ -0,0 +1,139 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserDao; +import com.sqx.modules.app.dao.UserFollowDao; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserFollow; +import com.sqx.modules.app.response.UserFollowResponse; +import com.sqx.modules.app.service.UserFollowService; +import lombok.AllArgsConstructor; +import org.checkerframework.checker.units.qual.A; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +@Service +public class UserFollowServiceImpl extends ServiceImpl implements UserFollowService { + + @Autowired + private UserDao userDao; + private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true); + + @Override + public Result insert(Long userId, Long followUserId) { + reentrantReadWriteLock.writeLock().lock(); + try{ + //查询是否关注过此接单 + QueryWrapper queryWrapper = new QueryWrapper(); + queryWrapper.eq("user_id", userId); + queryWrapper.eq("follow_user_id", followUserId); + UserFollow user = baseMapper.selectOne(queryWrapper); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //如果没关注 关注 + if (user == null) { + String data = simpleDateFormat.format(new Date()); + UserFollow userFollow = new UserFollow(); + userFollow.setUserId(userId); + userFollow.setFollowUserId(followUserId); + userFollow.setCreateTime(data); + baseMapper.insert(userFollow); + return Result.success("关注成功"); + } else { + //关注了 取消关注 + baseMapper.deleteById(user.getFollowId()); + return Result.success("取消关注成功"); + } + }catch (Exception e){ + e.printStackTrace(); + log.error("关注出错了!"+e.getMessage(),e); + }finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + @Override + public Result selectMyFollow(Long userId, Long page, Long limit) { + IPage iPage = new Page<>(page, limit); + //查看我的关注 + IPage iPage1 = baseMapper.selectMyFollow(iPage, userId); + List lists = iPage1.getRecords(); + for (UserFollowResponse userFollowResponse : lists) { + if (userFollowResponse != null) { + //用我关注的用户id 去查询是否关注过我 + List list = baseMapper.selectMyFollow1(userFollowResponse.getUserId()); + if (list.size() > 0) { + for (UserFollowResponse userFollow : list) { + if (userFollow.getUserId().equals(userId)) { + //他也关注我 state 1 + userFollowResponse.setStatus(1); + break; + } else { + //他没关注我 state 2 + userFollowResponse.setStatus(2); + } + } + } else { + //他没关注我 state 2 + userFollowResponse.setStatus(2); + } + } + } + + return Result.success().put("data", new PageUtils(iPage1)); + } + + @Override + public Result selectFans(Long userId, Long page, Long limit) { + IPage iPage = new Page<>(page, limit); + //查看我的粉丝 + IPage page1 = baseMapper.selectFans(iPage, userId); + List lists = page1.getRecords(); + for (UserFollowResponse userFollowResponse : lists) { + if (userFollowResponse != null) { + //查询我是否关注我的粉丝 + List list = baseMapper.selectFans1(userFollowResponse.getUserId()); + if (list.size() > 0) { + for (UserFollowResponse userFollow : list) { + if (userFollow.getUserId().equals(userId)) { + //我关注了 state 1 + userFollowResponse.setStatus(1); + break; + } else { + //我没关注 state 2 + userFollowResponse.setStatus(2); + } + } + } else { + //他没关注我 state 2 + userFollowResponse.setStatus(2); + } + } + + } + return Result.success().put("data", new PageUtils(page1)); + } + + @Override + public Result selectFollowUser(Long userId, Long followUserId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("user_id", userId); + queryWrapper.eq("follow_user_id", followUserId); + UserFollow userFollow = baseMapper.selectOne(queryWrapper); + if (userFollow != null) { + return Result.success().put("data", true); + } else { + return Result.success().put("data", false); + } + } +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/UserMoneyDetailsServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/UserMoneyDetailsServiceImpl.java new file mode 100644 index 0000000..975a96f --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/UserMoneyDetailsServiceImpl.java @@ -0,0 +1,62 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserMoneyDetailsDao; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.util.List; + +@Service +public class UserMoneyDetailsServiceImpl extends ServiceImpl implements UserMoneyDetailsService { + @Autowired + private UserService userService; + + @Override + public Result queryUserMoneyDetails(Integer page, Integer limit, Long userId, Integer classify, Integer type, String phone, String ordersNo, String userName) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + + IPage userMoneyDetailsIPage = baseMapper.queryUserMoneyDetails(pages, userId,classify,type,phone,ordersNo,userName); + List records = userMoneyDetailsIPage.getRecords(); + for (UserMoneyDetails userMoneyDetails : records) { + UserEntity user = userService.getById(userMoneyDetails.getUserId()); + userMoneyDetails.setUserEntity(user); + } + return Result.success().put("data", userMoneyDetailsIPage); + } + + + @Override + public Double monthIncome(String date, Long userId) { + return baseMapper.monthIncome(date,userId); + } + + @Override + public Double selectLaundrySumMoney(Long userId) { + return baseMapper.selectLaundrySumMoney(userId); + } + + @Override + public BigDecimal safetyMoneyStatistics() { + + return baseMapper.safetyMoneyStatistics(); + + + } + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/UserMoneyServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/UserMoneyServiceImpl.java new file mode 100644 index 0000000..f8cbc1b --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/UserMoneyServiceImpl.java @@ -0,0 +1,488 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.*; +import com.sqx.modules.app.entity.*; +import com.sqx.modules.app.service.*; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.service.OrdersService; +import jodd.util.StringUtil; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +@Service +@Slf4j +public class UserMoneyServiceImpl extends ServiceImpl implements UserMoneyService { + @Autowired + private UserMoneyDetailsDao userMoneyDetailsDao; + @Autowired + private OrdersDao ordersDao; + @Autowired + private UserVipDao userVipDao; + @Autowired + private VipDetailsDao vipDetailsDao; + @Autowired + private UserDao userDao; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private MessageService messageService; + @Autowired + private UserService userService; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private CommonInfoService commonInfoService; + private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true); + + + @Override + public void updateMoney(int i, Long userId, BigDecimal money) { + baseMapper.updateMayMoney(i, userId, money); + } + + @Override + public void updateSafetyMoney(int i, Long userId, BigDecimal money) { + baseMapper.updateSafetyMoney(i, userId, money); + } + + @Override + public UserMoney selectUserMoneyByUserId(Long userId) { + UserMoney userMoney = baseMapper.selectOne(new QueryWrapper().eq("user_id", userId)); +// if(userMoney==null){ +// userMoney=new UserMoney(); +// userMoney.setMoney(BigDecimal.ZERO); +// userMoney.setUserId(userId); +// userMoney.setSafetyMoney(BigDecimal.ZERO); +// baseMapper.insert(userMoney); +// } + return userMoney; + } + + @Override + public void updateSafetyMoneyWay(Long id,Integer safetyMoneyWay,String orderNo){ + UserMoney userMoney=new UserMoney(); + userMoney.setId(id); + userMoney.setSafetyMoneyWay(safetyMoneyWay); + userMoney.setOrderNo(orderNo); + baseMapper.updateById(userMoney); + } + + @Override + public Double selectMyProfit(Long userId) { + + return userMoneyDetailsDao.selectMyProfit(userId); + } + + @Override + public synchronized Result payTakingOrder(Long userId, Long orderId) { + //时间类型 + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //查看订单 + Orders orders = ordersDao.selectOne(new QueryWrapper().eq("orders_id", orderId)); + if (orders == null) { + return Result.error("订单不存在!"); + } else { + //如果是接单订单 + if (orders.getOrdersType() == 1) { + if (orders.getState().equals("1")) { + return Result.error("订单进行中!"); + } else if (orders.getState().equals("2")) { + return Result.error("订单已完成!"); + } else if (orders.getState().equals("3")) { + return Result.error("订单已退款!"); + } else { + //订单状态为待支付 + //查看用户账户余额 + UserMoney userMoney = selectUserMoneyByUserId(userId); + if (userMoney == null) { + return Result.error("用户钱包信息不存在!"); + } else { + //用户余额 + BigDecimal money = userMoney.getMoney(); + int i = money.compareTo(orders.getPayMoney()); + if (i >= 0) { + //修改我的的余额 + baseMapper.updateMayMoney(2, userId, orders.getPayMoney()); + //设置订单状态 + orders.setState("1"); + //设置更新时间 + orders.setUpdateTime(simpleDateFormat.format(new Date())); + //更新到订单表中 + ordersDao.updateById(orders); + return Result.success("支付成功!"); + + } else { + return Result.error("余额不足!"); + } + } + } + } else { + //会员订单 + if (orders.getState().equals("1")) { + return Result.error("订单进行中!"); + } else if (orders.getState().equals("2")) { + return Result.error("订单已完成!"); + } else if (orders.getState().equals("3")) { + return Result.error("订单已退款!"); + } else { + //订单的状态为待支付 + //查看用户账户余额 + UserMoney userMoney = selectUserMoneyByUserId(userId); + //用户余额 + BigDecimal money = userMoney.getMoney(); + int i = money.compareTo(orders.getPayMoney()); + if (i >= 0) { + Long vipTypeId = orders.getVipDetailsId(); + //查看要开通会员类型 + VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper().eq("id", vipTypeId)); + UserEntity userEntity = userService.selectUserById(userId); + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + MessageInfo messageInfo=new MessageInfo(); + userMoneyDetails.setMoney(orders.getPayMoney()); + userMoneyDetails.setUserId(orders.getUserId()); + if ((vipDetails.getVipNameType().equals(0))) { + //月 + userMoneyDetails.setContent("开通月卡会员"); + messageInfo.setContent("开通会员成功"); + } else if ((vipDetails.getVipNameType()).equals(1)) { + //季 + userMoneyDetails.setContent("开通季卡会员"); + messageInfo.setContent("开通会员成功"); + } else { + //年 + userMoneyDetails.setContent("开通年费会员"); + messageInfo.setContent("开通会员成功"); + } + userMoneyDetails.setTitle("开通会员"); + userMoneyDetails.setType(2); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + messageInfo.setTitle("开通会员"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if(StringUtil.isNotBlank(userEntity.getClientid())){ + userService.pushToSingle(messageInfo.getTitle(),messageInfo.getContent(),userEntity.getClientid()); + } + //修改我的的余额 + baseMapper.updateMayMoney(2, userId, orders.getPayMoney()); + //设置订单状态 + orders.setState("2"); + //设置更新时间 + orders.setUpdateTime(simpleDateFormat.format(new Date())); + //更新到订单表中 + ordersDao.updateById(orders); + //查看会员类型 + + //查看用户是否是会员 + UserVip userVip = userVipDao.selectOne(new QueryWrapper().eq("user_id", userId)); + //日历 + Calendar cal = Calendar.getInstance(); + if (userVip != null) { + //是会员 + //查看会员到期时间 + Date endDate = null; + try { + endDate = simpleDateFormat.parse(userVip.getEndTime()); + } catch (Exception e) { + e.getMessage(); + } + //查看会员是否到期 + if (endDate != null && System.currentTimeMillis() < (endDate.getTime())) { + //没有到期 + if (vipDetails != null) { + //设置会员到期时间到日历 + cal.setTime(endDate); + //判断会员的续费时间 + if ((vipDetails.getVipNameType().equals(0))) { + //月 + cal.add(Calendar.MONTH, 1); + } else if ((vipDetails.getVipNameType()).equals(1)) { + //季 + cal.add(Calendar.MONTH, 3); + } else { + //年 + cal.add(Calendar.YEAR, 1); + } + //设置会员的到期时间 + userVip.setEndTime(simpleDateFormat.format(cal.getTime())); + //更新会员信息 + userVipDao.updateById(userVip); + //填写邀请码则奖励金币 没有则不奖励 + addMoney(userId, vipDetails); + return Result.success("开通成功!"); + } else { + return Result.error("会员类型详情为空!"); + } + //没有开通过会员 或会员已经到期 + } else { + //到期了 + //将现在的时间设置到日历中去 + cal.setTime(new Date()); + //判断会员续费的时间 + if ((vipDetails.getVipNameType()).equals(0)) { + //月 + cal.add(Calendar.MONTH, 1); + } else if ((vipDetails.getVipNameType()).equals(1)) { + //季 + cal.add(Calendar.MONTH, 3); + } else { + //年 + cal.add(Calendar.YEAR, 1); + } + //设置会员的到期时间 + userVip.setEndTime(simpleDateFormat.format(cal.getTime())); + //更新会员信息 + userVipDao.updateById(userVip); + //填写邀请码则奖励金币 没有则不奖励 + addMoney(userId, vipDetails); + return Result.success("开通成功!"); + } + + } else { + //不是会员 + //创建会员对象 + UserVip userVip1 = new UserVip(); + //设置会员类型 + userVip1.setVipNameType(vipDetails.getVipNameType()); + //设置开通会员的用户id + userVip1.setUserId(userId); + //设置会员的购买时间 + userVip1.setCreateTime(simpleDateFormat.format(new Date())); + //将现在时间设置到日历中 + cal.setTime(new Date()); + //判断会员的续费时间 + if ((vipDetails.getVipNameType()).equals(0)) { + //月 + cal.add(Calendar.MONTH, 1); + } else if ((vipDetails.getVipNameType()).equals(1)) { + //季 + cal.add(Calendar.MONTH, 3); + } else { + //年 + cal.add(Calendar.YEAR, 1); + } + //设置会员的到期时间 + userVip1.setEndTime(simpleDateFormat.format(cal.getTime())); + //设置会员 + userVipDao.insert(userVip1); + //填写邀请码则奖励金币 没有则不奖励 + addMoney(userId, vipDetails); + return Result.success("开通成功!"); + } + + } else { + return Result.error("余额不足!"); + } + + + } + } + + } + } + + @Override + public PageUtils balanceDetailed(Long userId, Page pages) { + return new PageUtils(userMoneyDetailsDao.selectPage(pages,new QueryWrapper().eq("user_id",userId).orderByDesc("create_time "))); + } + + @Override + public Result profitDetailed(Long userId, IPage ipage) { + //收益明细 + return null; + } + + + /** + * 开通成功会员后 奖励金币 + * + * @param userId + * @param + */ + public void addMoney(Long userId, VipDetails vipDetails) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //是否填写过邀请码 + UserEntity userEntity = userDao.selectById(userId); + if (userEntity.getInviterCode() != null) { + //查询填写邀请码的所属人 + UserEntity user = userDao.selectOne(new QueryWrapper().eq("invitation_code", userEntity.getInviterCode())); + if(user!=null){ + //创建钱包详情模板 + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + //设置收益人 + userMoneyDetails.setUserId(user.getUserId()); + //设置购买人 + userMoneyDetails.setByUserId(userId); + //设置类型 + userMoneyDetails.setClassify(2); + userMoneyDetails.setType(1); + //设置title + userMoneyDetails.setTitle("邀请用户购买会员"); + //设置创建时间 + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + //填写过邀请码 + userMoneyDetails.setMoney(vipDetails.getAward()); + //设置内容 + userMoneyDetails.setContent("邀请用户购买会员奖励:"+vipDetails.getAward()); + userMoneyDetailsDao.insert(userMoneyDetails); + //将奖励的金币添加到受益人的钱包里 + baseMapper.updateMayMoney(1,user.getUserId(),vipDetails.getAward()); + + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("邀请用户购买会员奖励:"+vipDetails.getAward()); + messageInfo.setTitle("邀请用户购买会员"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(user.getUserName()); + messageInfo.setUserId(String.valueOf(user.getUserId())); + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + messageInfo.setCreateAt(sdf.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if(StringUtils.isNotEmpty(user.getClientid())){ + userService.pushToSingle("邀请用户购买会员","邀请用户购买会员奖励:"+vipDetails.getAward(),user.getClientid()); + } + log.info("奖励成功!"); + } + + } else { + log.error("没有填写过邀请码 无法奖励"); + } + } + + + @Override + public Result paySafetyMoney(Long userId) { + reentrantReadWriteLock.writeLock().lock(); + try { + UserEntity userEntity = userService.selectUserById(userId); + if (userEntity.getIsSafetyMoney() != null && userEntity.getIsSafetyMoney() == 1) { + return Result.error("当前账号已经缴纳过保证金了!"); + } + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + String value = commonInfoService.findOne(271).getValue(); + BigDecimal money = new BigDecimal(value); + if (userMoney.getMoney().doubleValue() < money.doubleValue()) { + return Result.error("当前账号金额不足!"); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = sdf.format(new Date()); + userMoneyService.updateMoney(2, userId, money); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setTitle("[保证金]缴纳保证金"); + userMoneyDetails.setContent("缴纳保证金,扣除:" + money); + userMoneyDetails.setType(2); + userMoneyDetails.setMoney(money); + userMoneyDetails.setCreateTime(time); + userMoneyDetailsService.save(userMoneyDetails); + + userMoneyService.updateSafetyMoney(1, userId, money); + userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setClassify(4); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setTitle("[保证金]缴纳保证金"); + userMoneyDetails.setContent("缴纳保证金,保证金增加:" + money); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(money); + userMoneyDetails.setCreateTime(time); + userMoneyDetailsService.save(userMoneyDetails); + userEntity.setIsSafetyMoney(1); + userService.updateById(userEntity); + return Result.success(); + } catch (Exception e) { + e.printStackTrace(); + log.error("缴纳保证金异常:" + e.getMessage(), e); + } finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + @Override + public BigDecimal sumHasSafetyMoney() { + + return baseMapper.sumHasSafetyMoney(); + + + } + + + @Override + public Result refundSafetMoney(Long userId) { + reentrantReadWriteLock.writeLock().lock(); + try { + UserEntity userEntity = userService.selectUserById(userId); + if (userEntity.getIsSafetyMoney() == null || userEntity.getIsSafetyMoney() != 1) { + return Result.error("当前账号未缴纳保证金!"); + } + //判断当前是否有进行中的订单 + Integer ordersCount = ordersDao.selectCount(new QueryWrapper().eq("state", 1).eq("order_taking_user_id", userId).eq("isdelete", 0)); + if (ordersCount > 0) { + return Result.error("当前账户有未完成的订单,请完成后再进行退款!"); + } + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + BigDecimal money = userMoney.getSafetyMoney(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = sdf.format(new Date()); + userMoneyService.updateMoney(1, userId, money); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setTitle("[保证金]退款保证金"); + userMoneyDetails.setContent("退款保证金,增加:" + money); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(money); + userMoneyDetails.setCreateTime(time); + userMoneyDetailsService.save(userMoneyDetails); + + userMoneyService.updateSafetyMoney(2, userId, money); + userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setClassify(4); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setTitle("[保证金]退款保证金"); + userMoneyDetails.setContent("退款保证金,保证金减少:" + money); + userMoneyDetails.setType(2); + userMoneyDetails.setMoney(money); + userMoneyDetails.setCreateTime(time); + userMoneyDetailsService.save(userMoneyDetails); + + userEntity.setIsSafetyMoney(2); + userService.updateById(userEntity); + + return Result.success(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/UserServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..9eead01 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/UserServiceImpl.java @@ -0,0 +1,1488 @@ +package com.sqx.modules.app.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.aliyun.oss.ClientException; +import com.aliyuncs.CommonRequest; +import com.aliyuncs.CommonResponse; +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.http.MethodType; +import com.aliyuncs.profile.DefaultProfile; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.getui.push.v2.sdk.ApiHelper; +import com.getui.push.v2.sdk.GtApiConfiguration; +import com.getui.push.v2.sdk.api.PushApi; +import com.getui.push.v2.sdk.common.ApiResult; +import com.getui.push.v2.sdk.dto.req.Audience; +import com.getui.push.v2.sdk.dto.req.message.PushDTO; +import com.getui.push.v2.sdk.dto.req.message.PushMessage; +import com.getui.push.v2.sdk.dto.req.message.android.GTNotification; +import com.github.qcloudsms.SmsSingleSender; +import com.github.qcloudsms.SmsSingleSenderResult; +import com.github.qcloudsms.httpclient.HTTPException; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.MsgDao; +import com.sqx.modules.app.dao.UserCertificationDao; +import com.sqx.modules.app.dao.UserDao; +import com.sqx.modules.app.dao.UserMoneyDao; +import com.sqx.modules.app.entity.*; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.app.service.UserVipService; +import com.sqx.modules.app.utils.JwtUtils; +import com.sqx.modules.app.utils.UserConstantInterface; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.file.utils.Md5Utils; +import com.sqx.modules.invite.service.InviteService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.operatorsLog.entity.OperatorsLog; +import com.sqx.modules.operatorsLog.service.OperatorsLogService; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import com.sqx.modules.tickets.dao.TicketsDao; +import com.sqx.modules.utils.EasyPoi.ExcelUtils; +import com.sqx.modules.utils.HttpClientUtil; +import com.sqx.modules.utils.InvitationCodeUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import weixin.popular.api.SnsAPI; +import weixin.popular.util.JsonUtil; + +import java.io.IOException; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +/** + * 用户 + * + * @author fang + * @date 2021/2/27 + */ + +@Service("userService") +@Slf4j +public class UserServiceImpl extends ServiceImpl implements UserService { + @Autowired + private UserVipService userVipService; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private OperatorsLogService operatorsLogService; + @Autowired + private MsgDao msgDao; + @Autowired + private TbCouponService couponService; + @Autowired + private TbCouponUserService couponUserService; + @Autowired + private JwtUtils jwtUtils; + private int number = 1; + @Autowired + private InviteService inviteService; + @Autowired + private UserMoneyDao userMoneyDao; + @Autowired + private MessageService messageService; + + @Autowired + private UserCertificationDao userCertificationDao; + @Autowired + private UserService userService; + @Autowired + private UserMoneyDetailsService moneyDetailsService; + @Autowired + private TicketsDao ticketsDao; + @Autowired + private OrdersService ordersService; + @Override + public Result selectShopList(String userName, String phone, Long laundryId) { + return Result.success().put("data", baseMapper.selectShopList(userName, phone, laundryId)); + } + + @Override + public UserEntity queryByPhone(String phone) { + return baseMapper.selectOne(new QueryWrapper().eq("phone", phone)); + } + + @Override + public UserEntity queryByOpenId(String openId) { + return baseMapper.selectOne(new QueryWrapper().eq("open_id", openId)); + } + + @Override + public UserEntity queryByShopOpenId(String shopOpenId) { + return baseMapper.selectOne(new QueryWrapper().eq("shop_open_id", shopOpenId)); + } + + @Override + public UserEntity queryByWxOpenId(String openId) { + return baseMapper.selectOne(new QueryWrapper().eq("wx_open_id", openId)); + } + + @Override + public UserEntity queryByAppleId(String appleId) { + return baseMapper.selectOne(new QueryWrapper().eq("apple_id", appleId)); + } + + @Override + public UserEntity queryByUserId(Long userId) { + UserEntity userEntity = baseMapper.selectOne(new QueryWrapper().eq("user_id", userId)); +// if (userEntity.getIsAuthentication() == null || userEntity.getIsAuthentication() != 1) { +// UserCertification userCertification = userCertificationDao.selectOne(new QueryWrapper().eq("user_id", userId)); +// if (userCertification != null && userCertification.getStatus() == 1) { +// userEntity.setIsAuthentication(1); +// baseMapper.updateById(userEntity); +// } +// } + userEntity.setTicketsCount(ticketsDao.getUserTicketCount(userId,null)); + userEntity.setBucketCount(ordersService.getUserBucketCount(userId)); + return userEntity; + } + + @Override + public UserEntity queryAgentUser(String province, String city, String district) { + return baseMapper.queryAgentUser(province, city, district); + } + + @Override + public List selectShopUserByDistance(Long laundryId) { + return baseMapper.selectShopUserByDistance(laundryId); + } + + @Override + public UserEntity queryByInvitationCode(String invitationCode) { + UserEntity user = baseMapper.selectOne(new QueryWrapper().eq("invitation_code", invitationCode)); + if (user != null) { + if (user.getRate() == null) { + user.setRate(new BigDecimal(commonInfoService.findOne(206).getValue())); + } + if (user.getZhiRate() == null) { + user.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue())); + } + if (user.getFeiRate() == null) { + user.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue())); + } + baseMapper.updateById(user); + } + return user; + } + + @Override + public Result updatePhone(String phone, String msg, Long userId) { + Msg msg1 = msgDao.findByPhoneAndCode(phone, msg); + //校验短信验证码 + if (msg1 != null) { + UserEntity userInfo = queryByPhone(phone); + if (userInfo != null) { + return Result.error("手机号已经被其他账号绑定"); + } else { + UserEntity one = baseMapper.selectById(userId); + one.setPhone(phone); + baseMapper.updateById(one); + return Result.success(); + } + } + return Result.error("验证码不正确"); + } + + @Override + public Result iosRegister(String appleId) { + if (StringUtils.isEmpty(appleId)) { + return Result.error("账号信息获取失败,请退出重试!"); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(new Date()); + // 根据返回的user实体类,判断用户是否是新用户,不是的话,更新最新登录时间,是的话,将用户信息存到数据库 + UserEntity userInfo = queryByAppleId(appleId); + if (userInfo != null) { + if (userInfo.getStatus().equals(2)) { + return Result.error("账号已被封禁,请联系客服处理!"); + } + userInfo.setUpdateTime(date); + baseMapper.updateById(userInfo); + //返回用户信息 + UserEntity user = queryByAppleId(appleId); + return getResult(user); + } else { + return Result.error(-200, "请先绑定手机号账号!"); + } + } + + @Override + public Result wxLogin(String code, Integer type) { + try { + String appid; + String secret; + if (type == null || type == 1) { + //微信小程序APPID + appid = commonInfoService.findOne(45).getValue(); + //微信小程序秘钥 + secret = commonInfoService.findOne(46).getValue(); + } else { + //微信小程序APPID + appid = commonInfoService.findOne(239).getValue(); + //微信小程序秘钥 + secret = commonInfoService.findOne(240).getValue(); + } + // 配置请求参数 + Map param = new HashMap<>(); + param.put("appid", appid); + param.put("secret", secret); + param.put("js_code", code); + param.put("grant_type", UserConstantInterface.WX_LOGIN_GRANT_TYPE); + param.put("scope", "snsapi_userinfo"); + // 发送请求 + String wxResult = HttpClientUtil.doGet(UserConstantInterface.WX_LOGIN_URL, param); + log.info(wxResult); + JSONObject jsonObject = JSONObject.parseObject(wxResult); + // 获取参数返回的 + String session_key = jsonObject.get("session_key").toString(); + //返回微信小程序openId + String open_id = jsonObject.get("openid").toString(); + Map map = new HashMap<>(); + //判断是否注册过 + if (type == null || type == 1) { + UserEntity userEntity = queryByOpenId(open_id); + if (userEntity != null && StringUtils.isNotEmpty(userEntity.getPhone())) { + map.put("flag", "2"); + } else { + map.put("flag", "1"); + } + } else { + UserEntity userEntity = queryByShopOpenId(open_id); + if (userEntity != null && StringUtils.isNotEmpty(userEntity.getPhone())) { + map.put("flag", "2"); + } else { + map.put("flag", "1"); + } + } + + + // 封装返回小程序 + map.put("session_key", session_key); + map.put("open_id", open_id); + if (jsonObject.get("unionid") != null) { + String unionid = jsonObject.get("unionid").toString(); + map.put("unionid", unionid); + } else { + map.put("unionid", "-1"); + } + + + return Result.success("登陆成功").put("data", map); + } catch (Exception e) { + System.err.println(e.toString()); + return Result.success("登录失败!"); + } + } + + + @Override + public Result wxRegister(UserEntity userInfo1) { + CommonInfo one = commonInfoService.findOne(329); + if (userInfo1.getType() == null || userInfo1.getType() == 1) { + if (StringUtils.isEmpty(userInfo1.getOpenId())) { + return Result.error("账号信息获取失败,请退出重试!"); + } + } else { + if (StringUtils.isEmpty(userInfo1.getShopOpenId())) { + return Result.error("账号信息获取失败,请退出重试!"); + } + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(new Date()); + // 根据返回的user实体类,判断用户是否是新用户,不是的话,更新最新登录时间,是的话,将用户信息存到数据库 + UserEntity userInfo; + if (userInfo1.getType() == null || userInfo1.getType() == 1) { + userInfo = queryByOpenId(userInfo1.getOpenId()); + } else { + userInfo = queryByShopOpenId(userInfo1.getShopOpenId()); + } + + if (userInfo != null) { + if (userInfo.getStatus().equals(2)) { + return Result.error("账号已被封禁,请联系客服处理!"); + } + if (StringUtils.isNotEmpty(userInfo1.getPhone())) { + if (StringUtils.isBlank(userInfo.getPhone())) { + userInfo.setPhone(userInfo1.getPhone()); + } + } + if (StringUtils.isBlank(userInfo.getUserName()) || "微信用户".equals(userInfo.getUserName())) { + if (StringUtils.isNotEmpty(userInfo.getPhone())) { + userInfo.setUserName(userInfo.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + } + } + if (StringUtils.isNotEmpty(userInfo1.getAvatar())) { + if (StringUtils.isBlank(userInfo.getAvatar())) { + userInfo.setAvatar(userInfo1.getAvatar()); + } + } + if (userInfo1.getCourseType() != null && userInfo1.getCourseType() == 1) { + if ("否".equals(one.getValue())) { + userInfo.setIsAuthentication(1); + } + } + userInfo.setUpdateTime(date); + baseMapper.updateById(userInfo); + } else { + //判断是否在app登陆过 手机号是否有账号 + UserEntity userByMobile = queryByPhone(userInfo1.getPhone()); + if (userByMobile != null) { + //有账号则绑定账号 + userByMobile.setOpenId(userInfo1.getOpenId()); + userByMobile.setShopOpenId(userInfo1.getShopOpenId()); + baseMapper.updateById(userByMobile); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("小程序账号绑定成功!"); + messageInfo.setTitle("系统通知"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userByMobile.getUserName()); + messageInfo.setUserId(String.valueOf(userByMobile.getUserId())); + messageInfo.setCreateAt(sdf.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (userByMobile.getStatus().equals(2)) { + return Result.error("账号已被封禁,请联系客服处理!"); + } + } else { + if (StringUtils.isEmpty(userInfo1.getInviterCode())) { + userInfo1.setInviterCode(commonInfoService.findOne(88).getValue()); + } + //没有则生成新账号 + userInfo1.setCreateTime(date); + userInfo1.setPlatform("小程序"); + userInfo1.setStatus(1); + if (userInfo1.getType() == null || userInfo1.getType() == 1) { + if (StringUtils.isNotEmpty(userInfo1.getPhone())) { + userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getPhone())); + } else { + userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getOpenId())); + } + } else { + if (StringUtils.isNotEmpty(userInfo1.getPhone())) { + userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getPhone())); + } else { + userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getShopOpenId())); + } + } + if (StringUtils.isBlank(userInfo1.getUserName()) || "微信用户".equals(userInfo1.getUserName())) { + if (StringUtils.isNotEmpty(userInfo1.getPhone())) { + userInfo1.setUserName(userInfo1.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + } + } + if (userInfo1.getCourseType() != null && userInfo1.getCourseType() == 1) { + if ("否".equals(one.getValue())) { + userInfo1.setIsAuthentication(1); + } + } + userInfo1.setInvitationCode(InvitationCodeUtil.toSerialCode()); + baseMapper.insertUser(userInfo1); + baseMapper.updateById(userInfo1); + //给用户创建钱包 + UserMoney userMoney = new UserMoney(); + userMoney.setUserId(userInfo1.getUserId()); + userMoney.setMoney(BigDecimal.valueOf(0)); + userMoney.setSafetyMoney(BigDecimal.ZERO); + userMoneyDao.insert(userMoney); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("恭喜您,账号注册成功!"); + messageInfo.setTitle("系统通知"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userInfo1.getUserName()); + messageInfo.setUserId(String.valueOf(userInfo1.getUserId())); + messageInfo.setCreateAt(sdf.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + UserEntity userEntity = queryByInvitationCode(userInfo1.getInviterCode()); + if (userEntity != null) { + inviteService.saveBody(userInfo1.getUserId(), userEntity); + } + } + } + //返回用户信息 + UserEntity user; + if (userInfo1.getType() == null || userInfo1.getType() == 1) { + user = queryByOpenId(userInfo1.getOpenId()); + } else { + user = queryByShopOpenId(userInfo1.getShopOpenId()); + } + return getResult(user); + } + + + @Override + public Result wxBindMobile(String phone, String code, String wxOpenId, String token, String platform, Integer sysPhone) { + Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code); + if (byPhoneAndCode == null) { + return Result.error("验证码错误"); + } + msgDao.deleteById(byPhoneAndCode.getId()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = simpleDateFormat.format(new Date()); + UserEntity userInfo = queryByPhone(phone); + if (userInfo != null) { + if (StringUtils.isNotEmpty(userInfo.getWxOpenId())) { + return Result.error("当前手机号已经被其他微信绑定"); + } + //小程序登陆过 + userInfo.setWxOpenId(wxOpenId); + String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId); + AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class); + if (user != null && user.getNickname() != null) { + if (user.getHeadimgurl() != null) { + userInfo.setAvatar(user.getHeadimgurl()); + } + userInfo.setSex(user.getSex()); + if (user.getNickname() != null) { + userInfo.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + } + } + baseMapper.updateById(userInfo); + } else { + //小程序没有登陆过 + userInfo = new UserEntity(); + String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId); + AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class); + if (user != null && user.getNickname() != null) { + if (user.getHeadimgurl() != null) { + userInfo.setAvatar(user.getHeadimgurl()); + } + userInfo.setSex(user.getSex()); + if (user.getNickname() != null) { + userInfo.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + } + } + userInfo.setWxOpenId(wxOpenId); + userInfo.setPhone(phone); + userInfo.setPlatform(platform); + userInfo.setCreateTime(time); + userInfo.setSysPhone(sysPhone); + userInfo.setStatus(1); + userInfo.setUpdateTime(time); + baseMapper.insert(userInfo); + } + UserEntity userEntity = queryByWxOpenId(userInfo.getWxOpenId()); + return getResult(userEntity); + } + + @Override + public Result iosBindMobile(String phone, String code, String appleId, String platform, Integer sysPhone) { + Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code); + if (byPhoneAndCode == null) { + return Result.error("验证码错误"); + } + msgDao.deleteById(byPhoneAndCode.getId()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = simpleDateFormat.format(new Date()); + UserEntity userInfo = queryByPhone(phone); + if (userInfo != null) { + if (StringUtils.isNotEmpty(userInfo.getAppleId())) { + return Result.error("当前手机号已经被其他苹果绑定"); + } + userInfo.setAppleId(appleId); + userInfo.setUpdateTime(simpleDateFormat.format(new Date())); + baseMapper.updateById(userInfo); + } else { + userInfo = new UserEntity(); + userInfo.setSex(0); + userInfo.setUserName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + userInfo.setPhone(phone); + userInfo.setPlatform(platform); + userInfo.setCreateTime(time); + userInfo.setSysPhone(sysPhone); + userInfo.setStatus(1); + userInfo.setUpdateTime(time); + baseMapper.insert(userInfo); + } + UserEntity userEntity = queryByAppleId(userInfo.getAppleId()); + return getResult(userEntity); + } + + + @Override + public Result wxAppLogin(String wxOpenId, String token) { + UserEntity userEntity = queryByWxOpenId(wxOpenId); + if (userEntity != null) { + if (userEntity.getStatus().equals(2)) { + return Result.error("账号已被禁用,请联系客服处理!"); + } + String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId); + AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class); + if (user != null && user.getNickname() != null) { + if (user.getHeadimgurl() != null) { + userEntity.setAvatar(user.getHeadimgurl()); + } + userEntity.setSex(user.getSex()); + if (user.getNickname() != null) { + userEntity.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + } + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userEntity.setUpdateTime(sdf.format(new Date())); + baseMapper.updateById(userEntity); + return getResult(userEntity); + } else { + return Result.error(-200, "请先绑定手机号账号!"); + } + } + + + @Override + public Result loginByOpenId(String openId) { + UserEntity userEntity = queryByWxOpenId(openId); + if (userEntity == null) { + return Result.error(-200, "未注册!"); + } + String token = jwtUtils.generateToken(userEntity.getUserId()); + Map map = new HashMap<>(); + map.put("token", token); + map.put("expire", jwtUtils.getExpire()); + map.put("user", userEntity); + return Result.success(map); + } + + + @Override + public Result registerCode(String phone, String msg, String platform, Integer sysPhone, String openId, String inviterCode, Integer courseType) { + CommonInfo one = commonInfoService.findOne(329); + Msg msg1 = msgDao.findByPhoneAndCode(phone, msg); + //校验短信验证码 + if (msg1 == null) { + return Result.error("验证码不正确"); + } + msgDao.deleteById(msg1.getId()); + //校验手机号是否存在 + UserEntity userInfo = queryByPhone(phone); + if (userInfo != null) { + if (userInfo.getStatus().equals(2)) { + return Result.error("账号已被禁用,请联系客服处理!"); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userInfo.setUpdateTime(sdf.format(new Date())); + if (courseType != null && courseType == 1) { + if ("否".equals(one.getValue())) { + userInfo.setIsPromotion(1); + } + } + baseMapper.updateById(userInfo); + return getResult(userInfo); + } else { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = simpleDateFormat.format(new Date()); + userInfo = new UserEntity(); + userInfo.setPhone(phone); + userInfo.setUserName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + userInfo.setPlatform(platform); + userInfo.setCreateTime(time); + userInfo.setSysPhone(sysPhone); + if (inviterCode != null) { + UserEntity userEntity = queryByInvitationCode(inviterCode); + if (userEntity != null) { + inviteService.saveBody(userInfo.getUserId(), userEntity); + } else { + return Result.error("邀请码不存在"); + } + } else { + userInfo.setInviterCode(commonInfoService.findOne(88).getValue()); + } + userInfo.setStatus(1); + userInfo.setWxOpenId(openId); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userInfo.setUpdateTime(sdf.format(new Date())); + if (courseType != null && courseType == 1) { + if ("否".equals(one.getValue())) { + userInfo.setIsPromotion(1); + } + } + baseMapper.insertUser(userInfo); + msgDao.deleteById(msg1.getId()); + //给用户创建钱包 + UserMoney userMoney = new UserMoney(); + userMoney.setUserId(userInfo.getUserId()); + userMoney.setMoney(BigDecimal.valueOf(0)); + userMoney.setSafetyMoney(BigDecimal.ZERO); + userMoneyDao.insert(userMoney); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("恭喜您,账号注册成功!"); + messageInfo.setTitle("系统通知"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userInfo.getUserName()); + messageInfo.setUserId(String.valueOf(userInfo.getUserId())); + messageInfo.setCreateAt(sdf.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + UserEntity userEntity = queryByInvitationCode(userInfo.getInviterCode()); + //发送新人优惠券 +// sendNewPeopleCoupon(userInfo.getUserId()); + return getResult(userInfo); + } + } + + /** + * 发送新人优惠券 + * + * @param userId + */ + @Override + public void sendNewPeopleCoupon(Long userId) { + //发送新人优惠劵 + CommonInfo couponConfig = commonInfoService.findOne(310); + String[] config = couponConfig.getValue().split(","); + //优惠券id + String couponId = config[0]; + //优惠券数量 + int num = Integer.parseInt(config[1]); + TbCoupon tbCoupon = couponService.getById(couponId); + TbCouponUser couponUser = new TbCouponUser(); + for (int i = 0; i < num; i++) { + //copy对象 + BeanUtils.copyProperties(tbCoupon, couponUser); + couponUser.setUserId(userId); + couponUser.setCreateTime(new Date()); + //是否是永久有效 + if (tbCoupon.getValidDays() != null && tbCoupon.getValidDays() != 0) { + //如果不是永久 + Calendar instance = Calendar.getInstance(); + instance.setTime(new Date()); + instance.add(Calendar.DATE, tbCoupon.getValidDays()); + couponUser.setExpirationTime(instance.getTime()); + couponUser.setValidDays(tbCoupon.getValidDays()); + } else { + couponUser.setValidDays(0); + } + couponUser.setStatus(0); + couponUserService.save(couponUser); + } + } + + @Override + public Result login(String phone, String pwd) { + UserEntity userEntity = queryByPhone(phone); + if (userEntity == null) { + return Result.error("手机号未注册!"); + } + if (!userEntity.getPassword().equals(DigestUtils.sha256Hex(pwd))) { + return Result.error("密码不正确!"); + } + if (userEntity.getStatus().equals(2)) { + return Result.error("账号已被禁用,请联系客服处理!"); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userEntity.setUpdateTime(sdf.format(new Date())); + baseMapper.updateById(userEntity); + return getResult(userEntity); + } + + + @Override + public Result getResult(UserEntity user) { + //生成token + String token = jwtUtils.generateToken(user.getUserId()); + Map map = new HashMap<>(); + map.put("token", token); + map.put("expire", jwtUtils.getExpire()); + map.put("user", user); + return Result.success(map); + } + + @Override + public Result sendMsg(String phone, String state) { + int code = (int) ((Math.random() * 9 + 1) * 100000); + System.out.println("sendMsg code is " + code); + SmsSingleSenderResult result = null; + /*if ("bindWx".equals(state)) { + UserEntity userByPhone = queryByPhone(phone); + if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getWxOpenId())) { + return Result.error("当前手机号已被其他微信账号绑定"); + } + } else if ("bindIos".equals(state)) { + UserEntity userByPhone = queryByPhone(phone); + if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getAppleId())) { + return Result.error("当前手机号已被其他苹果账号绑定"); + } + }*/ + if (phone != null) { + if ("forget".equals(state)) { + UserEntity userByPhone = queryByPhone(phone); + if (userByPhone == null) { + return Result.error("手机号未注册"); + } + } else { + UserEntity userByPhone = queryByPhone(phone); + if (userByPhone != null) { + return Result.error("当前手机号已被其他账号绑定"); + } + } + + } + CommonInfo three = commonInfoService.findOne(79); + //默认使用腾讯云 + if (three == null || "1".equals(three.getValue())) { + //腾讯云短信发送 + return sendMsgTencent(phone, state, code); + } else if ("2".equals(three.getValue())) { + //阿里云短信发送 + return sendMsgAlibaba(phone, code); + } else { + return sendMsgDXB(phone, state, code); + } + } + + + @Override + public Result sendMsg(String phone, String state, Integer code) { + CommonInfo three = commonInfoService.findOne(79); + //默认使用腾讯云 + if (three == null || "1".equals(three.getValue())) { + //腾讯云短信发送 + return sendMsgTencent(phone, state, code); + } else if ("2".equals(three.getValue())) { + //阿里云短信发送 + return sendMsgAlibaba(phone, code); + } else { + return sendMsgDXB(phone, state, code); + } + } + + + private Result sendMsgAlibaba(String phone, int code) { + //阿里云短信accessKeyId + CommonInfo three = commonInfoService.findOne(83); + String accessKeyId = three.getValue(); + //阿里云短信accessSecret + CommonInfo four = commonInfoService.findOne(84); + String accessSecret = four.getValue(); + DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret); + IAcsClient client = new DefaultAcsClient(profile); + CommonInfo name = commonInfoService.findOne(6); + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain("dysmsapi.aliyuncs.com"); + request.setSysVersion("2017-05-25"); + request.setSysAction("SendSms"); + request.putQueryParameter("RegionId", "cn-hangzhou"); + request.putQueryParameter("PhoneNumbers", phone); + request.putQueryParameter("SignName", name.getValue()); + String value = commonInfoService.findOne(80).getValue(); + request.putQueryParameter("TemplateCode", value); + request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}"); + try { + CommonResponse response = client.getCommonResponse(request); + System.out.println(response.getData()); + String data = response.getData(); + JSONObject jsonObject = JSON.parseObject(data); + if ("OK".equals(jsonObject.get("Code"))) { + Msg byPhone = msgDao.findByPhone(phone); + if (byPhone != null) { + byPhone.setCode(String.valueOf(code)); + byPhone.setPhone(phone); + msgDao.updateById(byPhone); + } else { + Msg msg = new Msg(); + msg.setCode(String.valueOf(code)); + msg.setPhone(phone); + msgDao.insert(msg); + } + /* UserEntity userByPhone = queryByPhone(phone); + if (userByPhone != null) { + return Result.success("login"); + } else { + return Result.success("register"); + }*/ + return Result.success("login"); + } else { + if (jsonObject.get("Message").toString().contains("分钟")) { + return Result.error("短信发送过于频繁,请一分钟后再试!"); + } else if (jsonObject.get("Message").toString().contains("小时")) { + return Result.error("短信发送过于频繁,请一小时后再试!"); + } else if (jsonObject.get("Message").toString().contains("天")) { + return Result.error("短信发送过于频繁,请明天再试!"); + } + log.info(jsonObject.get("Message").toString()); + return Result.error("短信发送失败!"); + } + } catch (ClientException | com.aliyuncs.exceptions.ClientException e) { + e.printStackTrace(); + } + return Result.error("验证码发送失败"); + } + + + private Result sendMsgTencent(String phone, String state, int code) { + SmsSingleSenderResult result = null; + try { + CommonInfo three = commonInfoService.findOne(31); + String clientId = three.getValue(); + + CommonInfo four = commonInfoService.findOne(32); + String clientSecret = four.getValue(); + CommonInfo name = commonInfoService.findOne(6); + /** + * 发送短信验证码的状态、 + * + * 在h5登录环境中 传的状态不是以下三种状态 + */ + SmsSingleSender ssender = new SmsSingleSender(Integer.valueOf(clientId), clientSecret); + switch (state) { + case "register": + result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + ",此验证码可用于登录或注册,10分钟内有效,如非您本人操作,可忽略本条消息", "", ""); + break; + case "forget": + result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + ",您正在执行找回密码操作,10分钟内有效,如非您本人操作,可忽略本条消息", "", ""); + break; + case "bind": + result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + ",您正在执行绑定手机号操作,10分钟内有效,如非您本人操作,可忽略本条消息", "", ""); + break; + default: + result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + ",此验证码可用于登录或注册,10分钟内有效,如非您本人操作,可忽略本条消息", "", ""); + break; + } + + + System.out.println(result); + if (result.result == 0) { + Msg byPhone = msgDao.findByPhone(phone); + if (byPhone != null) { + byPhone.setCode(String.valueOf(code)); + byPhone.setPhone(phone); + msgDao.updateById(byPhone); + } else { + Msg msg = new Msg(); + msg.setCode(String.valueOf(code)); + msg.setPhone(phone); + msgDao.insert(msg); + } + UserEntity userByPhone = queryByPhone(phone); + if (userByPhone != null) { + return Result.success("login"); + } else { + return Result.success("register"); + } + } else { + return Result.error(6, result.errMsg); + } + } catch (HTTPException | JSONException | IOException e) { + // HTTP 响应码错误 + e.printStackTrace(); + } + return Result.error("验证码发送失败"); + } + + + private Result sendMsgDXB(String phone, String state, int code) { + CommonInfo three = commonInfoService.findOne(164); + CommonInfo four = commonInfoService.findOne(165); + CommonInfo name = commonInfoService.findOne(6); + String testUsername = three.getValue(); //在短信宝注册的用户名 + String testPassword = four.getValue(); //在短信宝注册的密码 + String value = ""; + switch (state) { + case "register": + value = "【" + name.getValue() + "】验证码: " + code + ",此验证码可用于登录或注册,10分钟内有效,如非您本人操作,可忽略本条消息"; + break; + case "forget": + value = "【" + name.getValue() + "】验证码: " + code + ",您正在执行找回密码操作,10分钟内有效,如非您本人操作,可忽略本条消息"; + break; + case "bind": + value = "【" + name.getValue() + "】验证码: " + code + ",您正在执行绑定手机号操作,10分钟内有效,如非您本人操作,可忽略本条消息"; + break; + case "dx": + value = "【" + name.getValue() + "】您有" + code + "条未读消息,赶快上线查看吧!"; + break; + default: + value = "【" + name.getValue() + "】验证码: " + code + ",此验证码可用于登录或注册,10分钟内有效,如非您本人操作,可忽略本条消息"; + break; + } + StringBuilder httpArg = new StringBuilder(); + httpArg.append("u=").append(testUsername).append("&"); + httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&"); + httpArg.append("m=").append(phone).append("&"); + httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8")); + String result = Md5Utils.request("https://api.smsbao.com/sms", httpArg.toString()); + log.error("短信包返回值:" + result); + if ("0".equals(result)) { + Msg byPhone = msgDao.findByPhone(phone); + if (byPhone != null) { + byPhone.setCode(String.valueOf(code)); + byPhone.setPhone(phone); + msgDao.updateById(byPhone); + } else { + Msg msg = new Msg(); + msg.setCode(String.valueOf(code)); + msg.setPhone(phone); + msgDao.insert(msg); + } + UserEntity userByPhone = queryByPhone(phone); + if (userByPhone != null) { + return Result.success("login"); + } else { + return Result.success("register"); + } + } else { +// return ResultUtil.error(6, result.errMsg); + if ("30".equals(result)) { + return Result.error("错误密码"); + } else if ("40".equals(result)) { + return Result.error("账号不存在"); + } else if ("41".equals(result)) { + return Result.error("余额不足"); + } else if ("43".equals(result)) { + return Result.error("IP地址限制"); + } else if ("50".equals(result)) { + return Result.error("内容含有敏感词"); + } else if ("51".equals(result)) { + return Result.error("手机号码不正确"); + } + } + + return Result.error("验证码发送失败"); + } + + + @Override + public Result getOpenId(String code, Long userId) { + try { + //微信appid + CommonInfo one = commonInfoService.findOne(5); + //微信秘钥 + CommonInfo two = commonInfoService.findOne(21); + String openid = SnsAPI.oauth2AccessToken(one.getValue(), two.getValue(), code).getOpenid(); + if (StringUtils.isNotEmpty(openid)) { + UserEntity userEntity = new UserEntity(); + userEntity.setUserId(userId); + userEntity.setOpenId(openid); + baseMapper.updateById(userEntity); + return Result.success().put("data", openid); + } + return Result.error("获取失败"); + } catch (Exception e) { + log.error("GET_OPENID_FAIL"); + return Result.error("获取失败,出错了!"); + } + } + + @Override + public UserEntity selectUserById(Long userId) { + return baseMapper.selectById(userId); + } + + + @Override + public PageUtils selectUserPage(Integer page, Integer limit, String search, Integer sex, + String platform, String sysPhone, Integer status, Integer isAuthentication, + Integer isPromotion, Integer isAgent, String userName, Long laundryId, String isSafetyMoney, Integer isVip, String invitationCode, String inviterCode, Integer hasTicket) { + Page pages = new Page<>(page, limit); + return new PageUtils(baseMapper.selectUserPage(pages, search, sex, platform, sysPhone, status, isAuthentication, isPromotion, isAgent, userName, laundryId, isSafetyMoney, isVip, invitationCode, inviterCode, hasTicket)); + } + + @Override + public int queryInviterCount(String inviterCode) { + return baseMapper.queryInviterCount(inviterCode); + } + + @Override + public int queryUserCount(int type, String date, String platform, Integer isAuthentication) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"); + if (date == null || date == "") { + date = simpleDateFormat.format(new Date()); + } + return baseMapper.queryUserCount(type, date, platform, isAuthentication); + } + + @Override + public Double queryPayMoney(int type) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"); + String date = simpleDateFormat.format(new Date()); + return baseMapper.queryPayMoney(type, date); + } + + @Override + public IPage> queryCourseOrder(Page> iPage, int type, String date) { + return baseMapper.queryCourseOrder(iPage, type, date); + } + + @Override + public int userMessage(String date, int type) { + return baseMapper.userMessage(date, type); + } + + + @Override + public void pushToSingle(String title, String content, String clientId) { + GtApiConfiguration apiConfiguration = new GtApiConfiguration(); + //填写应用配置 + apiConfiguration.setAppId(commonInfoService.findOne(61).getValue()); + apiConfiguration.setAppKey(commonInfoService.findOne(60).getValue()); + apiConfiguration.setMasterSecret(commonInfoService.findOne(62).getValue()); + // 接口调用前缀,请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId + apiConfiguration.setDomain("https://restapi.getui.com/v2/"); + // 实例化ApiHelper对象,用于创建接口对象 + ApiHelper apiHelper = ApiHelper.build(apiConfiguration); + // 创建对象,建议复用。目前有PushApi、StatisticApi、UserApi + PushApi pushApi = apiHelper.creatApi(PushApi.class); + //根据cid进行单推 + PushDTO pushDTO = new PushDTO(); + // 设置推送参数 + pushDTO.setRequestId(System.currentTimeMillis() + ""); + PushMessage pushMessage = new PushMessage(); + GTNotification notification = new GTNotification(); + pushDTO.setPushMessage(pushMessage); + // 配置通知栏图标 + notification.setLogo("icon.png"); //配置通知栏图标,需要在客户端开发时嵌入,默认为push.png + // 配置通知栏网络图标 + notification.setLogoUrl(commonInfoService.findOne(19).getValue() + "/logo.png"); + notification.setTitle(title); + notification.setBody(content); + notification.setClickType("url"); + notification.setUrl(commonInfoService.findOne(19).getValue()); + pushMessage.setNotification(notification); + // 设置接收人信息 + Audience audience = new Audience(); + audience.addCid(clientId); + pushDTO.setAudience(audience); + // 进行cid单推 + ApiResult>> apiResult = pushApi.pushToSingleByCid(pushDTO); + if (apiResult.isSuccess()) { + // success + log.error("消息推送成功:" + apiResult.getData()); + } else { + // failed + log.error("消息推送成功失败:code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg()); + } + } + + + @Override + public Result loginApp(String phone, String password) { + //md5加密 + String pwd = DigestUtils.sha256Hex(password); + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("phone", phone); + UserEntity userEntity = baseMapper.selectOne(queryWrapper); + if (userEntity == null) { + return Result.error("手机号未注册!"); + } + if (!userEntity.getPassword().equals(pwd)) { + return Result.error("密码不正确!"); + } + if (userEntity.getStatus().equals(2)) { + return Result.error("账号已被禁用,请联系客服处理!"); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userEntity.setUpdateTime(sdf.format(new Date())); + baseMapper.updateById(userEntity); + return getResult(userEntity); + + } + + @Override + public Result registApp(String userName, String phone, String password, String msg, String platform, String inviterCode, Integer courseType) { + CommonInfo serviceOne = commonInfoService.findOne(329); + Msg msg1 = msgDao.findByPhoneAndCode(phone, msg); + //校验短信验证码 + if (msg1 == null) { + return Result.error("验证码不正确"); + } + msgDao.deleteById(msg1.getId()); + //校验手机号是否存在 + UserEntity userInfo = queryByPhone(phone); + if (userInfo != null) { + return Result.error("手机号已经被注册!"); + } else { + UserEntity userEntity = null; + if (StringUtils.isNotBlank(inviterCode)) { + userEntity = queryByInvitationCode(inviterCode); + if (userEntity == null) { + return Result.error("邀请码不存在"); + } + } else { + inviterCode = commonInfoService.findOne(88).getValue(); + } + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = simpleDateFormat.format(new Date()); + userInfo = new UserEntity(); + userInfo.setPhone(phone); + userInfo.setUserName(userName); + //对密码进行MD5加密 + userInfo.setPassword(DigestUtils.sha256Hex(password)); + userInfo.setPlatform(platform); + userInfo.setCreateTime(time); + userInfo.setStatus(1); + userInfo.setInviterCode(inviterCode); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userInfo.setCreateTime(sdf.format(new Date())); + userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode()); + if (courseType != null && courseType == 1) { + if ("否".equals(serviceOne.getValue())) { + userInfo.setIsAuthentication(1); + } + } + baseMapper.insertUser(userInfo); + //设置自己邀请码 + baseMapper.updateById(userInfo); + //给用户创建钱包 + UserMoney userMoney = new UserMoney(); + userMoney.setUserId(userInfo.getUserId()); + userMoney.setMoney(BigDecimal.valueOf(0)); + userMoney.setSafetyMoney(BigDecimal.ZERO); + userMoneyDao.insert(userMoney); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("恭喜您,账号注册成功!"); + messageInfo.setTitle("系统通知"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userInfo.getUserName()); + messageInfo.setUserId(String.valueOf(userInfo.getUserId())); + messageInfo.setCreateAt(sdf.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (userEntity != null) { + inviteService.saveBody(userInfo.getUserId(), userEntity); + } + return getResult(userInfo); + } + + } + + + @Override + public Result forgetPwd(String pwd, String phone, String msg) { + try { + Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, msg); + //校验短信验证码 + if (byPhoneAndCode == null) { + return Result.error("验证码不正确"); + } + UserEntity userByPhone = queryByPhone(phone); + userByPhone.setPassword(DigestUtils.sha256Hex(pwd)); + msgDao.deleteById(byPhoneAndCode.getId()); + baseMapper.updateById(userByPhone); + return Result.success(); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("服务器内部错误"); + } + } + + /** + * 公共用户桶操作 + * + * @param userType 1管理员 2师傅 3用户 + * @param updateUserId 修改人id + * @param userId 被修改的用户id + * @param num 修改数量 注意:值为修改(增加或减少)后的数量 + * @return + */ + @Override + public Result updateUserBucket(Integer userType, Long updateUserId, Long userId, Integer num, Long ordersId) { + UserEntity userEntity = userService.getById(userId); + + OperatorsLog operatorsLog = new OperatorsLog(); + operatorsLog.setUpdateUserId(updateUserId); + operatorsLog.setUserType(userType); + operatorsLog.setLastBucket(userEntity.getBucket()); + operatorsLog.setUserId(userId); + operatorsLog.setUserName(userEntity.getUserName()); + operatorsLog.setUserPhone(userEntity.getPhone()); + if (num > userEntity.getBucket()) { + operatorsLog.setOperator(1); + operatorsLog.setOperatorNum(num - userEntity.getBucket()); + } else if (num < userEntity.getBucket()) { + operatorsLog.setOperator(2); + operatorsLog.setOperatorNum(userEntity.getBucket() - num); + } else { + return Result.success(); + } + userEntity.setBucket(num); + operatorsLog.setNextBucket(userEntity.getBucket()); + + baseMapper.updateById(userEntity); + + operatorsLogService.addUpdateUserBucketLog(operatorsLog); + if (ordersId != null) { + Orders orders = new Orders(); + orders.setOrdersId(ordersId); + orders.setIsUpdateBucket(1); + ordersService.updateById(orders); + } + return Result.success(); + + + } + + @Override + public Integer getAllBucket() { + + return baseMapper.getAllBucket(); + + + } + + @Override + public Result takingOrdersMessage(Page> iPage, Long type, String date) { + //接单分析 + return Result.success().put("data", new PageUtils(baseMapper.takingOrdersMessage(iPage, type, date))); + } + + @Override + public int updateUserInfoLaundryIdIsNull(Long laundryId) { + return baseMapper.updateUserInfoLaundryIdIsNull(laundryId); + } + + @Override + public Result selectUserOrdersList(Integer page, Integer limit, Long laundryId, String userName, String phone, String time, Integer flag) { + return Result.success().put("data", new PageUtils(baseMapper.selectUserOrdersList(new Page<>(page, limit), laundryId, userName, phone, time, flag))); + } + + + @Override + public IPage getNearbyWorker(Integer page, Integer limit, Double lng, Double lat) { + if (lng == null || lat == null) { + return null; + } + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + String distance = commonInfoService.findOne(325).getValue(); + + + return baseMapper.getNearbyWorker(pages, lng, lat, distance + "000"); + + + } + + @Override + public Result giveUserVip(Long userId, Integer day) { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + UserVip userVip; + userVip = userVipService.getOne(new QueryWrapper().eq("user_id", userId)); + if (userVip == null) { + userVip = new UserVip(); + userVip.setVipNameType(3); + userVip.setUserId(userId); + userVip.setCreateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); + userVip.setIsVip(1); + LocalDateTime dateTime = LocalDateTime.now().plusDays(day); + userVip.setEndTime(fmt.format(dateTime)); + userVipService.save(userVip); + } else { + //会员过期时间 + LocalDateTime parse = LocalDateTime.parse(userVip.getEndTime(), fmt); + //如果已经过期,则从当前时间开始计算 + if (parse.isBefore(LocalDateTime.now())) { + String endTime = fmt.format(LocalDateTime.now().plusDays(day)); + userVip.setEndTime(endTime); + } else { + //如果未过期,则从过期时间开始计算 + String endTime = fmt.format(LocalDateTime.parse(userVip.getEndTime(), fmt).plusDays(day)); + userVip.setEndTime(endTime); + } + userVipService.updateById(userVip); + } + return Result.success(); + } + + @Override + public Result cancelUserVip(Long userId) { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + UserVip userVip = userVipService.getOne(new QueryWrapper().eq("user_id", userId)); + userVip.setEndTime(LocalDateTime.now().format(fmt)); + return userVipService.updateById(userVip) ? Result.success() : Result.error("取消失败"); + } + + @Override + public Result bucketCallback(Long userId, Integer num, BigDecimal payMoney, Integer classify) { + UserEntity userEntity = userService.getById(userId); + userService.updateById(userEntity); + + this.updateUserBucket(3, userId, userId, userEntity.getBucket() + num, null); + + UserMoneyDetails moneyDetails = new UserMoneyDetails(); + moneyDetails.setUserId(userId); + moneyDetails.setTitle("花费" + payMoney + "元购买桶数量" + num + "个"); + moneyDetails.setContent("花费" + payMoney + "元购买桶数量" + num + "个"); + moneyDetails.setClassify(8); + moneyDetails.setType(2); + moneyDetails.setMoney(payMoney); + moneyDetails.setCreateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); + if (classify == 4 || classify == 5) { + moneyDetails.setPayType(3); + } else if (classify == 1) { + moneyDetails.setPayType(1); + } else { + moneyDetails.setPayType(2); + } + moneyDetailsService.save(moneyDetails); + return Result.success(); + } + + @Override + public Result buyBucket(Long userId, Integer num) { + CommonInfo bucket = commonInfoService.findOne(326); + BigDecimal money = new BigDecimal(num).multiply(new BigDecimal(bucket.getValue())); + UserEntity userEntity = baseMapper.selectById(userId); + if (userEntity == null) { + return Result.error("用户不存在"); + } + + UserMoney userMoney = userMoneyDao.selectOne(new QueryWrapper().eq("user_id", userId)); + if (userMoney.getMoney().compareTo(money) >= 0) { + userMoneyDao.updateMayMoney(2, userId, money); + return this.bucketCallback(userId, num, money, 1); + } else { + return Result.error("您的余额不足,请充值后购买"); + } + + } + + @Override + public Result backBucket(Long userId, Integer num) { + CommonInfo bucket = commonInfoService.findOne(326); + BigDecimal money = new BigDecimal(num).multiply(new BigDecimal(bucket.getValue())); + UserEntity userEntity = userService.getById(userId); + if (userEntity == null) { + return Result.error("用户不存在"); + } + if (userEntity.getBucket() == null) { + return Result.error("你的压桶数量为0"); + } + if (userEntity.getBucket() < num) { + return Result.error("最大可退数量为:" + userEntity.getBucket()); + } + + updateUserBucket(3, userId, userId, userEntity.getBucket() - num, null); + + userMoneyDao.updateMayMoney(1, userId, money); + UserMoneyDetails moneyDetails = new UserMoneyDetails(); + moneyDetails.setUserId(userId); + moneyDetails.setTitle("退桶" + num + "个;总计退费" + money + "元"); + moneyDetails.setContent("退桶" + num + "个;总计退费" + money + "元"); + moneyDetails.setClassify(8); + moneyDetails.setType(1); + moneyDetails.setMoney(money); + moneyDetails.setCreateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); + moneyDetails.setPayType(1); + moneyDetailsService.save(moneyDetails); + return Result.success(); + + } + @Override + public int cancelArea(UserEntity userEntity) { + + + return baseMapper.cancelArea(userEntity); + + + } + + @Override + public int setUserLaundry(Long userId) { + + + + return baseMapper.setUserLaundry(userId); + } + @Override + public Result userExcelIn(MultipartFile file) throws IOException { + List userList = ExcelUtils.importExcel(file, 2, 1, UserEntity.class); + if (CollectionUtils.isEmpty(userList)) { + return Result.error("Excel数据为空,excel转化失败!"); + } + //当前行索引(Excel的数据从第几行开始,就填写几) + int index = 4; + //失败条数 + int repeat = 0; + //成功条数 + int successIndex = 0; + for (UserEntity userEntity : userList) { + if (userEntity.getPhone() != null) { + int count = userService.count(new QueryWrapper().eq("phone", userEntity.getPhone())); + if (count == 0) { + if (StringUtils.isBlank(userEntity.getUserName())) { + userEntity.setUserName(userEntity.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2")); + } + if (userEntity.getRate() == null) { + userEntity.setRate(new BigDecimal(commonInfoService.findOne(206).getValue())); + } + if (userEntity.getZhiRate() == null) { + userEntity.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue())); + } + if (userEntity.getFeiRate() == null) { + userEntity.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue())); + } + if (StringUtils.isNotBlank(userEntity.getInviterCode())) { + UserEntity entity = userService.getOne(new QueryWrapper().eq("inviter_code", userEntity.getInviterCode())); + //邀请码不存在则不写入 + if (entity == null) { + userEntity.setInviterCode(null); + } + } + userEntity.setPlatform("H5"); + userEntity.setInvitationCode(InvitationCodeUtil.toSerialCode()); + userEntity.setPassword(DigestUtils.sha256Hex(userEntity.getPassword())); + userEntity.setCreateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); + userEntity.setUpdateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); + int result = baseMapper.insert(userEntity); + UserMoney userMoney = new UserMoney(); + userMoney.setUserId(userEntity.getUserId()); + userMoney.setMoney(BigDecimal.ZERO); + userMoneyDao.insert(userMoney); + if (result > 0) { + successIndex++; + } + } + } else { + repeat++; + } + + } + return Result.success("导入成功,共新增【" + successIndex + "】条,失败【" + (userList.size() - successIndex) + "】条,其中过滤重复数据【" + repeat + "】条"); + + + } + + @Override + public List userEntityExcelOut(String search,String phone, Integer sex, String platform, String sysPhone, Integer status, Integer isAuthentication, Integer isPromotion, Integer isAgent, String userName, Long laundryId, String isSafetyMoney, Integer isVip, String invitationCode, String inviterCode, Integer hasTicket) { + Page pages = new Page<>(); + pages.setSize(-1); + + return baseMapper.selectUserPage(pages, search, sex, platform, sysPhone, status, isAuthentication, isPromotion, isAgent, userName, laundryId, isSafetyMoney, isVip, invitationCode, inviterCode, hasTicket).getRecords(); + } + + @Override + public List> getUserBucket(Integer flag, String date) { + + + return ordersService.getUserBucket(flag,date); + + + } + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/UserVipServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/UserVipServiceImpl.java new file mode 100644 index 0000000..2c799de --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/UserVipServiceImpl.java @@ -0,0 +1,39 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserVipDao; +import com.sqx.modules.app.entity.UserVip; +import com.sqx.modules.app.service.UserVipService; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; + +@Service +public class UserVipServiceImpl extends ServiceImpl implements UserVipService { + + @Override + public UserVip selectUserVipByUserId(Long userId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("user_id", userId); + return baseMapper.selectOne(queryWrapper); + } + @Override + public Result isUserVip(Long userId) { + boolean isVip = false; + //查询用户是否是会员 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("user_id", userId); + UserVip userVip = baseMapper.selectOne(queryWrapper); + if (userVip != null) { + if (userVip.getIsVip() == 1) { + isVip = true; + } + } + return Result.success().put("data", isVip); + } + + +} diff --git a/src/main/java/com/sqx/modules/app/service/impl/VipDetailsServiceImpl.java b/src/main/java/com/sqx/modules/app/service/impl/VipDetailsServiceImpl.java new file mode 100644 index 0000000..d704aed --- /dev/null +++ b/src/main/java/com/sqx/modules/app/service/impl/VipDetailsServiceImpl.java @@ -0,0 +1,27 @@ +package com.sqx.modules.app.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.VipDetailsDao; +import com.sqx.modules.app.entity.VipDetails; +import com.sqx.modules.app.service.VipDetailsService; +import org.springframework.stereotype.Service; + +@Service +public class VipDetailsServiceImpl extends ServiceImpl implements VipDetailsService { + + @Override + public Result selectVipDetails() { + return Result.success().put("data", baseMapper.selectList(null)); + } + + @Override + public Result insertVipDetails(VipDetails vipDetails) { + int cpunt = baseMapper.insert(vipDetails); + if (cpunt > 0) { + return Result.success("添加成功!"); + } else { + return Result.error("添加失败"); + } + } +} diff --git a/src/main/java/com/sqx/modules/app/utils/HttpUtils.java b/src/main/java/com/sqx/modules/app/utils/HttpUtils.java new file mode 100644 index 0000000..ae95866 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/utils/HttpUtils.java @@ -0,0 +1,316 @@ +package com.sqx.modules.app.utils; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; + +public class HttpUtils { + + /** + * get + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @return + * @throws Exception + */ + public static HttpResponse doGet(String host, String path, String method, + Map headers, + Map querys) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpGet request = new HttpGet(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + return httpClient.execute(request); + } + + /** + * post form + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param bodys + * @return + * @throws Exception + */ + public static HttpResponse doPost(String host, String path, String method, + Map headers, + Map querys, + Map bodys) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPost request = new HttpPost(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (bodys != null) { + List nameValuePairList = new ArrayList(); + + for (String key : bodys.keySet()) { + nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); + } + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); + formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); + request.setEntity(formEntity); + } + + return httpClient.execute(request); + } + + /** + * Post String + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPost(String host, String path, String method, + Map headers, + Map querys, + String body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPost request = new HttpPost(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (StringUtils.isNotBlank(body)) { + request.setEntity(new StringEntity(body, "utf-8")); + } + + return httpClient.execute(request); + } + + /** + * Post stream + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPost(String host, String path, String method, + Map headers, + Map querys, + byte[] body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPost request = new HttpPost(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (body != null) { + request.setEntity(new ByteArrayEntity(body)); + } + + return httpClient.execute(request); + } + + /** + * Put String + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPut(String host, String path, String method, + Map headers, + Map querys, + String body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPut request = new HttpPut(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (StringUtils.isNotBlank(body)) { + request.setEntity(new StringEntity(body, "utf-8")); + } + + return httpClient.execute(request); + } + + /** + * Put stream + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPut(String host, String path, String method, + Map headers, + Map querys, + byte[] body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPut request = new HttpPut(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (body != null) { + request.setEntity(new ByteArrayEntity(body)); + } + + return httpClient.execute(request); + } + + /** + * Delete + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @return + * @throws Exception + */ + public static HttpResponse doDelete(String host, String path, String method, + Map headers, + Map querys) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + return httpClient.execute(request); + } + + private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException { + StringBuilder sbUrl = new StringBuilder(); + sbUrl.append(host); + if (!StringUtils.isBlank(path)) { + sbUrl.append(path); + } + if (null != querys) { + StringBuilder sbQuery = new StringBuilder(); + for (Map.Entry query : querys.entrySet()) { + if (0 < sbQuery.length()) { + sbQuery.append("&"); + } + if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) { + sbQuery.append(query.getValue()); + } + if (!StringUtils.isBlank(query.getKey())) { + sbQuery.append(query.getKey()); + if (!StringUtils.isBlank(query.getValue())) { + sbQuery.append("="); + sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8")); + } + } + } + if (0 < sbQuery.length()) { + sbUrl.append("?").append(sbQuery); + } + } + + return sbUrl.toString(); + } + + private static HttpClient wrapClient(String host) { + HttpClient httpClient = new DefaultHttpClient(); + if (host.startsWith("https://")) { + sslClient(httpClient); + } + + return httpClient; + } + + private static void sslClient(HttpClient httpClient) { + try { + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] xcs, String str) { + + } + + public void checkServerTrusted(X509Certificate[] xcs, String str) { + + } + }; + ctx.init(null, new TrustManager[]{tm}, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx); + ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + ClientConnectionManager ccm = httpClient.getConnectionManager(); + SchemeRegistry registry = ccm.getSchemeRegistry(); + registry.register(new Scheme("https", 443, ssf)); + } catch (KeyManagementException ex) { + throw new RuntimeException(ex); + } catch (NoSuchAlgorithmException ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/src/main/java/com/sqx/modules/app/utils/JwtUtils.java b/src/main/java/com/sqx/modules/app/utils/JwtUtils.java new file mode 100644 index 0000000..06a7ad5 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/utils/JwtUtils.java @@ -0,0 +1,86 @@ +package com.sqx.modules.app.utils; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * jwt工具类 + * + */ +@ConfigurationProperties(prefix = "sqx.jwt") +@Component +public class JwtUtils { + private Logger logger = LoggerFactory.getLogger(getClass()); + + private String secret; + private long expire; + private String header; + + /** + * 生成jwt token + */ + public String generateToken(long userId) { + Date nowDate = new Date(); + //过期时间 + Date expireDate = new Date(nowDate.getTime() + expire * 1000); + + return Jwts.builder() + .setHeaderParam("typ", "JWT") + .setSubject(userId+"") + .setIssuedAt(nowDate) + .setExpiration(expireDate) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + } + + public Claims getClaimByToken(String token) { + try { + return Jwts.parser() + .setSigningKey(secret) + .parseClaimsJws(token) + .getBody(); + }catch (Exception e){ + logger.debug("validate is token error ", e); + return null; + } + } + + /** + * token是否过期 + * @return true:过期 + */ + public boolean isTokenExpired(Date expiration) { + return expiration.before(new Date()); + } + + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public long getExpire() { + return expire; + } + + public void setExpire(long expire) { + this.expire = expire; + } + + public String getHeader() { + return header; + } + + public void setHeader(String header) { + this.header = header; + } +} diff --git a/src/main/java/com/sqx/modules/app/utils/UserConstantInterface.java b/src/main/java/com/sqx/modules/app/utils/UserConstantInterface.java new file mode 100644 index 0000000..2ba9f31 --- /dev/null +++ b/src/main/java/com/sqx/modules/app/utils/UserConstantInterface.java @@ -0,0 +1,53 @@ +package com.sqx.modules.app.utils; + + +import cn.hutool.core.codec.Base64; +import com.alibaba.fastjson.JSON; +import com.sqx.common.utils.Result; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.spec.AlgorithmParameterSpec; + +/** + * 参数配置 + */ +public interface UserConstantInterface { + + + /** + * 请求的网址 + */ + String WX_LOGIN_URL = "http://api.weixin.qq.com/sns/jscode2session"; + + /** + * 固定参数 + */ + String WX_LOGIN_GRANT_TYPE = "authorization_code"; + + /** + * 解密手机号 + * @param decryptData 加密手机号(微信返回) + * @param key session_key + * @param iv iv(微信返回) + * @return + */ + static Result decryptS5(String decryptData, String key, String iv) { + try { + byte[] encData = Base64.decode(decryptData); + byte[] ivs = Base64.decode(iv); + byte[] keys = Base64.decode(key); + AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivs); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + SecretKeySpec keySpec = new SecretKeySpec(keys, "AES"); + cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); + return Result.success("获取手机号成功").put("data", JSON.parseObject(new String(cipher.doFinal(encData), "UTF-8"))); + } catch (Exception e) { + e.printStackTrace(); + return Result.error(-1,"获取手机号失败"); + } + } + +} + diff --git a/src/main/java/com/sqx/modules/app/utils/WxPhone.java b/src/main/java/com/sqx/modules/app/utils/WxPhone.java new file mode 100644 index 0000000..d82119b --- /dev/null +++ b/src/main/java/com/sqx/modules/app/utils/WxPhone.java @@ -0,0 +1,14 @@ +package com.sqx.modules.app.utils; + +import lombok.Data; + +@Data +public class WxPhone { + + private String decryptData; + + private String key; + + private String iv; + +} diff --git a/src/main/java/com/sqx/modules/apply/controller/ApplyController.java b/src/main/java/com/sqx/modules/apply/controller/ApplyController.java new file mode 100644 index 0000000..932e08a --- /dev/null +++ b/src/main/java/com/sqx/modules/apply/controller/ApplyController.java @@ -0,0 +1,63 @@ +package com.sqx.modules.apply.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.apply.entity.Apply; +import com.sqx.modules.apply.service.ApplyService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "申请", tags = {"申请"}) +@RequestMapping(value = "/apply") +public class ApplyController { + + @Autowired + private ApplyService applyService; + + @PostMapping("/insertApply") + @ApiOperation("发起申请") + public Result insertApply(@RequestBody Apply apply){ + return applyService.insertApply(apply); + } + + @PostMapping("/updateApply") + @ApiOperation("修改申请") + public Result updateApply(@RequestBody Apply apply){ + return applyService.updateApply(apply); + } + + @PostMapping("/deleteApply") + @ApiOperation("删除申请") + public Result deleteApply(Long applyId){ + return applyService.deleteApply(applyId); + } + + @GetMapping("/selectApplyList") + @ApiOperation("查询申请列表") + public Result selectApplyList(Integer page,Integer limit,String applyName,String applyPhone,Integer status,Integer classify){ + return applyService.selectApplyList(page, limit, applyName, applyPhone, status, classify); + } + + @GetMapping("/selectApplyByUserIdAndClassify") + @ApiOperation("查询申请详情") + public Result selectApplyByUserIdAndClassify(Long userId,Integer classify){ + return Result.success().put("data",applyService.selectApplyByUserIdAndClassify(userId, classify)); + } + + @PostMapping("/auditApply") + @ApiOperation("审核申请") + public Result auditApply(String ids,String content,Integer status){ + return applyService.auditApply(ids, status, content); + } + + + + + + + + + +} diff --git a/src/main/java/com/sqx/modules/apply/controller/app/AppApplyController.java b/src/main/java/com/sqx/modules/apply/controller/app/AppApplyController.java new file mode 100644 index 0000000..6ec58ce --- /dev/null +++ b/src/main/java/com/sqx/modules/apply/controller/app/AppApplyController.java @@ -0,0 +1,58 @@ +package com.sqx.modules.apply.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.apply.entity.Apply; +import com.sqx.modules.apply.service.ApplyService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "申请", tags = {"申请"}) +@RequestMapping(value = "/app/apply") +public class AppApplyController { + + @Autowired + private ApplyService applyService; + + @Login + @PostMapping("/insertApply") + @ApiOperation("发起申请") + public Result insertApply(@RequestBody Apply apply,@RequestAttribute Long userId){ + apply.setUserId(userId); + return applyService.insertApply(apply); + } + + @Login + @PostMapping("/updateApply") + @ApiOperation("修改申请") + public Result updateApply(@RequestBody Apply apply){ + return applyService.updateApply(apply); + } + + @Login + @PostMapping("/deleteApply") + @ApiOperation("删除申请") + public Result deleteApply(Long applyId){ + return applyService.deleteApply(applyId); + } + + @GetMapping("/selectApplyList") + @ApiOperation("查询申请列表") + public Result selectApplyList(Integer page,Integer limit,String applyName,String applyPhone,Integer status,Integer classify){ + return applyService.selectApplyList(page, limit, applyName, applyPhone, status, classify); + } + + @Login + @GetMapping("/selectApplyByUserIdAndClassify") + @ApiOperation("查询申请详情") + public Result selectApplyByUserIdAndClassify(@RequestAttribute Long userId,Integer classify){ + return Result.success().put("data",applyService.selectApplyByUserIdAndClassify(userId, classify)); + } + + + + +} diff --git a/src/main/java/com/sqx/modules/apply/dao/ApplyDao.java b/src/main/java/com/sqx/modules/apply/dao/ApplyDao.java new file mode 100644 index 0000000..2b9a984 --- /dev/null +++ b/src/main/java/com/sqx/modules/apply/dao/ApplyDao.java @@ -0,0 +1,16 @@ +package com.sqx.modules.apply.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.apply.entity.Apply; +import org.apache.ibatis.annotations.Mapper; + +/** + * @author fang + * @date 2022/8/3 + */ +@Mapper +public interface ApplyDao extends BaseMapper { + + + +} diff --git a/src/main/java/com/sqx/modules/apply/entity/Apply.java b/src/main/java/com/sqx/modules/apply/entity/Apply.java new file mode 100644 index 0000000..815136c --- /dev/null +++ b/src/main/java/com/sqx/modules/apply/entity/Apply.java @@ -0,0 +1,72 @@ +package com.sqx.modules.apply.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description apply + * @author fang + * @date 2022-08-05 + */ +@Data +public class Apply implements Serializable { + + private static final long serialVersionUID = 1L; + + + /** + * 申请id + */ + @TableId(type = IdType.AUTO) + private Long applyId; + + /** + * 姓名 + */ + private String applyName; + + /** + * 电话 + */ + private String applyPhone; + + /** + * 年龄 + */ + private String applyAge; + + /** + * 内容 + */ + private String applyContent; + + /** + * 分类 1推广员 2代理商 + */ + private Integer classify; + + /** + * 用户id + */ + private Long userId; + + /** + * 状态 1待审核 2通过 3拒绝 + */ + private Integer status; + + /** + * 审核内容 + */ + private String auditContent; + + /** + * 创建时间 + */ + private String createTime; + + public Apply() {} +} diff --git a/src/main/java/com/sqx/modules/apply/service/ApplyService.java b/src/main/java/com/sqx/modules/apply/service/ApplyService.java new file mode 100644 index 0000000..215f01b --- /dev/null +++ b/src/main/java/com/sqx/modules/apply/service/ApplyService.java @@ -0,0 +1,23 @@ +package com.sqx.modules.apply.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.apply.entity.Apply; + +public interface ApplyService extends IService { + + Result insertApply(Apply apply); + + Result updateApply(Apply apply); + + Result deleteApply(Long applyId); + + Result selectApplyList(Integer page,Integer limit,String applyName,String applyPhone,Integer status,Integer classify); + + Apply selectApplyByUserIdAndClassify(Long userId,Integer classify); + + Result auditApply(String ids,Integer status,String content); + + +} diff --git a/src/main/java/com/sqx/modules/apply/service/impl/ApplyServiceImpl.java b/src/main/java/com/sqx/modules/apply/service/impl/ApplyServiceImpl.java new file mode 100644 index 0000000..ae34874 --- /dev/null +++ b/src/main/java/com/sqx/modules/apply/service/impl/ApplyServiceImpl.java @@ -0,0 +1,102 @@ +package com.sqx.modules.apply.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.apply.dao.ApplyDao; +import com.sqx.modules.apply.entity.Apply; +import com.sqx.modules.apply.service.ApplyService; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Date; + +/** + * 申请 + */ +@Service +public class ApplyServiceImpl extends ServiceImpl implements ApplyService { + @Autowired + private UserService userService; + + @Override + public Result insertApply(Apply apply) { + Integer count = baseMapper.selectCount(new QueryWrapper().eq("user_id", apply.getUserId()).eq("classify", apply.getClassify()).ne("status", 3)); + if (count >= 1) { + return Result.error("您已经提交过了!"); + } + Apply one = baseMapper.selectOne(new QueryWrapper().eq("user_id", apply.getUserId()).eq("classify", apply.getClassify())); + apply.setStatus(1); + apply.setCreateTime(DateUtils.format(new Date())); + if (one != null) { + baseMapper.updateById(apply); + } else { + baseMapper.insert(apply); + } + return Result.success(); + } + + @Override + public Result updateApply(Apply apply) { + apply.setStatus(1); + baseMapper.updateById(apply); + return Result.success(); + } + + @Override + public Result deleteApply(Long applyId) { + baseMapper.deleteById(applyId); + return Result.success(); + } + + + @Override + public Result selectApplyList(Integer page, Integer limit, String applyName, String applyPhone, Integer status, Integer classify) { + IPage applyPage = baseMapper.selectPage(new Page<>(page, limit), + new QueryWrapper() + .eq(StringUtils.isNotBlank(applyName), "apply_name", applyName) + .eq(StringUtils.isNotBlank(applyPhone), "apply_phone", applyPhone) + .eq(status != null && status != 0, "status", status) + .eq(classify != null, "classify", classify).orderByDesc("create_time")); + return Result.success().put("data", new PageUtils(applyPage)); + } + + @Override + public Apply selectApplyByUserIdAndClassify(Long userId, Integer classify) { + return baseMapper.selectOne(new QueryWrapper().eq("user_id", userId).eq("classify", classify)); + } + + @Override + public Result auditApply(String ids, Integer status, String content) { + for (String id : ids.split(",")) { + Apply apply = baseMapper.selectById(id); + if (apply.getStatus().equals(1)) { + if (status == 2) { + apply.setStatus(2); + apply.setAuditContent("通过"); + UserEntity userEntity = userService.getById(apply.getUserId()); + if (apply.getClassify() == 1) { + userEntity.setIsPromotion(1); + } else { + userEntity.setIsAgent(1); + } + userService.updateById(userEntity); + } else { + apply.setStatus(3); + apply.setAuditContent(content); + } + baseMapper.updateById(apply); + } + } + return Result.success(); + } + + +} diff --git a/src/main/java/com/sqx/modules/banner/controller/ActivityController.java b/src/main/java/com/sqx/modules/banner/controller/ActivityController.java new file mode 100644 index 0000000..91a7192 --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/controller/ActivityController.java @@ -0,0 +1,97 @@ +package com.sqx.modules.banner.controller; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.banner.entity.Activity; +import com.sqx.modules.banner.service.ActivityService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * @author fang + * @date 2020/7/9 + */ +@Slf4j +@RestController +@Api(value = "菜单和活动管理", tags = {"菜单和活动管理"}) +@RequestMapping(value = "/activity") +public class ActivityController { + + + @Autowired + private ActivityService activityService; + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台详情") + @ResponseBody + public Result getBanner(@PathVariable Long id) { + return Result.success().put("data",activityService.selectActivityById(id)); + } + + @RequestMapping(value = "/state/{state}", method = RequestMethod.GET) + @ApiOperation("根据状态查询菜单列表") + @ResponseBody + public Result getBannerState(@PathVariable String state) { + return Result.success().put("data",activityService.selectByState(state)); + } + + @RequestMapping(value = "/updateActivity", method = RequestMethod.POST) + @ApiOperation("管理平台修改") + @ResponseBody + public Result addBanner(@RequestBody Activity activity) { + activityService.updateActivity(activity); + return Result.success(); + } + + @RequestMapping(value = "/updateActivityStatus", method = RequestMethod.POST) + @ApiOperation("管理平台修改状态") + @ResponseBody + public Result updateActivity(Long id) { + Activity activity = activityService.selectActivityById(id); + if("1".equals(activity.getState())){ + activity.setState("2"); + activityService.updateActivity(activity); + }else{ + activity.setState("1"); + activityService.updateActivity(activity); + } + return Result.success(); + } + + @PostMapping("/insertActivity") + @ApiOperation("添加") + @ResponseBody + public Result insertActivity(@RequestBody Activity activity){ + activityService.insertActivity(activity); + return Result.success(); + } + + @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) + @ApiOperation("管理平台删除") + public Result deleteBanner(@PathVariable Long id) { + activityService.deleteActivity(id); + return Result.success(); + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + @ApiOperation("用户端获取广告位") + @ResponseBody + public Result getBannerList() { + return Result.success().put("data",activityService.selectActivity()); + } + + @RequestMapping(value = "/selectActivity", method = RequestMethod.GET) + @ApiOperation("管理平台获取全部广告位") + @ResponseBody + public Result selectActivity() { + return Result.success().put("data",activityService.selectActivitys()); + } + + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/banner/controller/BannerController.java b/src/main/java/com/sqx/modules/banner/controller/BannerController.java new file mode 100644 index 0000000..a26756f --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/controller/BannerController.java @@ -0,0 +1,86 @@ +package com.sqx.modules.banner.controller; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.banner.entity.Banner; +import com.sqx.modules.banner.service.BannerService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; + +/** + * @author fang + * @date 2020/7/9 + */ +@Slf4j +@RestController +@Api(value = "banner图", tags = {"banner图"}) +@RequestMapping(value = "/banner") +public class BannerController { + + + @Autowired + private BannerService bannerService; + + + @RequestMapping(value = "/selectBannerList", method = RequestMethod.GET) + @ApiOperation("查询所有banner图") + @ResponseBody + public Result selectBannerList(Integer classify){ + return Result.success().put("data",bannerService.selectBannerLists(classify)); + } + + + @RequestMapping(value = "/selectBannerPage", method = RequestMethod.GET) + @ApiOperation("查询所有banner图") + @ResponseBody + public Result selectBannerPage(Integer page,Integer limit,Integer classify,Integer state){ + return Result.success().put("data",bannerService.selectPage(page,limit,classify,state)); + } + + + @RequestMapping(value = "/selectBannerById", method = RequestMethod.GET) + @ApiOperation("根据id查看详细信息") + @ResponseBody + public Result selectBannerById(Long id){ + return Result.success().put("data",bannerService.selectBannerById(id)); + } + + @RequestMapping(value = "/updateBannerStateById", method = RequestMethod.POST) + @ApiOperation("隐藏banner图") + @ResponseBody + public Result updateBannerStateById(Long id){ + return bannerService.updateBannerStateById(id); + } + + @RequestMapping(value = "/updateBannerById", method = RequestMethod.POST) + @ApiOperation("修改banner图") + @ResponseBody + public Result updateBannerById(@RequestBody Banner banner){ + bannerService.updateBannerById(banner); + return Result.success(); + } + + @RequestMapping(value = "/deleteBannerById", method = RequestMethod.GET) + @ApiOperation("删除banner图") + @ResponseBody + public Result deleteBannerById(String ids){ + bannerService.removeByIds(Arrays.asList(ids.split(","))); + return Result.success(); + } + + @RequestMapping(value = "/insertBanner", method = RequestMethod.POST) + @ApiOperation("添加banner图") + @ResponseBody + public Result insertBanner(@RequestBody Banner banner){ + bannerService.insertBanner(banner); + return Result.success(); + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/banner/controller/app/AppBannerController.java b/src/main/java/com/sqx/modules/banner/controller/app/AppBannerController.java new file mode 100644 index 0000000..51edaa0 --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/controller/app/AppBannerController.java @@ -0,0 +1,38 @@ +package com.sqx.modules.banner.controller.app; + + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.banner.service.BannerService; +import com.sqx.modules.taking.response.OrderTakingResponse; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * @author liyuan + * @date 2021/8/9 + */ +@Slf4j +@RestController +@Api(value = "app banner图", tags = {"app banner图"}) +@RequestMapping(value = "/app/banner") +public class AppBannerController { + + + @Autowired + private BannerService bannerService; + + @RequestMapping(value = "/selectBannerList", method = RequestMethod.GET) + @ApiOperation("查询所有banner图") + @ResponseBody + public Result selectBannerList(Integer classify) { + return Result.success().put("data", bannerService.selectBannerList(classify)); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/banner/dao/ActivityDao.java b/src/main/java/com/sqx/modules/banner/dao/ActivityDao.java new file mode 100644 index 0000000..04b26e3 --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/dao/ActivityDao.java @@ -0,0 +1,19 @@ +package com.sqx.modules.banner.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.banner.entity.Activity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @author fang + * @date 2020/7/9 + */ +@Mapper +public interface ActivityDao extends BaseMapper { + + + List selectByState(String state); + +} diff --git a/src/main/java/com/sqx/modules/banner/dao/BannerDao.java b/src/main/java/com/sqx/modules/banner/dao/BannerDao.java new file mode 100644 index 0000000..b3fe689 --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/dao/BannerDao.java @@ -0,0 +1,27 @@ +package com.sqx.modules.banner.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.banner.entity.Banner; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @author fang + * @date 2020/7/9 + */ +@Mapper +public interface BannerDao extends BaseMapper { + + + List selectLists(@Param("classify") Integer classify); + + List selectList(@Param("classify") Integer classify); + + Page selectPage(IPage page, @Param("classify") Integer classify, @Param("state")Integer state); + +} diff --git a/src/main/java/com/sqx/modules/banner/entity/Activity.java b/src/main/java/com/sqx/modules/banner/entity/Activity.java new file mode 100644 index 0000000..c1facbd --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/entity/Activity.java @@ -0,0 +1,29 @@ +package com.sqx.modules.banner.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * 活动推广 + */ +@Data +@TableName("activity") +public class Activity implements Serializable { + @TableId(type = IdType.INPUT) + private Long id; + + private String createAt; + + private String imageUrl; + + private String url; + + private String title; + + private String state; + +} diff --git a/src/main/java/com/sqx/modules/banner/entity/Banner.java b/src/main/java/com/sqx/modules/banner/entity/Banner.java new file mode 100644 index 0000000..93b2623 --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/entity/Banner.java @@ -0,0 +1,67 @@ +package com.sqx.modules.banner.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.io.Serializable; +/** + * @author fang + * @date 2020/7/9 + */ +@Data +@TableName("banner") +@AllArgsConstructor +@NoArgsConstructor +public class Banner implements Serializable { + + private static final long serialVersionUID = 1L; + /** + * banner图id + */ + @TableId(type = IdType.INPUT) + private Long id; + + /** + * 创建时间 + */ + private String createTime; + + /** + * 名称 + */ + private String name; + + /** + * 图片地址 + */ + private String imageUrl; + + /** + * 状态 1正常 2隐藏 + */ + private Integer state; + + /** + * 分类 1 banner图 2 首页分类 + */ + private Integer classify; + + /** + * 跳转地址 + */ + private String url; + + /** + * 顺序 + */ + private Integer sort; + + /** + * 描述 + */ + private String describes; + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/banner/service/ActivityService.java b/src/main/java/com/sqx/modules/banner/service/ActivityService.java new file mode 100644 index 0000000..af91c58 --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/service/ActivityService.java @@ -0,0 +1,27 @@ +package com.sqx.modules.banner.service; + + +import com.sqx.modules.banner.entity.Activity; + +import java.util.List; + +public interface ActivityService { + + + List selectByState(String state); + + Activity selectActivityById(Long id); + + int insertActivity(Activity info); + + int updateActivity(Activity info); + + int deleteActivity(Long id); + + List selectActivity(); + + List selectActivitys(); + + + +} diff --git a/src/main/java/com/sqx/modules/banner/service/BannerService.java b/src/main/java/com/sqx/modules/banner/service/BannerService.java new file mode 100644 index 0000000..1948bec --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/service/BannerService.java @@ -0,0 +1,30 @@ +package com.sqx.modules.banner.service; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.banner.entity.Banner; +import com.sqx.modules.taking.response.OrderTakingResponse; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +public interface BannerService extends IService { + + List selectBannerList(Integer classify); + + List selectBannerLists(Integer classify); + + int saveBody(String image, String url, Integer sort); + + Banner selectBannerById(Long id); + + Result updateBannerStateById(Long id); + + int updateBannerById(Banner banner); + + int insertBanner(Banner banner); + + PageUtils selectPage(Integer page, Integer limit, Integer classify, Integer state); + +} diff --git a/src/main/java/com/sqx/modules/banner/service/impl/ActivityServiceImpl.java b/src/main/java/com/sqx/modules/banner/service/impl/ActivityServiceImpl.java new file mode 100644 index 0000000..ec7be7b --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/service/impl/ActivityServiceImpl.java @@ -0,0 +1,65 @@ +package com.sqx.modules.banner.service.impl; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.banner.dao.ActivityDao; +import com.sqx.modules.banner.entity.Activity; +import com.sqx.modules.banner.service.ActivityService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * 活动推广 + */ +@Service +public class ActivityServiceImpl extends ServiceImpl implements ActivityService { + + + @Autowired + private ActivityDao activityDao; + + @Override + public List selectByState(String state) { + return activityDao.selectByState(state); + } + + @Override + public Activity selectActivityById(Long id) { + return activityDao.selectById(id); + } + + @Override + public int insertActivity(Activity activity) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + activity.setCreateAt(sdf.format(now)); + return activityDao.insert(activity); + } + + @Override + public int updateActivity(Activity activity) { + return activityDao.updateById(activity); + } + + @Override + public int deleteActivity(Long id) { + return activityDao.deleteById(id); + } + + @Override + public List selectActivity() { + return activityDao.selectList(new QueryWrapper().eq("state", 1)); + } + + @Override + public List selectActivitys() { + return activityDao.selectList(null); + } + + +} diff --git a/src/main/java/com/sqx/modules/banner/service/impl/BannerServiceImpl.java b/src/main/java/com/sqx/modules/banner/service/impl/BannerServiceImpl.java new file mode 100644 index 0000000..e9e7c8f --- /dev/null +++ b/src/main/java/com/sqx/modules/banner/service/impl/BannerServiceImpl.java @@ -0,0 +1,100 @@ +package com.sqx.modules.banner.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.banner.dao.BannerDao; +import com.sqx.modules.banner.entity.Banner; +import com.sqx.modules.banner.service.BannerService; +import com.sqx.modules.taking.response.OrderTakingResponse; +import com.sqx.modules.taking.service.OrderTakingService; +import io.swagger.annotations.ApiParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * banner图 + */ +@Service +public class BannerServiceImpl extends ServiceImpl implements BannerService { + + @Autowired + private BannerDao bannerDao; + @Autowired + private OrderTakingService orderTakingService; + + + @Override + public List selectBannerList(Integer classify) { + return bannerDao.selectList(classify); + } + + @Override + public List selectBannerLists(Integer classify) { + return bannerDao.selectLists(classify); + } + + @Override + public PageUtils selectPage(Integer page, Integer limit, Integer classify, Integer state){ + IPage pages=new Page<>(page,limit); + return new PageUtils(bannerDao.selectPage(pages,classify,state)); + } + + + @Override + public int saveBody(String image, String url, Integer sort) { + Banner banner = new Banner(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + banner.setImageUrl(image); + banner.setCreateTime(sdf.format(now)); + banner.setState(1); + banner.setUrl(url); + banner.setSort(sort == null ? 1 : sort); + return bannerDao.insert(banner); + } + + @Override + public int insertBanner(Banner banner) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + banner.setCreateTime(sdf.format(now)); + banner.setState(2); + return bannerDao.insert(banner); + } + + + @Override + public Banner selectBannerById(Long id) { + return bannerDao.selectById(id); + } + + @Override + public Result updateBannerStateById(Long id) { + Banner banner = selectBannerById(id); + if (banner != null) { + if (banner.getState() == 1) { + banner.setState(2); + } else { + banner.setState(1); + } + bannerDao.updateById(banner); + return Result.success(); + } else { + return Result.error("修改对象为空!"); + } + } + + @Override + public int updateBannerById(Banner banner) { + return bannerDao.updateById(banner); + } + + +} diff --git a/src/main/java/com/sqx/modules/chat/controller/ChatController.java b/src/main/java/com/sqx/modules/chat/controller/ChatController.java new file mode 100644 index 0000000..cc7d02e --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/controller/ChatController.java @@ -0,0 +1,50 @@ +package com.sqx.modules.chat.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.chat.service.ChatContentService; +import com.sqx.modules.chat.service.ChatConversationService; +import com.sqx.modules.chats.service.ChatsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Api(value = "聊天", tags = {"聊天"}) +@RequestMapping(value = "/chat") +public class ChatController { + + @Autowired + private ChatContentService chatContentService; + @Autowired + private ChatConversationService chatConversationService; + + @GetMapping("/selectChatConversationPage") + @ApiOperation("获取聊天会话") + public Result selectChatConversationPage(Integer page, Integer limit, Long userId, String nickName){ + return Result.success().put("data",chatConversationService.selectChatConversationPage(page, limit, userId,nickName)); + } + + + @GetMapping("/selectChatContent") + @ApiOperation("获取聊天记录") + public Result selectChatContent(Integer page,Integer limit,Long chatConversationId,String content){ + return Result.success().put("data",chatContentService.selectChatContentPage(page, limit, chatConversationId,content)); + } + + + @PostMapping("/deleteChatContentById") + @ApiOperation("删除某一句聊天记录") + public Result deleteChatContentById(Long chatContentId){ + chatContentService.removeById(chatContentId); + return Result.success(); + } + + + + + +} diff --git a/src/main/java/com/sqx/modules/chat/controller/Timer.java b/src/main/java/com/sqx/modules/chat/controller/Timer.java new file mode 100644 index 0000000..badf08d --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/controller/Timer.java @@ -0,0 +1,101 @@ +package com.sqx.modules.chat.controller; + +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.chat.dao.ChatContentDao; +import com.sqx.modules.chat.dao.ChatConversationDao; +import com.sqx.modules.chat.entity.ChatConversation; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.utils.SenInfoCheckUtil; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Component +public class Timer { + + @Autowired + private UserService userService; + @Autowired + private ChatContentDao chatContentDao; + @Autowired + private ChatConversationDao chatConversationDao; + @Autowired + private CommonInfoService commonInfoService; + + +// @Scheduled(cron="0 */1 * * * ?") +// public void sendMsg(){ +// //获取超过一分钟未读的消息 进行小程序推送 +// List> maps = chatContentDao.selectChatContentCountByWx(1,0); +// String value = commonInfoService.findOne(249).getValue(); +// for(Map map:maps){ +// String chatConversationId = String.valueOf(map.get("chatConversationId")); +// String userId = String.valueOf(map.get("userId")); +// String ccUserId = String.valueOf(map.get("ccUserId")); +// String ccFocusedUserId = String.valueOf(map.get("ccFocusedUserId")); +// String counts = String.valueOf(map.get("counts")); +// if(userId.equals(ccUserId)){ +// userId=ccFocusedUserId; +// }else{ +// userId=ccUserId; +// } +// if(StringUtils.isNotEmpty(userId) && !"null".equals(userId)){ +// UserEntity userEntity = userService.selectUserById(Long.parseLong(userId)); +// if(userEntity!=null && (userEntity.getIsSendMsg()==null || userEntity.getIsSendMsg()==1)){ +// if(StringUtils.isNotEmpty(chatConversationId) && !"null".equals(chatConversationId)){ +// ChatConversation chatConversation = chatConversationDao.selectById(Long.parseLong(chatConversationId)); +// if(chatConversation!=null){ +// chatConversation.setIsWxMsg(Integer.parseInt(userId)); +// chatConversationDao.updateById(chatConversation); +// } +// } +// /*List msgList=new ArrayList<>(); +// msgList.add("未读消息通知"); +// msgList.add("您有"+counts+"条未读消息,赶快上线查看吧!"); +// if(StringUtils.isNotEmpty(userEntity.getOpenId())){ +// SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),value,null,msgList,3); +// }else{ +// SenInfoCheckUtil.sendShopMsg(userEntity.getShopOpenId(),value,null,msgList,3); +// }*/ +// } +// } +// } +// String msg = commonInfoService.findOne(250).getValue(); +// String count = commonInfoService.findOne(251).getValue(); +// List> mapList = chatContentDao.selectChatContentCountByDx(Integer.parseInt(msg),Integer.parseInt(count)); +// for(Map map:mapList){ +// String chatConversationId = String.valueOf(map.get("chatConversationId")); +// String userId = String.valueOf(map.get("userId")); +// String ccUserId = String.valueOf(map.get("ccUserId")); +// String ccFocusedUserId = String.valueOf(map.get("ccFocusedUserId")); +// String counts = String.valueOf(map.get("counts")); +// if(userId.equals(ccUserId)){ +// userId=ccFocusedUserId; +// }else{ +// userId=ccUserId; +// } +// if(StringUtils.isNotEmpty(userId) && !"null".equals(userId)){ +// UserEntity userEntity = userService.selectUserById(Long.parseLong(userId)); +// if(userEntity!=null && (userEntity.getIsSendMsg()==null || userEntity.getIsSendMsg()==1)){ +// if(StringUtils.isNotEmpty(chatConversationId) && !"null".equals(chatConversationId)){ +// ChatConversation chatConversation = chatConversationDao.selectById(Long.parseLong(chatConversationId)); +// if(chatConversation!=null){ +// chatConversation.setIsSendMsg(Integer.parseInt(userId)); +// chatConversationDao.updateById(chatConversation); +// } +// } +// userService.sendMsg(userEntity.getPhone(),"dx",Integer.parseInt(counts)); +// } +// } +// } +// } + + + +} diff --git a/src/main/java/com/sqx/modules/chat/controller/app/AppChatController.java b/src/main/java/com/sqx/modules/chat/controller/app/AppChatController.java new file mode 100644 index 0000000..854ad4e --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/controller/app/AppChatController.java @@ -0,0 +1,65 @@ +package com.sqx.modules.chat.controller.app; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.chat.entity.ChatConversation; +import com.sqx.modules.chat.service.ChatContentService; +import com.sqx.modules.chat.service.ChatConversationService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@Api(value = "聊天", tags = {"聊天"}) +@RequestMapping(value = "/app/chat") +public class AppChatController { + + @Autowired + private ChatContentService chatContentService; + @Autowired + private ChatConversationService chatConversationService; + @Autowired + private MessageService messageService; + + @Login + @GetMapping("/selectChatConversationPage") + @ApiOperation("获取聊天会话") + public Result selectChatConversationPage(Integer page,Integer limit,@RequestAttribute("userId") Long userId){ + return Result.success().put("data",chatConversationService.selectChatConversationPage(page, limit, userId,null)); + } + + @Login + @PostMapping("/insertChatConversation") + @ApiOperation("发起聊天") + public Result insertChatConversation(@RequestBody ChatConversation chatConversation){ + return chatConversationService.insertChatConversations(chatConversation); + } + + @Login + @GetMapping("/selectChatContent") + @ApiOperation("获取聊天记录") + public Result selectChatContent(Integer page,Integer limit,Long chatConversationId,@RequestAttribute("userId") Long userId){ + //清空未读消息 + chatContentService.updateChatContentStatusByUserIdAndChatId(userId, chatConversationId); + return Result.success().put("data",chatContentService.selectChatContentPage(page, limit, chatConversationId,null)); + } + + @Login + @GetMapping("/selectChatCount") + @ApiOperation("获取未读消息数量") + public Result selectChatCount(@RequestAttribute("userId") Long userId){ + int chatCount = chatContentService.selectChatCount(userId); + int messageCount = messageService.count(new QueryWrapper().eq("is_see", 0).eq("user_id", userId)); + Map result=new HashMap<>(); + result.put("chatCount",chatCount); + result.put("messageCount",messageCount); + return Result.success().put("data",result); + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chat/controller/app/AppChatSocket.java b/src/main/java/com/sqx/modules/chat/controller/app/AppChatSocket.java new file mode 100644 index 0000000..9e62ec0 --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/controller/app/AppChatSocket.java @@ -0,0 +1,181 @@ +package com.sqx.modules.chat.controller.app; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.chat.entity.ChatContent; +import com.sqx.modules.chat.service.ChatContentService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.websocket.*; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Slf4j +@Component +@ServerEndpoint("/chatSocket/{userId}") +public class AppChatSocket {//用户聊天 + + /** + * 在线人数 + */ + public static int onlineNumber = 0; + /** + * 以用户的id为key,WebSocket为对象保存起来 + */ + private static Map clients = new ConcurrentHashMap(); + private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + /** + * 会话 + */ + private Session session; + /** + * 用户id + */ + private String userId; + + // 这里使用静态,让 service 属于类 + private static ChatContentService chatContentService; + private static UserService userService; + + // 注入的时候,给类的 service 注入 + @Autowired + public void setWxChatContentService(ChatContentService chatContentService,UserService userService) { + AppChatSocket.chatContentService = chatContentService; + AppChatSocket.userService = userService; + } + + + + /** + * 建立连接 + * + * @param session + */ + @OnOpen + public void onOpen(@PathParam("userId") String userId, Session session) + { + onlineNumber++; + log.error("现在来连接的客户id:"+userId); + this.userId = userId; + this.session = session; + log.error("有新连接加入! 当前在线人数" + onlineNumber); + try { + //把自己的信息加入到map当中去 + AppChatSocket appChatSocket = clients.get(userId); + if(appChatSocket!=null){ + clients.remove(userId); + } + clients.put(userId, this); + + /*sendMessageTo("恭喜你连接成功!",wxUserId);*/ + } + catch (Exception e){ + log.error(userId+"上线的时候通知所有人发生了错误"); + } + + } + + @OnError + public void onError(Session session, Throwable error) { + log.error("服务端发生了错误"+error.getMessage()); + //error.printStackTrace(); + } + /** + * 连接关闭 + */ + @OnClose + public void onClose() + { + onlineNumber--; + //webSockets.remove(this); + clients.remove(userId); + log.error("有连接关闭! 当前在线人数" + onlineNumber); + } + + /** + * 收到客户端的消息 + * + * @param message 消息 + * @param session 会话 + */ + @OnMessage + public void onMessage(String message, Session session) + { + try { + JSONObject jsonObject = JSON.parseObject(message); + String textMessage = jsonObject.getString("content"); + String messageType = jsonObject.getString("messageType"); + String width = jsonObject.getString("width"); + String height = jsonObject.getString("height"); + String userId = jsonObject.getString("userId"); + String chatConversationId = jsonObject.getString("chatConversationId"); + chatContentService.updateChatContentStatusByUserIdAndChatId(Long.parseLong(this.userId), Long.parseLong(chatConversationId)); + //将聊天记录保存包数据库中 + ChatContent wxChatContent=new ChatContent(); + wxChatContent.setChatConversationId(Long.parseLong(chatConversationId)); + wxChatContent.setUserId(Long.parseLong(this.userId)); + wxChatContent.setWidth(width); + wxChatContent.setHeight(height); + wxChatContent.setContent(textMessage); + wxChatContent.setMessageType(messageType); + wxChatContent.setCreateTime(sdf.format(new Date())); + //判断对方是否在线 + AppChatSocket chatSocket = clients.get(userId); + if (chatSocket!=null) { + chatSocket.session.getAsyncRemote().sendText(message); + } + wxChatContent.setStatus(0); + chatContentService.save(wxChatContent); + UserEntity userEntity = userService.selectUserById(Long.parseLong(userId)); + if(userEntity!=null && StringUtils.isNotBlank(userEntity.getClientid())){ + UserEntity user = userService.selectUserById(Long.parseLong(this.userId)); + if("2".equals(messageType)){ + textMessage="[图片]"; + }else if("3".equals(messageType)){ + textMessage="[语音]"; + } + userService.pushToSingle("新消息提醒",user.getUserName()+":"+textMessage,userEntity.getClientid()); + } + /*AppChatSocket chatSocket = clients.get(userId); + if (chatSocket!=null) { + chatSocket.session.getAsyncRemote().sendText(message); + }*/ + } + catch (Exception e){ + log.error("发生了错误了"+e.getMessage(),e); + } + + } + + + public void sendMessageTo(String message, String ToUserName) throws IOException { + for (AppChatSocket item : clients.values()) { + if (item.userId.equals(ToUserName) ) { + item.session.getAsyncRemote().sendText(message); + System.err.println(this.userId+"发送成功:"+ToUserName); + break; + } + } + } + + public void sendMessageAll(String message,String FromUserName) throws IOException { + for (AppChatSocket item : clients.values()) { + item.session.getAsyncRemote().sendText(message); + } + } + + public static synchronized int getOnlineCount() { + return onlineNumber; + } + +} diff --git a/src/main/java/com/sqx/modules/chat/dao/ChatContentDao.java b/src/main/java/com/sqx/modules/chat/dao/ChatContentDao.java new file mode 100644 index 0000000..01d9a7b --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/dao/ChatContentDao.java @@ -0,0 +1,29 @@ +package com.sqx.modules.chat.dao; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.chat.entity.ChatContent; +import com.sqx.modules.common.entity.CommonInfo; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + + +@Mapper +public interface ChatContentDao extends BaseMapper { + + IPage> selectChatContentPage(Page> page,@Param("chatConversationId") Long chatConversationId,@Param("content") String content); + + int updateChatContentStatusByUserIdAndChatId(@Param("userId") Long userId,@Param("chatConversationId") Long chatConversationId); + + int selectChatCount(@Param("userId") Long userId); + + List> selectChatContentCountByWx(@Param("minute") Integer minute,@Param("counts") Integer counts); + + List> selectChatContentCountByDx(@Param("minute") Integer minute,@Param("counts") Integer counts); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chat/dao/ChatConversationDao.java b/src/main/java/com/sqx/modules/chat/dao/ChatConversationDao.java new file mode 100644 index 0000000..c2113e4 --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/dao/ChatConversationDao.java @@ -0,0 +1,22 @@ +package com.sqx.modules.chat.dao; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.chat.entity.ChatContent; +import com.sqx.modules.chat.entity.ChatConversation; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.Map; + + +@Mapper +public interface ChatConversationDao extends BaseMapper { + + IPage> selectChatConversationPage(Page> page,@Param("userId") Long userId,@Param("nickName") String nickName); + + int insertChatConversation(ChatConversation chatConversation); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chat/entity/ChatContent.java b/src/main/java/com/sqx/modules/chat/entity/ChatContent.java new file mode 100644 index 0000000..3db86fe --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/entity/ChatContent.java @@ -0,0 +1,52 @@ +package com.sqx.modules.chat.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; + +import lombok.Data; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import java.util.Date; + +/** + * 聊天内容对象 chat_content + * + * @author fang + * @date 2020-03-17 + */ +@Data +@TableName("chat_content") +public class ChatContent { + private static final long serialVersionUID = 1L; + + /** 聊天内容id */ + @TableId(type = IdType.INPUT) + private Long chatContentId; + + /** 聊天会话id */ + private Long chatConversationId; + + /** 聊天内容 */ + private String content; + + /** 聊天类型 */ + private String messageType; + + /** 宽度 */ + private String width; + + /** 高度 */ + private String height; + + /** 发送人 */ + private Long userId; + + /** 状态(0未读 1已读) */ + private Integer status; + /** + * 创建时间 + */ + private String createTime; + +} diff --git a/src/main/java/com/sqx/modules/chat/entity/ChatConversation.java b/src/main/java/com/sqx/modules/chat/entity/ChatConversation.java new file mode 100644 index 0000000..69cdfeb --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/entity/ChatConversation.java @@ -0,0 +1,50 @@ +package com.sqx.modules.chat.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + + +/** + * 聊天会话对象 chat_conversation + * + * @author fang + * @date 2020-03-17 + */ +@Data +@TableName("chat_conversation") +public class ChatConversation { + private static final long serialVersionUID = 1L; + + /** 聊天会话id */ + @TableId(type = IdType.INPUT) + private Long chatConversationId; + + /** 发起人id */ + private Long userId; + + /** 接收人id */ + private Long focusedUserId; + + /** 状态 */ + private Long status; + + /** + * 创建时间 + */ + private String createTime; + + /** + * 修改时间 + */ + private String updateTime; + + /** 备注 */ + private String remark; + + private Integer isSendMsg; + + private Integer isWxMsg; + +} diff --git a/src/main/java/com/sqx/modules/chat/service/ChatContentService.java b/src/main/java/com/sqx/modules/chat/service/ChatContentService.java new file mode 100644 index 0000000..6420b35 --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/service/ChatContentService.java @@ -0,0 +1,17 @@ +package com.sqx.modules.chat.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.chat.entity.ChatContent; +import org.apache.ibatis.annotations.Param; + +public interface ChatContentService extends IService { + + PageUtils selectChatContentPage(Integer page, Integer limit, Long chatConversationId,String content); + + int updateChatContentStatusByUserIdAndChatId(Long userId,Long chatConversationId); + + int selectChatCount(Long userId); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chat/service/ChatConversationService.java b/src/main/java/com/sqx/modules/chat/service/ChatConversationService.java new file mode 100644 index 0000000..55fce8a --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/service/ChatConversationService.java @@ -0,0 +1,20 @@ +package com.sqx.modules.chat.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.chat.entity.ChatContent; +import com.sqx.modules.chat.entity.ChatConversation; + + +public interface ChatConversationService extends IService { + + PageUtils selectChatConversationPage(Integer page, Integer limit, Long userId,String nickName); + + int insertChatConversation(ChatConversation chatConversation); + + ChatConversation selectChatConversation(Long userId,Long focusedUserId); + + Result insertChatConversations(ChatConversation chatConversation); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chat/service/impl/ChatContentServiceImpl.java b/src/main/java/com/sqx/modules/chat/service/impl/ChatContentServiceImpl.java new file mode 100644 index 0000000..17763d4 --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/service/impl/ChatContentServiceImpl.java @@ -0,0 +1,39 @@ +package com.sqx.modules.chat.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.chat.dao.ChatContentDao; +import com.sqx.modules.chat.entity.ChatContent; +import com.sqx.modules.chat.service.ChatContentService; +import com.sqx.modules.common.dao.CommonInfoDao; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; + + +@Service +public class ChatContentServiceImpl extends ServiceImpl implements ChatContentService { + + + @Override + public PageUtils selectChatContentPage(Integer page, Integer limit, Long chatConversationId,String content) { + return new PageUtils(baseMapper.selectChatContentPage(new Page<>(page,limit),chatConversationId,content)); + } + + @Override + public int updateChatContentStatusByUserIdAndChatId(Long userId,Long chatConversationId){ + return baseMapper.updateChatContentStatusByUserIdAndChatId(userId, chatConversationId); + } + + @Override + public int selectChatCount(Long userId) { + return baseMapper.selectChatCount(userId); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chat/service/impl/ChatConversationServiceImpl.java b/src/main/java/com/sqx/modules/chat/service/impl/ChatConversationServiceImpl.java new file mode 100644 index 0000000..9a13c22 --- /dev/null +++ b/src/main/java/com/sqx/modules/chat/service/impl/ChatConversationServiceImpl.java @@ -0,0 +1,75 @@ +package com.sqx.modules.chat.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.chat.dao.ChatContentDao; +import com.sqx.modules.chat.dao.ChatConversationDao; +import com.sqx.modules.chat.entity.ChatContent; +import com.sqx.modules.chat.entity.ChatConversation; +import com.sqx.modules.chat.service.ChatContentService; +import com.sqx.modules.chat.service.ChatConversationService; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.RequestBody; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.locks.ReentrantReadWriteLock; + + +@Service +public class ChatConversationServiceImpl extends ServiceImpl implements ChatConversationService { + + private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(); + + + + @Override + public PageUtils selectChatConversationPage(Integer page, Integer limit, Long userId,String nickName){ + return new PageUtils(baseMapper.selectChatConversationPage(new Page<>(page,limit),userId,nickName)); + } + + + @Override + public int insertChatConversation(ChatConversation chatConversation) { + return baseMapper.insertChatConversation(chatConversation); + } + + @Override + public ChatConversation selectChatConversation(Long userId,Long focusedUserId){ + ChatConversation chatConversation = baseMapper.selectOne(new QueryWrapper().eq("user_id", userId).eq("focused_user_id", focusedUserId)); + if(chatConversation!=null){ + return chatConversation; + } + return baseMapper.selectOne(new QueryWrapper().eq("focused_user_id", userId).eq("user_id", focusedUserId)); + } + + + @Override + public Result insertChatConversations(ChatConversation chatConversation){ + reentrantReadWriteLock.writeLock().lock(); + try{ + ChatConversation chatConversation1 = selectChatConversation(chatConversation.getUserId(), chatConversation.getFocusedUserId()); + if(chatConversation1==null){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String format = sdf.format(new Date()); + chatConversation.setCreateTime(format); + chatConversation.setUpdateTime(format); + baseMapper.insertChatConversation(chatConversation); + return Result.success().put("data",chatConversation); + } + return Result.success().put("data",chatConversation1); + }catch (Exception e){ + e.printStackTrace(); + log.error("发起聊天出错"+e.getMessage(),e); + }finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试"); + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chats/controller/ChatsContentController.java b/src/main/java/com/sqx/modules/chats/controller/ChatsContentController.java new file mode 100644 index 0000000..a4e9317 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/controller/ChatsContentController.java @@ -0,0 +1,55 @@ +package com.sqx.modules.chats.controller; + +import com.sqx.modules.chats.entity.ChatsContent; +import com.sqx.modules.chats.service.ChatsContentService; +import com.sqx.modules.chats.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="聊天会话内容",tags={"聊天会话内容"}) +@RequestMapping(value = "/chatsContent") +public class ChatsContentController { + @Autowired + private ChatsContentService service; + + + @GetMapping("/list") + @ApiOperation("用户端聊天内容列表") + public Result findAll(Long chatId) { + return service.findAll(chatId); + } + + @GetMapping("/storeList") + @ApiOperation("商户端聊天内容列表") + public Result storeList(Long chatId) { + return service.storeList(chatId); + } + + + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + @PostMapping("/save") + @ApiOperation("发送消息") + public Result saveBody(@RequestBody ChatsContent entity) { + return service.saveBody(entity); + } + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody ChatsContent entity) { + return service.updateBody(entity); + } + + @GetMapping("/delete") + @ApiOperation("删除聊天会话内容") + public Result delete(String ids) { + return service.delete(ids); + } + +} diff --git a/src/main/java/com/sqx/modules/chats/controller/ChatsController.java b/src/main/java/com/sqx/modules/chats/controller/ChatsController.java new file mode 100644 index 0000000..2336437 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/controller/ChatsController.java @@ -0,0 +1,69 @@ +package com.sqx.modules.chats.controller; + + +import com.sqx.modules.chats.entity.Chats; +import com.sqx.modules.chats.service.ChatsService; +import com.sqx.modules.chats.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="聊天会话",tags={"聊天会话"}) +@RequestMapping(value = "/chats") +public class ChatsController { + @Autowired + private ChatsService service; + + @GetMapping("/count") + @ApiOperation("商家端未读消息") + public Result count(@ApiParam("店铺id(总后台商户传0)") @RequestParam Long storeId) { + return service.count(storeId); + } + + @GetMapping("/userCount") + @ApiOperation("用户端未读消息") + public Result userCount(@ApiParam("店铺id(总后台商户传0)") @RequestParam Long userId) { + return service.userCount(userId); + } + + @GetMapping("/list") + @ApiOperation("商家端会话列表") + public Result findAll(@ApiParam("店铺id(总后台商户传0)") @RequestParam Long storeId, + @ApiParam("用户昵称") @RequestParam(required = false) String userName) { + return service.findAll(storeId, userName); + } + + @GetMapping("/userList") + @ApiOperation("用户端会话列表") + public Result userList(Long userId) { + return service.userList(userId); + } + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + @PostMapping("/save") + @ApiOperation("用户端发起聊天") + public Result saveBody(@RequestBody Chats entity) { + return service.saveBody(entity); + } + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody Chats entity) { + return service.updateBody(entity); + } + + @GetMapping("/delete") + @ApiOperation("删除聊天会话") + public Result delete(Long id) { + return service.delete(id); + } + +} diff --git a/src/main/java/com/sqx/modules/chats/controller/WebSocket.java b/src/main/java/com/sqx/modules/chats/controller/WebSocket.java new file mode 100644 index 0000000..e3a3b8a --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/controller/WebSocket.java @@ -0,0 +1,164 @@ +package com.sqx.modules.chats.controller; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.sqx.modules.chats.entity.ChatsContent; +import com.sqx.modules.chats.service.ChatsContentService; +import com.sqx.modules.chats.utils.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.websocket.*; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * WebSocket聊天实现 + */ +@Component +@ServerEndpoint("/websocket/{wxUserId}") +public class WebSocket { + private Logger logger = LoggerFactory.getLogger(this.getClass()); + + //通过类似GET请求方式传递参数的方法(服务端采用第二种方法"WebSocketHandler"实现) + //websocket = new WebSocket("ws://127.0.0.1:18080/testWebsocket?id=23&name=Lebron"); + /** + * 在线人数 + */ + public static int onlineNumber = 0; + /** + * 以用户的id为key,WebSocket为对象保存起来 + */ + private static Map clients = new ConcurrentHashMap(); + /** + * 会话 + */ + private Session session; + /** + * 用户id + */ + private String wxUserId; + + //这里使用静态,让 service 属于类 + private static ChatsContentService chatContentService; + + //注入的时候,给类的 service 注入 + @Autowired + public void setWxChatContentService(ChatsContentService chatContentService) { + WebSocket.chatContentService = chatContentService; + } + + + /** + * 建立连接 + * + * @param session + */ + @OnOpen + public void onOpen(@PathParam("wxUserId") String wxUserId, Session session) { + onlineNumber++; + logger.info("现在来连接的客户id:" + wxUserId); + this.wxUserId = wxUserId; + this.session = session; + logger.info("有新连接加入! 当前在线人数" + onlineNumber); + try { + //把自己的信息加入到map当中去 + clients.remove(wxUserId); + clients.put(wxUserId, this); + /*sendMessageTo("恭喜你连接成功!",wxUserId);*/ + } catch (Exception e) { + logger.info(wxUserId + "上线的时候通知所有人发生了错误"); + } + } + + @OnError + public void onError(Session session, Throwable error) { + logger.info("服务端发生了错误" + error.getMessage()); + } + + /** + * 连接关闭 + */ + @OnClose + public void onClose() { + onlineNumber--; + //webSockets.remove(this); + clients.remove(wxUserId); + logger.info("有连接关闭! 当前在线人数" + onlineNumber); + } + + /** + * 接收客户端的消息,并把消息发送给所有连接的会话 + */ + @OnMessage + public void onMessage(String message) { + try { + //解析聊天内容 + JSONObject jsonObject = JSON.parseObject(message); + String type = jsonObject.getString("type"); + String content = jsonObject.getString("content"); + String sendType = jsonObject.getString("sendType"); + String userId = jsonObject.getString("userId"); + String storeId = jsonObject.getString("storeId"); + Long chatId = Long.valueOf(jsonObject.getString("chatId")); //会话id + if ("1".equals(sendType)) { + logger.info("用户发送消息:" + message); + } else { + logger.info("客服发送消息:" + message); + } + //聊天记录 + ChatsContent wxChatContent = new ChatsContent(); + wxChatContent.setContent(content); + wxChatContent.setType(Integer.valueOf(type)); + wxChatContent.setSendType(Integer.valueOf(sendType)); + wxChatContent.setUserId(Long.valueOf(userId)); + wxChatContent.setStoreId(Long.valueOf(storeId)); + wxChatContent.setChatId(chatId); + wxChatContent.setCreateTime(DateUtil.createTime()); //创建时间 + wxChatContent.setStatus(1); //未读 + //判断对方是否在线,消息设为已读 + for (WebSocket item : clients.values()) { + if ("1".equals(sendType)) { //用户发送 + if (item.wxUserId.equals(storeId)) { + wxChatContent.setStatus(2); //已读 + item.session.getAsyncRemote().sendText(message); + } + }else { + if (item.wxUserId.equals(userId)) { + wxChatContent.setStatus(2); //已读 + item.session.getAsyncRemote().sendText(message); + } + } + } + //保存消息内容 + chatContentService.saveBody(wxChatContent); + } catch (Exception e) { + logger.info("发生了错误了"); + } + } + + public void sendMessageTo(String message, String wxUserId) throws IOException { + for (WebSocket item : clients.values()) { + if (item.wxUserId.equals(wxUserId)) { + item.session.getAsyncRemote().sendText(message); + break; + } + } + } + + public void sendMessageAll(String message, String FromUserName) throws IOException { + for (WebSocket item : clients.values()) { + item.session.getAsyncRemote().sendText(message); + } + } + + public static synchronized int getOnlineCount() { + return onlineNumber; + } + +} diff --git a/src/main/java/com/sqx/modules/chats/controller/WebSocketStompConfig.java b/src/main/java/com/sqx/modules/chats/controller/WebSocketStompConfig.java new file mode 100644 index 0000000..6ecd8f3 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/controller/WebSocketStompConfig.java @@ -0,0 +1,18 @@ +package com.sqx.modules.chats.controller; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.server.standard.ServerEndpointExporter; + +/** + * websocket的配置 + */ +@Configuration +public class WebSocketStompConfig{ + //这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint + @Bean + public ServerEndpointExporter serverEndpointExporter() + { + return new ServerEndpointExporter(); + } +} diff --git a/src/main/java/com/sqx/modules/chats/controller/app/AppChatsController.java b/src/main/java/com/sqx/modules/chats/controller/app/AppChatsController.java new file mode 100644 index 0000000..d26a74d --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/controller/app/AppChatsController.java @@ -0,0 +1,50 @@ +package com.sqx.modules.chats.controller.app; + + +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.chats.entity.Chats; +import com.sqx.modules.chats.service.ChatsContentService; +import com.sqx.modules.chats.service.ChatsService; +import com.sqx.modules.chats.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="聊天会话",tags={"聊天会话"}) +@RequestMapping(value = "/app/chats") +public class AppChatsController { + + @Autowired + private ChatsService service; + @Autowired + private ChatsContentService chatsContentService; + + @PostMapping("/save") + @ApiOperation("用户端发起聊天") + public Result saveBody(@RequestBody Chats entity) { + return service.saveBody(entity); + } + + @GetMapping("/list") + @ApiOperation("用户端聊天内容列表") + public Result findAll(Long chatId) { + return chatsContentService.findAll(chatId); + } + + @GetMapping("/count") + @ApiOperation("商家端未读消息") + public Result count(@ApiParam("店铺id(总后台商户传0)") @RequestParam Long storeId) { + return service.count(storeId); + } + + @Login + @GetMapping("/userCount") + @ApiOperation("用户端未读消息") + public Result userCount(@ApiParam("店铺id(总后台商户传0)") @RequestAttribute Long userId) { + return service.userCount(userId); + } + +} diff --git a/src/main/java/com/sqx/modules/chats/entity/Chats.java b/src/main/java/com/sqx/modules/chats/entity/Chats.java new file mode 100644 index 0000000..59624c1 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/entity/Chats.java @@ -0,0 +1,44 @@ +package com.sqx.modules.chats.entity; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +/** + * 聊天会话 + */ +@Data +@Entity +@org.hibernate.annotations.Table(appliesTo = "chats",comment = "聊天会话") +public class Chats implements Serializable { + @Id() + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(columnDefinition = "bigInt(20) comment '会话id'") + private Long chatId; + @Column(columnDefinition = "varchar(255) comment '创建时间'") + private String createTime; + /**用户信息*/ + @Column(columnDefinition = "bigInt(20) comment '用户id'") + private Long userId; + @Column(columnDefinition = "varchar(255) comment '用户头像'") + private String userHead; + @Column(columnDefinition = "varchar(255) comment '用户昵称'") + private String userName; + /**商户信息*/ + @Column(columnDefinition = "bigInt(20) comment '总后台id(总后台传0'") + private Long storeId; + @Column(columnDefinition = "varchar(255) comment '后台头像'") + private String storeHead; + @Column(columnDefinition = "varchar(255) comment '商户昵称'") + private String storeName; + /**聊天内容*/ + @Column(columnDefinition = "int default 0 comment'用户未读条数'") + private Integer userCount; + @Column(columnDefinition = "int default 0 comment'后台未读条数'") + private Integer storeCount; + @Transient + private String content; //聊天内容 + @Transient + private String contentTime; //消息时间 +} diff --git a/src/main/java/com/sqx/modules/chats/entity/ChatsContent.java b/src/main/java/com/sqx/modules/chats/entity/ChatsContent.java new file mode 100644 index 0000000..3a48d40 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/entity/ChatsContent.java @@ -0,0 +1,39 @@ +package com.sqx.modules.chats.entity; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +/** + * 聊天会话内容 + */ + +@Data +@Entity +@org.hibernate.annotations.Table(appliesTo = "chats_content",comment = "聊天会话内容") +public class ChatsContent implements Serializable { + @Id() + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(columnDefinition = "bigInt(20) comment '会话内容id'") + private Long chatContentId; + @Column(columnDefinition = "text comment '聊天内容'") + private String content; + @Column(columnDefinition = "int(1) comment '类型(1文字 2图片 3订单 4商品)'") + private Integer type; + @Column(columnDefinition = "int default 1 comment '是否已读(1未读 2已读)'") + private Integer status; + @Column(columnDefinition = "varchar(255) comment '创建时间'") + private String createTime; + @Column(columnDefinition = "int(1) comment '消息来源(1用户消息 2后台消息)'") + private Integer sendType; + @Column(columnDefinition = "bigInt(20) comment '用户id'") + private Long userId; + @Column(columnDefinition = "bigInt(20) comment '后台id(总后台传0)'") + private Long storeId; + /**会话信息*/ + @Column(columnDefinition = "bigInt(20) comment '会话id'") + private Long chatId; + @Transient + private Chats chat; //聊天会话 +} diff --git a/src/main/java/com/sqx/modules/chats/respository/ChatContentRepository.java b/src/main/java/com/sqx/modules/chats/respository/ChatContentRepository.java new file mode 100644 index 0000000..2a56b05 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/respository/ChatContentRepository.java @@ -0,0 +1,42 @@ +package com.sqx.modules.chats.respository; + + + +import com.sqx.modules.chats.entity.ChatsContent; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Repository +public interface ChatContentRepository extends JpaRepository { + + //条件查询带分页 + Page findAll(Specification specification, Pageable pageable); + + //条件查询 + List findAll(Specification specification); + + //根据会话id删除聊天内容 + void deleteAllByChatId(Long chatId); + + //用户消息设置为已读 + @Modifying + @Transactional + @Query(value = "update ChatsContent s set s.status=2 where s.chatId=:chatId and s.sendType=1") + Integer updateStatusByChantIdAndSendTye1(@Param("chatId") Long chatId); + + //店铺消息设置为已读 + @Modifying + @Transactional + @Query(value = "update ChatsContent s set s.status=2 where s.chatId=:chatId and s.sendType=2") + Integer updateStatusByChantIdAndSendTye2(@Param("chatId") Long chatId); + +} diff --git a/src/main/java/com/sqx/modules/chats/respository/ChatRepository.java b/src/main/java/com/sqx/modules/chats/respository/ChatRepository.java new file mode 100644 index 0000000..0f6b606 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/respository/ChatRepository.java @@ -0,0 +1,77 @@ +package com.sqx.modules.chats.respository; + + +import com.sqx.modules.chats.entity.Chats; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; + +@Repository +public interface ChatRepository extends JpaRepository { + + //条件查询带分页 + Page findAll(Specification specification, Pageable pageable); + + //条件查询 + List findAll(Specification specification, Sort sort); + + //商家端未读消息统计 + @Query(value = "select sum(s.storeCount) from Chats s where s.storeId=:storeId") + Integer count(@Param("storeId") Long storeId); + + @Query(value = "select sum(s.userCount) from Chats s where s.userId=:userId") + Integer userCounts(@Param("userId") Long userId); + + //根据用户id和店铺id查询会话 + @Query(value = "from Chats s where s.userId=:userId and s.storeId=:storeId") + List findByUserIdAndStoreId(@Param("userId") Long userId, @Param("storeId") Long storeId); + + //商家端会话列表 + @Query(value = "select c.chat_id as chatId,c.store_count as storeCount,c.user_head as userHead,c.user_name as userName, cc.content, cc.create_time as contentContent from chats c left join chat_content cc on c.chat_id = cc.chat_id where c.store_id=:storeId order by cc.create_time desc", + nativeQuery=true) + List> findAllByStoreId(@Param("storeId") Long storeId); + + //商家端会话列表 + @Query(value = "select c.chat_id as chatId,c.store_count as storeCount,c.user_head as userHead,c.user_name as userName, cc.content, cc.create_time as contentContent from chats c left join chat_content cc on c.chat_id = cc.chat_id where c.store_id=:storeId and c.user_name like concat('%',:userName,'%') order by cc.create_time desc", + nativeQuery=true) + List> findAllByStoreIdAndUserName(@Param("storeId") Long storeId, @Param("userName") String userName); + + //用户端会话列表 + @Query(value = "select c.chat_id as chatId,c.store_head as storeHead,c.store_name as storeName,c.user_count as userCount, cc.content, cc.create_time as contentContent from chats c left join chat_content cc on c.chat_id = cc.chat_id where c.user_id=:userId order by cc.create_time desc limit 0,1", + nativeQuery=true) + List> findAllByUserId(@Param("userId") Long userId); + + //店铺未读+1 + @Modifying + @Transactional + @Query(value = "update Chats s set s.storeCount=s.storeCount+1, s.createTime=:createTime where s.chatId=:chatId") + Integer addStoreCount(@Param("chatId") Long chatId, @Param("createTime") String createTime); + + //店铺未读清空 + @Modifying + @Transactional + @Query(value = "update Chats s set s.storeCount=0 where s.chatId=:chatId") + Integer storeCount(@Param("chatId") Long chatId); + + //用户未读+1 + @Modifying + @Transactional + @Query(value = "update Chats s set s.userCount=s.userCount+1, s.createTime=:createTime where s.chatId=:chatId") + Integer addUserCount(@Param("chatId") Long chatId, @Param("createTime") String createTime); + + //用户未读清空 + @Modifying + @Transactional + @Query(value = "update Chats s set s.userCount=0 where s.chatId=:chatId") + Integer userCount(@Param("chatId") Long chatId); +} diff --git a/src/main/java/com/sqx/modules/chats/service/ChatsContentService.java b/src/main/java/com/sqx/modules/chats/service/ChatsContentService.java new file mode 100644 index 0000000..cae4189 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/service/ChatsContentService.java @@ -0,0 +1,39 @@ +package com.sqx.modules.chats.service; + + +import com.sqx.modules.chats.entity.ChatsContent; +import com.sqx.modules.chats.utils.Result; + +public interface ChatsContentService { + + /** + * 用户聊天内容列表 + * @param chatId + * @return + */ + Result findAll(Long chatId); + + /** + * 店铺聊天内容列表 + * @param chatId + * @return + */ + Result storeList(Long chatId); + + //查询 + Result findOne(Long id); + + //删除 + Result delete(String ids); + + /** + * 发送消息 + * @param entity + * @return + */ + Result saveBody(ChatsContent entity); + + //修改 + Result updateBody(ChatsContent entity); + +} diff --git a/src/main/java/com/sqx/modules/chats/service/ChatsContentServiceImpl.java b/src/main/java/com/sqx/modules/chats/service/ChatsContentServiceImpl.java new file mode 100644 index 0000000..372de0a --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/service/ChatsContentServiceImpl.java @@ -0,0 +1,140 @@ +package com.sqx.modules.chats.service; + + +import com.sqx.modules.chats.entity.Chats; +import com.sqx.modules.chats.entity.ChatsContent; +import com.sqx.modules.chats.respository.ChatContentRepository; +import com.sqx.modules.chats.respository.ChatRepository; +import com.sqx.modules.chats.utils.DateUtil; +import com.sqx.modules.chats.utils.Result; +import com.sqx.modules.chats.utils.ResultUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.ArrayList; +import java.util.List; + +@Service +public class ChatsContentServiceImpl implements ChatsContentService { + @Autowired + private ChatContentRepository jpaRepository; + @Autowired + private ChatRepository chatRepository; + + /** + * 用户聊天内容列表 + * @param chatId 会话id + * @return + */ + @Override + public Result findAll(Long chatId) { + //构造自定义查询条件 + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + predicateList.add(criteriaBuilder.equal(root.get("chatId"), chatId)); + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + List list = jpaRepository.findAll(queryCondition); + /* + 用户调取消息内容列表 + 1.用户的未读数为0 + 2.店铺发送的消息为已读 + */ + chatRepository.userCount(chatId); //用户未读为0 + jpaRepository.updateStatusByChantIdAndSendTye2(chatId); //用户调取列表,设置店铺发送的消息为已读 + //聊天会话信息 + List allChat = chatRepository.findAll(); + for (ChatsContent cc : list) { + for (Chats c : allChat) { + if (c.getChatId().equals( cc.getChatId())){ + cc.setChat(c); + } + } + } + return ResultUtil.success(list); + } + + /** + * 店铺聊天内容列表 + * @param chatId + * @return + */ + @Override + public Result storeList(Long chatId) { + //构造自定义查询条件 + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + predicateList.add(criteriaBuilder.equal(root.get("chatId"), chatId)); + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + List list = jpaRepository.findAll(queryCondition); + /* + 店铺调取消息内容列表 + 1.店铺的未读数为0 + 2.用户发送的消息为已读 + */ + chatRepository.storeCount(chatId); //用户未读为0 + jpaRepository.updateStatusByChantIdAndSendTye1(chatId); //店铺调取列表,设置用户发送的消息为已读 + //聊天会话信息 + List allChat = chatRepository.findAll(); + for (ChatsContent cc : list) { + for (Chats c : allChat) { + if (c.getChatId().equals(cc.getChatId())){ + cc.setChat(c); + } + } + } + return ResultUtil.success(list); + } + + /** + * 发送消息 + * @param entity + * @return + */ + @Override + public Result saveBody(ChatsContent entity) { + //发送消息保存消息 + entity.setCreateTime(DateUtil.createTime()); + entity.setStatus(1); //未读 + ChatsContent save = jpaRepository.save(entity); + //会话列表未读加1 + if (save.getSendType() == 1){ + chatRepository.addStoreCount(save.getChatId(), DateUtil.createTime()); //用户发送消息,店铺未读+1 + }else { + chatRepository.addUserCount(save.getChatId(), DateUtil.createTime()); //店铺发送消息,用户未读+1 + } + return ResultUtil.success(save); + } + + @Override + public Result updateBody(ChatsContent entity) { + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result findOne(Long id) { + return ResultUtil.success(jpaRepository.findById(id).orElse(null)); + } + + @Override + public Result delete(String ids) { + String[] split = ids.split(","); + for (String id : split) { + jpaRepository.deleteById(Long.valueOf(id)); + } + return ResultUtil.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/chats/service/ChatsService.java b/src/main/java/com/sqx/modules/chats/service/ChatsService.java new file mode 100644 index 0000000..d9522ca --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/service/ChatsService.java @@ -0,0 +1,43 @@ +package com.sqx.modules.chats.service; + + +import com.sqx.modules.chats.entity.Chats; +import com.sqx.modules.chats.utils.Result; + +public interface ChatsService { + + /** + * 商家端未读消息 + * @param storeId + * @return + */ + Result count(Long storeId); + Result userCount(Long count); + + /** + * 商家端会话列表 + * @param storeId + * @return + */ + Result findAll(Long storeId, String userName); + + /** + * 用户端会话列表 + * @param userId + * @return + */ + Result userList(Long userId); + + //查询 + Result findOne(Long id); + + //删除 + Result delete(Long id); + + //添加 + Result saveBody(Chats entity); + + //修改 + Result updateBody(Chats entity); + +} diff --git a/src/main/java/com/sqx/modules/chats/service/ChatsServiceImpl.java b/src/main/java/com/sqx/modules/chats/service/ChatsServiceImpl.java new file mode 100644 index 0000000..d085613 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/service/ChatsServiceImpl.java @@ -0,0 +1,134 @@ +package com.sqx.modules.chats.service; + + +import com.sqx.modules.chat.entity.ChatContent; +import com.sqx.modules.chats.entity.Chats; +import com.sqx.modules.chats.entity.ChatsContent; +import com.sqx.modules.chats.respository.ChatContentRepository; +import com.sqx.modules.chats.respository.ChatRepository; +import com.sqx.modules.chats.utils.DateUtil; +import com.sqx.modules.chats.utils.Result; +import com.sqx.modules.chats.utils.ResultUtil; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.ArrayList; +import java.util.List; + +@Service +public class ChatsServiceImpl implements ChatsService { + @Autowired + private ChatRepository jpaRepository; + @Autowired + private ChatContentRepository chatContentRepository; + + @Override + public Result count(Long storeId) { + Integer count = jpaRepository.count(storeId); + return ResultUtil.success(count==null?0:count); + } + + @Override + public Result userCount(Long userId) { + Integer count = jpaRepository.userCounts(userId); + return ResultUtil.success(count==null?0:count); + } + + /** + * 商家端会话列表 + * @param storeId + * @return + */ + @Override + public Result findAll(Long storeId, String userName) { + //构造自定义查询条件 + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + predicateList.add(criteriaBuilder.equal(root.get("storeId"), storeId)); + if (StringUtils.isNotEmpty(userName)){ + predicateList.add(criteriaBuilder.like(root.get("userName"), "%"+userName+"%")); + } + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + List list = jpaRepository.findAll(queryCondition, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime"))); + //最新一条消息展示 + List allContent = chatContentRepository.findAll(); + for (Chats c : list) { + for (ChatsContent cc : allContent) { + if (c.getChatId().equals(cc.getChatId())){ + c.setContent(cc.getContent()); + c.setContentTime(cc.getCreateTime()); + } + } + } + return ResultUtil.success(list); + } + + /** + * 用户端会话列表 + * @param userId + * @return + */ + @Override + public Result userList(Long userId) { + //构造自定义查询条件 + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + predicateList.add(criteriaBuilder.equal(root.get("userId"), userId)); + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + List list = jpaRepository.findAll(queryCondition, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime"))); + return ResultUtil.success(list); + } + + /** + * 用户端发起聊天 + * @param entity + * @return + */ + @Override + public Result saveBody(Chats entity) { + //判断是否存在聊天 + List chatList = jpaRepository.findByUserIdAndStoreId(entity.getUserId(), entity.getStoreId()); + if (chatList.size() > 0){ + Chats chat = chatList.get(0); + return ResultUtil.success(chat); + }else { + //不存在会话,创建会话 + entity.setCreateTime(DateUtil.createTime()); + Chats save = jpaRepository.save(entity); + return ResultUtil.success(save); + } + } + + @Override + public Result updateBody(Chats entity) { + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result findOne(Long id) { + return ResultUtil.success(jpaRepository.findById(id).orElse(null)); + } + + + @Override + public Result delete(Long id) { + jpaRepository.deleteById(id); //删除会话 + chatContentRepository.deleteAllByChatId(id); //删除会话聊天内容 + return ResultUtil.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/chats/utils/DateUtil.java b/src/main/java/com/sqx/modules/chats/utils/DateUtil.java new file mode 100644 index 0000000..498c43f --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/utils/DateUtil.java @@ -0,0 +1,547 @@ +package com.sqx.modules.chats.utils; + +import org.apache.commons.lang.time.DateUtils; +import org.apache.commons.lang3.StringUtils; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +public class DateUtil { + /** + * 判断是否是购物节日期 + * @param date + * @return true 是 + */ + public static boolean isShoppingFestival(Date date){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + int month = calendar.get(Calendar.MONTH)+1; + int day = calendar.get(Calendar.DAY_OF_MONTH); + + //判断是否是双十一 + if(month==11 && day==11){ + return true; + } + + //判断是否是双十二 + if(month==12 && day==12){ + return true; + } + + return false; + } + + /** + * 获取两个日期之间左右年月 + * @param minDate + * @param maxDate + * @return + * @throws ParseException + */ + public static List getMonthBetween(Date minDate, Date maxDate) throws ParseException { + ArrayList result = new ArrayList(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月 + + Calendar min = Calendar.getInstance(); + Calendar max = Calendar.getInstance(); + + min.setTime(minDate); + min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); + + max.setTime(maxDate); + max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); + + Calendar curr = min; + while (curr.before(max)) { + result.add(sdf.format(curr.getTime())); + curr.add(Calendar.MONTH, 1); + } + + return result; + } + + /** + * 获取指定月份天数 + * @param year 年份(四位数) + * @param month 月份(从1开始) + * @return + */ + public static int getMonthDays(int year, int month) { + if (month == 2) { + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { + return 29; + } else { + return 28; + } + } else if (month == 4 || month == 6 || month == 9 || month == 11) { + return 30; + } else { + return 31; + } + } + + /** + * 判断时间是否在时间段内 + * + * @param date + * 当前时间 yyyy-MM-dd HH:mm:ss + * @param strDateBegin + * 开始时间 00:00 + * @param strDateEnd + * 结束时间 00:05 + * @return 在时间段内返回true + */ + public static boolean isInDate(Date date, String strDateBegin, String strDateEnd) { + + if(date==null || StringUtils.isBlank(strDateBegin) || StringUtils.isBlank(strDateEnd)){ + return false; + } + + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); + String strDate = sdf.format(date); + // 截取当前时间时分秒 + int strDateH = Integer.parseInt(strDate.substring(0, 2)); + int strDateM = Integer.parseInt(strDate.substring(3, 5)); + // 截取开始时间时分秒 + int strDateBeginH = Integer.parseInt(strDateBegin.substring(0, 2)); + int strDateBeginM = Integer.parseInt(strDateBegin.substring(3, 5)); + // 截取结束时间时分秒 + int strDateEndH = Integer.parseInt(strDateEnd.substring(0, 2)); + int strDateEndM = Integer.parseInt(strDateEnd.substring(3, 5)); + + if(strDateH >= strDateBeginH && strDateH <= strDateEndH){ + + //判断开始时间和结束时间的小时是否一样 + if(strDateBeginH == strDateEndH){ //是 + + // + if(strDateH == strDateBeginH){ + if(strDateM >= strDateBeginM && strDateM <= strDateEndM){ + return true; + } + }else{ + return false; + } + + }else{ //否 + + if(strDateH == strDateBeginH){ + + if(strDateM >= strDateBeginM){ + return true; + }else{ + return false; + } + + }else if(strDateH == strDateEndH){ + + if(strDateM <= strDateEndM){ + return true; + }else{ + return false; + } + + }else{ + return true; + } + + } + }else{ + return false; + } + + return false; + } + /** + * + * @param pattern,字符串的format格式,例如:yyyy-MM-dd HH:mm:ss + * @param date,需要转换为指定格式的日期对象 + * @return + */ + public static String getFormatStrByPatternAndDate(String pattern,Date date){ + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); + return simpleDateFormat.format(date); + } + public static Date getDataByFormatString(String pattern,String dateFormatStr){ + try { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); + return simpleDateFormat.parse(dateFormatStr); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + + /** + * 将日期的时分秒转为 00:00:00 + * @param date + * @return + * @throws + */ + public static Date lowDate(Date date){ + String lowDate = getFormatStrByPatternAndDate("yyyy-MM-dd",date) + " 00:00:00"; + return getDataByFormatString("yyyy-MM-dd HH:mm:ss",lowDate); + } + + /** + * 将日期的时分秒转为 23:59:59 + * @param date + * @return + * @throws ParseException + */ + public static Date hightDate(Date date){ + String lowDate = getFormatStrByPatternAndDate("yyyy-MM-dd",date) + " 23:59:59"; + return getDataByFormatString("yyyy-MM-dd HH:mm:ss",lowDate); + } + + /** + * 计算d1 到 d2 相差多少时间 + * @param d1 未来的时间 + * @param d2 现在的时间 + * @return 数组下标 0 天 1 时 2 分 3 秒 + */ + public static long[] dateDiff(Date d1, Date d2) throws ParseException { + long nd = 1000*24*60*60;//一天的毫秒数 + long nh = 1000*60*60;//一小时的毫秒数 + long nm = 1000*60;//一分钟的毫秒数 + long ns = 1000;//一秒钟的毫秒数 + //获得两个时间的毫秒时间差异 + long diff = d1.getTime() - d2.getTime(); + long day = diff/nd;//计算差多少天 + long hour = diff%nd/nh;//计算差多少小时 + long min = diff%nd%nh/nm;//计算差多少分钟 + long sec = diff%nd%nh%nm/ns;//计算差多少秒 + return new long[]{day,hour,min,sec}; + } + + /** + * 判断 start 是否大于 end + * @param start + * @param end + * @return + * @throws ParseException + */ + public static boolean startThanEnd(Date start, Date end) throws ParseException{ + long[] result = dateDiff(start, end); + if(result[0]>=0 && result[1]>=0 && result[2]>=0 && result[3]>=0){ + return true; + } + return false; + } + + /** + * 获取指定日期指定分钟后的日期 + * @param date + * @param minute + * @return + */ + public static Date getLaterMinute(Date date, Long minute) { + minute = minute == null ? 0 : minute; + long curren = date.getTime(); + curren += minute * 60 * 1000; + return new Date(curren); + } + + /** + * 获取指定日期指定分钟前的日期 + * @param date + * @param minute + * @return + */ + public static Date getPreviouslyMinute(Date date, Long minute) { + minute = minute == null ? 0 : minute; + long curren = date.getTime(); + curren -= minute * 60 * 1000; + return new Date(curren); + } + + /** + * 获取指定日期指定天数后的日期 + * @param date 指定的时间 + * @param later 指定的天数 + * @return + */ + public static Date getLaterDay(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current + later * 24 * 60 * 60 * 1000); + } + + + /** + * 获取指定日期指定天数前的日期 + * @param date 指定的时间 + * @param later 指定的天数 + * @return + */ + public static Date getPreviouslyDay(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current - later * 24 * 60 * 60 * 1000); + } + + /** + * 获取指定日期指定小时后的日期 + * @param date 指定的时间 + * @param later 指定的小时 + * @return + */ + public static Date getLaterHour(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current + later * 60 * 60 * 1000); + } + + /** + * 获取指定日期指定小时前的日期 + * @param date 指定的时间 + * @param later 指定的小时 + * @return + */ + public static Date getPreviouslyHour(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current - later * 60 * 60 * 1000); + } + + /** + * 得到本周周一 + * @return + */ + public static Date getMondayOfWeek() { + Calendar c = Calendar.getInstance(); + int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1; + if (day_of_week == 0){ + day_of_week = 7; + } + c.add(Calendar.DATE, -day_of_week + 1); + return c.getTime(); + } + + /** + * 得到本周周日 + * @return + */ + public static Date getSundayOfWeek() { + Calendar c = Calendar.getInstance(); + int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1; + if (day_of_week == 0){ + day_of_week = 7; + } + c.add(Calendar.DATE, -day_of_week + 7); + return c.getTime(); + } + + /** + * 获取当前月的第一天 + * @return + */ + public static Date getFirstDayOfMonth(){ + Calendar c = Calendar.getInstance(); + c.add(Calendar.MONTH, 0); + c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 + return c.getTime(); + } + + /** + * 获取当前月的最后一天 + * @return + */ + public static Date getLastDayOfMonth(){ + Calendar ca = Calendar.getInstance(); + ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); + return ca.getTime(); + } + + /** + * 获取上一个月的第一天 + * @return + */ + public static Date getFirstDayOfPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -1); + calendar.set(Calendar.DAY_OF_MONTH,1); + return calendar.getTime(); + } + + /** + * 获取上一个月的最后一天 + * @return + */ + public static Date getLastDayOfPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DAY_OF_MONTH, 0); + return calendar.getTime(); + } + + /** + * 获取上上一个月的第一天 + * @return + */ + public static Date getFirstDayOfPPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -2); + calendar.set(Calendar.DAY_OF_MONTH,1); + return calendar.getTime(); + } + + /** + * 获取上上一个月的最后一天 + * @return + */ + public static Date getLastDayOfPPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -1); + calendar.set(Calendar.DAY_OF_MONTH, 0); + return calendar.getTime(); + } + + /** + * 获取指定日期是星期几 + * @param date + * @return + */ + public static int getDayOfWeek(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + //一周第一天是否为星期天 + boolean isFirstSunday = (cal.getFirstDayOfWeek() == Calendar.SUNDAY); + //获取周几 + int weekDay = cal.get(Calendar.DAY_OF_WEEK); + //若一周第一天为星期天,则-1 + if (isFirstSunday) { + weekDay = weekDay - 1; + if (weekDay == 0) { + weekDay = 7; + } + } + return weekDay; + } + + /** + * 获取创建时间 + * @return + */ + public static String createTime() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + } + + /** + * 获取创建时间 + * @return + */ + public static String createDate() { + return new SimpleDateFormat("yyyy-MM-dd").format(new Date()); + } + + /** + * 结束时间 + * @return + */ + public static String endTime(Integer hours) { + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = DateUtils.addHours(new Date(), hours); + return sf.format(date); + } + + /** + * 结束时间 + * @param days 日期 + * @return + */ + public static String addDays(String nowTime, Integer days) { + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try{ + Date date = DateUtils.addDays(sf.parse(nowTime), days); + return sf.format(date); + }catch (Exception e){ + e.printStackTrace(); + return null; + } + } + + //判断是否在规定的时间内签到 nowTime 当前时间 beginTime规定开始时间 endTime规定结束时间 + public static boolean betweenStratEndTime(String startTime, String endTime) throws Exception{ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String now = sf.format(new Date()); + //设置当前时间 + Calendar date = Calendar.getInstance(); + date.setTime(sf.parse(now)); + //设置开始时间 + Calendar start = Calendar.getInstance(); + start.setTime(sf.parse(startTime));//开始时间 + //设置结束时间 + Calendar end = Calendar.getInstance(); + start.setTime(sf.parse(endTime));//开始时间 + //处于开始时间之后,和结束时间之前的判断 + + if ((start.after(date) && end.before(date))) { + return true; + } else { + return false; + } + } + + /** + * 获取当前日期的几天前/后的日期:传入-1为一天前 + * @return + */ + public static String getBeforeDay(int num){ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.DATE, num); + return sf.format(cal.getTime()); + } + + /** + * 获取当前日期的几月前/后的日期:传入-1为上月 + * @return + */ + public static String getBeforeMonth(int num){ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM"); + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.MONTH, num); + return sf.format(cal.getTime()); + } + + /** + * 是否开始 + * @param startTime 开始时间 + * @return true 已开始 + */ + public static boolean isStart(String startTime){ + try{ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date f = sf.parse(startTime); + return f.before(new Date()); + }catch (Exception e){ + e.printStackTrace(); + } + return true; + } + + /** + * 获取指定时间几分钟前的时间 + * @return + */ + public static String getBeforeMinute(String time, int num){ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar cal = Calendar.getInstance(); + try{ + Date timeDate = sf.parse(time); + cal.setTime(timeDate); + cal.add(Calendar.MINUTE, -num); + return sf.format(cal.getTime()); + }catch (Exception e){ + e.printStackTrace(); + } + return time; + } + +} diff --git a/src/main/java/com/sqx/modules/chats/utils/DescribeException.java b/src/main/java/com/sqx/modules/chats/utils/DescribeException.java new file mode 100644 index 0000000..8c7799b --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/utils/DescribeException.java @@ -0,0 +1,34 @@ +package com.sqx.modules.chats.utils; + +public class DescribeException extends RuntimeException{ + + private Integer code; + + /** + * 继承exception,加入错误状态值 + * @param exceptionEnum + */ + public DescribeException(ExceptionEnum exceptionEnum) { + super(exceptionEnum.getMsg()); + this.code = exceptionEnum.getCode(); + } + + /** + * 自定义错误信息 + * @param message + * @param code + */ + public DescribeException(String message, Integer code) { + super(message); + this.code = code; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } +} + diff --git a/src/main/java/com/sqx/modules/chats/utils/ExceptionEnum.java b/src/main/java/com/sqx/modules/chats/utils/ExceptionEnum.java new file mode 100644 index 0000000..3240791 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/utils/ExceptionEnum.java @@ -0,0 +1,49 @@ +package com.sqx.modules.chats.utils; + +public enum ExceptionEnum { + UNKNOW_ERROR(-1, "未知错误"), + LIMIT_USER(-100, "当前账户受限制请联系管理员"), + USER_NOT_FIND(-101, "用户未注册"), + USER_IS_BIND_FOR_ANTHER_OPENID(-99, "当前手机号已经被其他微信绑定"), + WRONT_TOKEN(-102, "用户信息失效,请重新登录"), + USER_PWD_EMPTY(-103, "用户名密码不能为空"), + USER_PWD_ERROR(-104, "用户名或密码错误"), + USER_IS_EXITS(-105, "手机号已经注册!"), + ERROR(-106, "服务器内部错误"), + UPDATE_PWD_ERROR(-107, "密码修改失败"), + STATE_PWD_ERROR(-108, "状态修改失败"), + DATA_EMPTY(-109, "添加数据不能为空"), + Return_ATA_EMPTY(-110, "暂无数据"), + ADD_ERROR(-111, "提现失败"), + CODE_ERROR(-112, "验证码不正确"), + BIND_ERROR(-113, "手机号已经被其他账号绑定"), + SEND_ERROR(-114, "验证码发送失败"), + USER_PHONE_ERROR(-115, "用户名不能为空"), + OLD_PWD_ERROR(-116, "原始密码错误"), + IS_REGISTER(-117, "当前手机号已经绑定其他微信账号"), + IS_BIND(-118, "当前淘宝账号已经绑定其他手机号"), + IS_BIND_RELATION(-119, "当前账号已经绑定其他淘宝账号"), + OLD_NOT_SAME_NEW_PWD_ERROR(-120, "新密码不能等于和原始密码一致"), + USER_IS_REGISTER(-121, "用户已经注册请前往登录"), + RELATIONID_IS_REGISTER(-122, "淘宝账号已经授权绑定其他手机号"), + CODE_NOT_FOUND(-123, "邀请码不存在"), + COMMON_IS_EXITS(-124, "已经存在"), + COUPONS_ZERO(-125, "优惠券被领完了"), + COUPONS_GET_OUT(-126, "优惠券超过领取次数"), + COUPONS_TIME_OUT(-127, "优惠券已过期"); + private Integer code; + private String msg; + ExceptionEnum(Integer code, String msg) { + this.code = code; + this.msg = msg; + } + + public Integer getCode() { + return code; + } + + public String getMsg() { + return msg; + } +} + diff --git a/src/main/java/com/sqx/modules/chats/utils/Result.java b/src/main/java/com/sqx/modules/chats/utils/Result.java new file mode 100644 index 0000000..02594ee --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/utils/Result.java @@ -0,0 +1,51 @@ +package com.sqx.modules.chats.utils; + +public class Result { + + // error_code 状态值:0 极为成功,其他数值代表失败 + private Integer status; + + // error_msg 错误信息,若status为0时,为success + private String msg; + + // content 返回体报文的出参,使用泛型兼容不同的类型 + private T data; + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer code) { + this.status = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public T getData(Object object) { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public T getData() { + return data; + } + + @Override + public String toString() { + return "Result{" + + "status=" + status + + ", msg='" + msg + '\'' + + ", data=" + data + + '}'; + + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/chats/utils/ResultUtil.java b/src/main/java/com/sqx/modules/chats/utils/ResultUtil.java new file mode 100644 index 0000000..d844147 --- /dev/null +++ b/src/main/java/com/sqx/modules/chats/utils/ResultUtil.java @@ -0,0 +1,56 @@ +package com.sqx.modules.chats.utils; + +public class ResultUtil { + + /** + * 返回成功,传入返回体具体出參 + * + * @param object + * @return + */ + public static Result success(Object object) { + Result result = new Result(); + result.setStatus(0); + result.setMsg("success"); + result.setData(object); + return result; + } + + /** + * 提供给部分不需要出參的接口 + * + * @return + */ + public static Result success() { + return success(null); + } + + /** + * 自定义错误信息 + * + * @param code + * @param msg + * @return + */ + public static Result error(Integer code, String msg) { + Result result = new Result(); + result.setStatus(code); + result.setMsg(msg); + result.setData(null); + return result; + } + + /** + * 返回异常信息,在已知的范围内 + * + * @param exceptionEnum + * @return + */ + public static Result error(ExceptionEnum exceptionEnum) { + Result result = new Result(); + result.setStatus(exceptionEnum.getCode()); + result.setMsg(exceptionEnum.getMsg()); + result.setData(null); + return result; + } +} diff --git a/src/main/java/com/sqx/modules/common/controller/CommonController.java b/src/main/java/com/sqx/modules/common/controller/CommonController.java new file mode 100644 index 0000000..5419412 --- /dev/null +++ b/src/main/java/com/sqx/modules/common/controller/CommonController.java @@ -0,0 +1,57 @@ +package com.sqx.modules.common.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "通用配置管理", tags = {"通用配置管理"}) +@RequestMapping(value = "/common") +public class CommonController { + @Autowired + private CommonInfoService commonService; + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台通用配置详情") + @ResponseBody + public Result getCommon(@PathVariable Integer id) { + return Result.success().put("data",commonService.findOne(id)); + } + + @RequestMapping(value = "/update", method = RequestMethod.POST) + @ApiOperation("管理平台添加通用配置") + @ResponseBody + public Result addCommon(@RequestBody CommonInfo app) { + + return commonService.update(app); + } + + @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台删除通用配置") + public Result deleteCommon(@PathVariable int id) { + return commonService.delete(id); + } + + @RequestMapping(value = "/type/{type}", method = RequestMethod.GET) + @ApiOperation("用户端根据type获取对象") + @ResponseBody + public Result getCommonList(@PathVariable Integer type) { + return commonService.findByType(type); + } + + + @RequestMapping(value = "/type/condition/{condition}", method = RequestMethod.GET) + @ApiOperation("根据condition去查询 xitong xitongs shouye") + @ResponseBody + public Result findByTypeAndCondition(@PathVariable String condition) { + return commonService.findByTypeAndCondition(condition); + } + + + + +} diff --git a/src/main/java/com/sqx/modules/common/controller/app/AppCommonController.java b/src/main/java/com/sqx/modules/common/controller/app/AppCommonController.java new file mode 100644 index 0000000..c71dfcc --- /dev/null +++ b/src/main/java/com/sqx/modules/common/controller/app/AppCommonController.java @@ -0,0 +1,26 @@ +package com.sqx.modules.common.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.common.service.CommonInfoService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "通用配置管理", tags = {"通用配置管理"}) +@RequestMapping(value = "/app/common") +public class AppCommonController { + @Autowired + private CommonInfoService commonService; + + + @RequestMapping(value = "/type/{type}", method = RequestMethod.GET) + @ApiOperation("用户端根据type获取对象") + @ResponseBody + public Result getCommonList(@PathVariable Integer type) { + return commonService.findByType(type); + } + + +} diff --git a/src/main/java/com/sqx/modules/common/dao/CommonInfoDao.java b/src/main/java/com/sqx/modules/common/dao/CommonInfoDao.java new file mode 100644 index 0000000..558bf5e --- /dev/null +++ b/src/main/java/com/sqx/modules/common/dao/CommonInfoDao.java @@ -0,0 +1,24 @@ +package com.sqx.modules.common.dao; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.common.entity.CommonInfo; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * @author fang + * @date 2020/7/8 + */ +@Mapper +public interface CommonInfoDao extends BaseMapper { + + List findByCondition(@Param("condition") String condition); + + CommonInfo findOne(@Param("type") int type); + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/common/entity/CommonInfo.java b/src/main/java/com/sqx/modules/common/entity/CommonInfo.java new file mode 100644 index 0000000..db944b1 --- /dev/null +++ b/src/main/java/com/sqx/modules/common/entity/CommonInfo.java @@ -0,0 +1,36 @@ +package com.sqx.modules.common.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import lombok.Data; + +import java.io.Serializable; + +/** + * 通用配置管理 + */ +@Data +@TableName("common_info") +public class CommonInfo implements Serializable { + + @TableId(type = IdType.INPUT) + private long id; + + private String createAt; + + private Integer type; //1表示客服二维码 2表示公众号二维码 3表示全局佣金是否开启 4注册客服渠道id配置 5、佣金规则 6、 + + private String value; + + private String max; + + private String min; + + private String conditionFrom; + + private TbCoupon tbCoupon; + +} + diff --git a/src/main/java/com/sqx/modules/common/service/CommonInfoService.java b/src/main/java/com/sqx/modules/common/service/CommonInfoService.java new file mode 100644 index 0000000..4481694 --- /dev/null +++ b/src/main/java/com/sqx/modules/common/service/CommonInfoService.java @@ -0,0 +1,43 @@ +package com.sqx.modules.common.service; + +import com.sqx.common.utils.Result; +import com.sqx.modules.common.entity.CommonInfo; + +/** + * @author fang + * @date 2020/7/8 + */ +public interface CommonInfoService { + + /** + * 保存对象 + * + * @param + */ + Result update(CommonInfo commonInfo); + + /** + * 获取一个对象 + */ + CommonInfo findOne(int id); + + /** + * 删除一个 + */ + Result delete(long id); + + /** + * 修改 + */ + Result updateBody(CommonInfo commonInfo); + /** + * 通过类型查询 + */ + Result findByType(Integer type); + + /** + * 通过类型查询 + */ + Result findByTypeAndCondition(String condition); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/common/service/impl/CommonInfoServiceImpl.java b/src/main/java/com/sqx/modules/common/service/impl/CommonInfoServiceImpl.java new file mode 100644 index 0000000..6094c1d --- /dev/null +++ b/src/main/java/com/sqx/modules/common/service/impl/CommonInfoServiceImpl.java @@ -0,0 +1,85 @@ +package com.sqx.modules.common.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.common.dao.CommonInfoDao; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * @author fang + * @date 2020/7/8 + */ +@Service +public class CommonInfoServiceImpl extends ServiceImpl implements CommonInfoService { + + + private final CommonInfoDao commonInfoDao; + + @Autowired + private TbCouponService couponService; + + @Autowired + public CommonInfoServiceImpl(CommonInfoDao commonInfoDao) { + this.commonInfoDao = commonInfoDao; + } + + @Override + public Result update(CommonInfo commonInfo) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + commonInfo.setCreateAt(sdf.format(now)); + commonInfoDao.updateById(commonInfo); + return Result.success(); + } + + + @Override + public CommonInfo findOne(int id) { + return commonInfoDao.findOne(id); + } + + @Override + public Result delete(long id) { + commonInfoDao.deleteById(id); + return Result.success(); + } + + + @Override + public Result updateBody(CommonInfo commonInfo) { + commonInfoDao.updateById(commonInfo); + return Result.success(); + } + + @Override + public Result findByType(Integer type) { + return Result.success().put("data", commonInfoDao.findOne(type)); + } + + @Override + public Result findByTypeAndCondition(String condition) { + List commonInfoList = commonInfoDao.findByCondition(condition); + for (CommonInfo commonInfo : commonInfoList) { + if (StringUtils.isNotBlank(commonInfo.getValue())){ + String[] split = commonInfo.getValue().split(","); + TbCoupon tbCoupon = couponService.getById(split[0]); + if(tbCoupon!=null){ + commonInfo.setTbCoupon(tbCoupon); + } + } + } + return Result.success().put("data", commonInfoList); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/coupon/controller/SelfCouponController.java b/src/main/java/com/sqx/modules/coupon/controller/SelfCouponController.java new file mode 100644 index 0000000..053ef33 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/controller/SelfCouponController.java @@ -0,0 +1,54 @@ +package com.sqx.modules.coupon.controller; + +import com.sqx.modules.coupon.entity.SelfCoupon; +import com.sqx.modules.coupon.service.SelfCouponService; +import com.sqx.modules.coupon.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="自营商城优惠券制作",tags={"自营商城优惠券制作"}) +@RequestMapping(value = "/selfCoupon") +public class SelfCouponController { + @Autowired + private SelfCouponService service; + + + @GetMapping("/list") + @ApiOperation("列表") + public Result findAll(Integer page, Integer size) { + return service.findAll(page, size); + } + + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody SelfCoupon entity) { + return service.saveBody(entity); + } + + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody SelfCoupon entity) { + return service.updateBody(entity); + } + + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return service.delete(id); + } + +} diff --git a/src/main/java/com/sqx/modules/coupon/controller/SelfCouponIssueController.java b/src/main/java/com/sqx/modules/coupon/controller/SelfCouponIssueController.java new file mode 100644 index 0000000..c7a5e87 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/controller/SelfCouponIssueController.java @@ -0,0 +1,60 @@ +package com.sqx.modules.coupon.controller; + +import com.sqx.modules.coupon.entity.SelfCouponIssue; +import com.sqx.modules.coupon.service.SelfCouponIssueService; +import com.sqx.modules.coupon.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="自营商城优惠券发布",tags={"自营商城优惠券发布"}) +@RequestMapping(value = "/selfCouponIssue") +public class SelfCouponIssueController { + @Autowired + private SelfCouponIssueService service; + + + @GetMapping("/list") + @ApiOperation("后台列表") + public Result findAll(Integer page, Integer size) { + return service.findAll(page, size); + } + + + @GetMapping("/useList") + @ApiOperation("用户端领券列表") + public Result useList(@RequestParam(required = false) Long goodsId, @RequestParam(required = false) Long userId) { + return service.useList(goodsId, userId); + } + + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody SelfCouponIssue entity) { + return service.saveBody(entity); + } + + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody SelfCouponIssue entity) { + return service.updateBody(entity); + } + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return service.delete(id); + } + +} diff --git a/src/main/java/com/sqx/modules/coupon/controller/SelfCouponUserController.java b/src/main/java/com/sqx/modules/coupon/controller/SelfCouponUserController.java new file mode 100644 index 0000000..4992c13 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/controller/SelfCouponUserController.java @@ -0,0 +1,79 @@ +package com.sqx.modules.coupon.controller; + +import com.sqx.modules.coupon.entity.SelfCouponUser; +import com.sqx.modules.coupon.service.SelfCouponUserService; +import com.sqx.modules.coupon.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; + +@RestController +@Api(value="自营商城优惠券领取",tags={"自营商城优惠券领取"}) +@RequestMapping(value = "/selfCouponUser") +public class SelfCouponUserController { + @Autowired + private SelfCouponUserService service; + + @PostMapping("/sendUserCoupon") + @ApiOperation("赠送用户优惠券") + public Result sendUserCoupon(String userIds,String couponIds,Integer type){ + return service.sendUserCoupon(userIds, couponIds,type); + } + + + @GetMapping("/list") + @ApiOperation("列表") + public Result findAll(Integer page, Integer size, String couponName,String nickName) { + return service.findAll(page, size, couponName,nickName); + } + + + @GetMapping("/userList") + @ApiOperation("用户端用户优惠券列表") + public Result userList(Integer page, Integer size, Long userId, @RequestParam(required = false) String goodsId, Integer type, BigDecimal money,Integer status) { + return service.userList(page, size, userId, goodsId, type,money,status); + } + + @GetMapping("/useList") + @ApiOperation("优惠券使用列表") + public Result useList(Long userId, @RequestParam(required = false) String goodsId) { + return service.useList(userId, goodsId); + } + + + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody SelfCouponUser entity) { + return service.saveBody(entity); + } + + + + + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody SelfCouponUser entity) { + return service.updateBody(entity); + } + + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return service.delete(id); + } + +} diff --git a/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponController.java b/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponController.java new file mode 100644 index 0000000..06e4a5b --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponController.java @@ -0,0 +1,54 @@ +package com.sqx.modules.coupon.controller.app; + +import com.sqx.modules.coupon.entity.SelfCoupon; +import com.sqx.modules.coupon.service.SelfCouponService; +import com.sqx.modules.coupon.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="自营商城优惠券制作",tags={"自营商城优惠券制作"}) +@RequestMapping(value = "/app/selfCoupon") +public class AppSelfCouponController { + @Autowired + private SelfCouponService service; + + + @GetMapping("/list") + @ApiOperation("列表") + public Result findAll(Integer page, Integer size) { + return service.findAll(page, size); + } + + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody SelfCoupon entity) { + return service.saveBody(entity); + } + + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody SelfCoupon entity) { + return service.updateBody(entity); + } + + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return service.delete(id); + } + +} diff --git a/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponIssueController.java b/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponIssueController.java new file mode 100644 index 0000000..c3f0c7c --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponIssueController.java @@ -0,0 +1,60 @@ +package com.sqx.modules.coupon.controller.app; + +import com.sqx.modules.coupon.entity.SelfCouponIssue; +import com.sqx.modules.coupon.service.SelfCouponIssueService; +import com.sqx.modules.coupon.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="自营商城优惠券发布",tags={"自营商城优惠券发布"}) +@RequestMapping(value = "/app/selfCouponIssue") +public class AppSelfCouponIssueController { + @Autowired + private SelfCouponIssueService service; + + + @GetMapping("/list") + @ApiOperation("后台列表") + public Result findAll(Integer page, Integer size) { + return service.findAll(page, size); + } + + + @GetMapping("/useList") + @ApiOperation("用户端领券列表") + public Result useList(@RequestParam(required = false) Long goodsId, @RequestParam(required = false) Long userId) { + return service.useList(goodsId, userId); + } + + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody SelfCouponIssue entity) { + return service.saveBody(entity); + } + + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody SelfCouponIssue entity) { + return service.updateBody(entity); + } + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return service.delete(id); + } + +} diff --git a/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponUserController.java b/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponUserController.java new file mode 100644 index 0000000..8870fdb --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/controller/app/AppSelfCouponUserController.java @@ -0,0 +1,73 @@ +package com.sqx.modules.coupon.controller.app; + +import com.sqx.modules.coupon.entity.SelfCouponUser; +import com.sqx.modules.coupon.service.SelfCouponUserService; +import com.sqx.modules.coupon.utils.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; + +@RestController +@Api(value="自营商城优惠券领取",tags={"自营商城优惠券领取"}) +@RequestMapping(value = "/app/selfCouponUser") +public class AppSelfCouponUserController { + @Autowired + private SelfCouponUserService service; + + + @GetMapping("/list") + @ApiOperation("列表") + public Result findAll(Integer page, Integer size, String couponName) { + return service.findAll(page, size, couponName,null); + } + + + @GetMapping("/userList") + @ApiOperation("用户端用户优惠券列表") + public Result userList(Integer page, Integer size, Long userId, @RequestParam(required = false) String goodsId, Integer type, BigDecimal money,Integer status) { + return service.userList(page, size, userId, goodsId, type,money,status); + } + + @GetMapping("/useList") + @ApiOperation("优惠券使用列表") + public Result useList(Long userId, @RequestParam(required = false) String goodsId) { + return service.useList(userId, goodsId); + } + + + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return service.findOne(id); + } + + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody SelfCouponUser entity) { + return service.saveBody(entity); + } + + + + + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody SelfCouponUser entity) { + return service.updateBody(entity); + } + + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return service.delete(id); + } + +} diff --git a/src/main/java/com/sqx/modules/coupon/entity/SelfCoupon.java b/src/main/java/com/sqx/modules/coupon/entity/SelfCoupon.java new file mode 100644 index 0000000..93e4fee --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/entity/SelfCoupon.java @@ -0,0 +1,38 @@ +package com.sqx.modules.coupon.entity; + +import lombok.Data; + +import javax.persistence.*; + +/** + * 自营商城优惠券制作 + */ +@Data +@Entity +public class SelfCoupon { + @Id() + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long couponId; //优惠券id + @Column + private Integer type; //优惠券类型(1通用券 2商品券) + @Column + private String couponName; //优惠券名称 + @Column + private String lessMoney; //优惠券面值 + @Column + private String minMoney; //优惠券最低消费 + @Column + private Integer validDay; //优惠券有效期限(天) + @Column + private Integer sort; //排序 + @Column + private Integer status; //状态(1开启 2关闭) + @Column + private String createTime; //创建时间 + /**商品信息*/ + @Column + private String goodsIds; //商品ids(多个) + @Column + private String goodsImages; //商品图片(多个) + +} diff --git a/src/main/java/com/sqx/modules/coupon/entity/SelfCouponIssue.java b/src/main/java/com/sqx/modules/coupon/entity/SelfCouponIssue.java new file mode 100644 index 0000000..a885d27 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/entity/SelfCouponIssue.java @@ -0,0 +1,46 @@ +package com.sqx.modules.coupon.entity; + +import lombok.Data; + +import javax.persistence.*; + +/** + * 自营商城优惠券发布 + */ +@Data +@Entity +public class SelfCouponIssue { + @Id() + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long couponIssueId; //优惠券发布id + @Column + private String startTime; //领取开启时间 + @Column + private String endTime; //领券结束时间 + @Column + private Integer issueNumber; //发布数量 + @Column + private Integer remainNumber; //剩余数量 + @Column + private Integer isLimit; //是否限量(1限量 2不限量) + @Column + private Integer status; //状态(1开启 2关闭) + @Column + private String createTime; //创建时间 + /**优惠券信息*/ + @Column + private Long couponId; //优惠券id + @Column + private Integer type; //优惠券类型(1通用券 2商品券) + @Column + private String couponName; //优惠券名称 + @Transient + private SelfCoupon coupon; //优惠券实体 + /**商品信息*/ + @Column + private String goodsIds; //商品ids(多个) + /**领取状态*/ + @Transient + private Integer getStatus; //领取状态(1可领取 2已领取) + +} diff --git a/src/main/java/com/sqx/modules/coupon/entity/SelfCouponUser.java b/src/main/java/com/sqx/modules/coupon/entity/SelfCouponUser.java new file mode 100644 index 0000000..1faf396 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/entity/SelfCouponUser.java @@ -0,0 +1,45 @@ +package com.sqx.modules.coupon.entity; + +import lombok.Data; + +import javax.persistence.*; + +/** + * 自营商城优惠券用户领取记录 + */ +@Data +@Entity +public class SelfCouponUser { + @Id() + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long couponUserId; //优惠券用户id + @Column + private String failureTime; //失效时间 + @Column + private Integer status; //状态(1未使用 2已使用 3已过期) + @Column + private String createTime; //创建时间 + /**优惠券信息*/ + @Column + private Long couponId; //优惠券id + @Column + private Integer type; //优惠券类型(1通用券 2商品券) + @Column + private String goodsIds; //商品id + @Column + private String couponName; //优惠券名称 + @Column + private String lessMoney; //优惠券面值 + @Column + private String minMoney; //优惠券最低消费 + @Transient + private SelfCoupon coupon; //优惠券实体 + /**优惠券发布信息*/ + @Column + private Long couponIssueId; //优惠券发布id + /**用户信息*/ + @Column + private Long userId; //用户id + @Column + private String nickName; //用户昵称 +} diff --git a/src/main/java/com/sqx/modules/coupon/respository/SelfCouponIssueJpaRepository.java b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponIssueJpaRepository.java new file mode 100644 index 0000000..894dfc3 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponIssueJpaRepository.java @@ -0,0 +1,25 @@ +package com.sqx.modules.coupon.respository; + + +import com.sqx.modules.coupon.entity.SelfCouponIssue; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SelfCouponIssueJpaRepository extends JpaRepository { + + //分页查询 + Page findAll(Pageable pageable); + + //条件查询 + Page findAll(Specification specification, Pageable pageable); + + //领券列表 + List findAll(Specification specification); + +} diff --git a/src/main/java/com/sqx/modules/coupon/respository/SelfCouponIssueRepository.java b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponIssueRepository.java new file mode 100644 index 0000000..1b72c64 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponIssueRepository.java @@ -0,0 +1,9 @@ +package com.sqx.modules.coupon.respository; + + +import com.sqx.modules.coupon.entity.SelfCouponIssue; +import org.springframework.data.repository.Repository; + +public interface SelfCouponIssueRepository extends Repository { + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/coupon/respository/SelfCouponJpaRepository.java b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponJpaRepository.java new file mode 100644 index 0000000..34c78f4 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponJpaRepository.java @@ -0,0 +1,20 @@ +package com.sqx.modules.coupon.respository; + + +import com.sqx.modules.coupon.entity.SelfCoupon; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SelfCouponJpaRepository extends JpaRepository { + + //分页查询 + Page findAll(Pageable pageable); + + //条件查询 + Page findAll(Specification specification, Pageable pageable); + +} diff --git a/src/main/java/com/sqx/modules/coupon/respository/SelfCouponRepository.java b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponRepository.java new file mode 100644 index 0000000..1beeaf8 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponRepository.java @@ -0,0 +1,9 @@ +package com.sqx.modules.coupon.respository; + + +import com.sqx.modules.coupon.entity.SelfCoupon; +import org.springframework.data.repository.Repository; + +public interface SelfCouponRepository extends Repository { + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/coupon/respository/SelfCouponUserJpaRepository.java b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponUserJpaRepository.java new file mode 100644 index 0000000..ec2e1c8 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponUserJpaRepository.java @@ -0,0 +1,54 @@ +package com.sqx.modules.coupon.respository; + + +import com.sqx.modules.coupon.entity.SelfCouponUser; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Repository +public interface SelfCouponUserJpaRepository extends JpaRepository { + + //分页查询 + Page findAll(Pageable pageable); + + //条件查询 + Page findAll(Specification specification, Pageable pageable); + + List findAll(Specification specification); + + List findByUserIdAndCouponIssueId(Long userId, Long couponIssueId); + + //查询用户的优惠券 + @Query(value = "from SelfCouponUser s where s.userId=:userId") + List findAllByUserId(@Param("userId") Long userId); + + //查询用户通用券 + @Query(value = "from SelfCouponUser s where s.userId=:userId and s.status=1 and s.type = 1 ") + List findAllByUSerIdAndType1(@Param("userId") Long userId); + + //优惠券被使用 + @Modifying + @Transactional + @Query(value = "update SelfCouponUser s set s.status=2 where s.couponUserId=:couponUserId") + Integer usedCoupon(@Param("couponUserId") Long couponUserId); + + //优惠券退还 + @Modifying + @Transactional + @Query(value = "update SelfCouponUser s set s.status=1 where s.couponUserId=:couponUserId") + Integer backCoupon(@Param("couponUserId") Long couponUserId); + + //查询用户通用券 + @Query(value = "select count(s.userId) from SelfCouponUser s where s.userId=:userId and s.couponName=:couponName ") + int checkGetCoupon(@Param("userId") Long userId, @Param("couponName") String couponName); + +} diff --git a/src/main/java/com/sqx/modules/coupon/respository/SelfCouponUserRepository.java b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponUserRepository.java new file mode 100644 index 0000000..0c6a6ba --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/respository/SelfCouponUserRepository.java @@ -0,0 +1,9 @@ +package com.sqx.modules.coupon.respository; + + +import com.sqx.modules.coupon.entity.SelfCouponUser; +import org.springframework.data.repository.Repository; + +public interface SelfCouponUserRepository extends Repository { + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/coupon/service/SelfCouponIssueService.java b/src/main/java/com/sqx/modules/coupon/service/SelfCouponIssueService.java new file mode 100644 index 0000000..511b493 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/service/SelfCouponIssueService.java @@ -0,0 +1,26 @@ +package com.sqx.modules.coupon.service; + + +import com.sqx.modules.coupon.entity.SelfCouponIssue; +import com.sqx.modules.coupon.utils.Result; + +public interface SelfCouponIssueService { + //列表 + Result findAll(Integer page, Integer size); + + //用户端 + Result useList(Long goodsId, Long userId); + + //查询 + Result findOne(Long id); + + //删除 + Result delete(Long id); + + //添加 + Result saveBody(SelfCouponIssue entity); + + //修改 + Result updateBody(SelfCouponIssue entity); + +} diff --git a/src/main/java/com/sqx/modules/coupon/service/SelfCouponIssueServiceImpl.java b/src/main/java/com/sqx/modules/coupon/service/SelfCouponIssueServiceImpl.java new file mode 100644 index 0000000..d2be8d5 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/service/SelfCouponIssueServiceImpl.java @@ -0,0 +1,113 @@ +package com.sqx.modules.coupon.service; + +import com.sqx.modules.chats.utils.DateUtil; +import com.sqx.modules.coupon.entity.SelfCoupon; +import com.sqx.modules.coupon.entity.SelfCouponIssue; +import com.sqx.modules.coupon.entity.SelfCouponUser; +import com.sqx.modules.coupon.respository.SelfCouponIssueJpaRepository; +import com.sqx.modules.coupon.respository.SelfCouponJpaRepository; +import com.sqx.modules.coupon.respository.SelfCouponUserJpaRepository; +import com.sqx.modules.coupon.utils.Result; +import com.sqx.modules.coupon.utils.ResultUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.ArrayList; +import java.util.List; + +@Service +public class SelfCouponIssueServiceImpl implements SelfCouponIssueService { + @Autowired + private SelfCouponIssueJpaRepository jpaRepository; + @Autowired + private SelfCouponUserJpaRepository couponUserJpaRepository; + @Autowired + private SelfCouponJpaRepository couponJpaRepository; + + @Override + public Result findAll(Integer page, Integer size) { + Pageable pageable = PageRequest.of(page, size); + return ResultUtil.success(jpaRepository.findAll(pageable)); + } + + /** + * 用户可领取的优惠券列表 + * @param goodsId + * @param userId + * @return + */ + @Override + public Result useList(Long goodsId, Long userId) { + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + if (goodsId != null) { + predicateList.add(criteriaBuilder.like(root.get("goodsIds"), "%"+goodsId+"%")); + } + String nowTime = DateUtil.createTime(); + predicateList.add(criteriaBuilder.lessThan(root.get("startTime"), nowTime)); + predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("endTime"), nowTime)); + predicateList.add(criteriaBuilder.equal(root.get("status"), 1)); + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + List list = jpaRepository.findAll(queryCondition); + List couponUserList = couponUserJpaRepository.findAllByUserId(userId); //用户领券信息 + List couponList = couponJpaRepository.findAll(); //优惠券信息:金额 + //筛选可领取的券 + for (SelfCouponIssue c : list) { + //1.剩余数量 + if (c.getRemainNumber() == 0){ //剩余数量为空 + list.remove(c); + break; + } + for (SelfCoupon s : couponList) { + if (c.getCouponId().equals(s.getCouponId())){ + c.setCoupon(s); + break; + } + } + //2.领取限制 + c.setGetStatus(1); //领取状态(1可领取 2已领取) + for (SelfCouponUser u : couponUserList) { + if (u.getCouponIssueId()!=null){ + if (u.getCouponIssueId().equals(c.getCouponIssueId()) && c.getIsLimit() == 1){ //判断是否已领取且券为限领 + c.setGetStatus(2); + break; + } + } + } + } + return ResultUtil.success(list); + } + + @Override + public Result saveBody(SelfCouponIssue entity) { + entity.setCreateTime(DateUtil.createTime()); + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result updateBody(SelfCouponIssue entity) { + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result findOne(Long id) { + return ResultUtil.success(jpaRepository.findById(id).orElse(null)); + } + + @Override + public Result delete(Long id) { + jpaRepository.deleteById(id); + return ResultUtil.success(); + } +} diff --git a/src/main/java/com/sqx/modules/coupon/service/SelfCouponService.java b/src/main/java/com/sqx/modules/coupon/service/SelfCouponService.java new file mode 100644 index 0000000..89c0ce2 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/service/SelfCouponService.java @@ -0,0 +1,22 @@ +package com.sqx.modules.coupon.service; + +import com.sqx.modules.coupon.entity.SelfCoupon; +import com.sqx.modules.coupon.utils.Result; + +public interface SelfCouponService { + //列表 + Result findAll(Integer page, Integer size); + + //查询 + Result findOne(Long id); + + //删除 + Result delete(Long id); + + //添加 + Result saveBody(SelfCoupon entity); + + //修改 + Result updateBody(SelfCoupon entity); + +} diff --git a/src/main/java/com/sqx/modules/coupon/service/SelfCouponServiceImpl.java b/src/main/java/com/sqx/modules/coupon/service/SelfCouponServiceImpl.java new file mode 100644 index 0000000..59bb04e --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/service/SelfCouponServiceImpl.java @@ -0,0 +1,47 @@ +package com.sqx.modules.coupon.service; + +import com.sqx.modules.chats.utils.DateUtil; +import com.sqx.modules.coupon.entity.SelfCoupon; +import com.sqx.modules.coupon.respository.SelfCouponJpaRepository; +import com.sqx.modules.coupon.utils.Result; +import com.sqx.modules.coupon.utils.ResultUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +@Service +public class SelfCouponServiceImpl implements SelfCouponService { + @Autowired + private SelfCouponJpaRepository jpaRepository; + + @Override + public Result findAll(Integer page, Integer size) { + Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "sort"))); + return ResultUtil.success(jpaRepository.findAll(pageable)); + } + + + @Override + public Result saveBody(SelfCoupon entity) { + entity.setCreateTime(DateUtil.createTime()); + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result updateBody(SelfCoupon entity) { + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result findOne(Long id) { + return ResultUtil.success(jpaRepository.findById(id).orElse(null)); + } + + @Override + public Result delete(Long id) { + jpaRepository.deleteById(id); + return ResultUtil.success(); + } +} diff --git a/src/main/java/com/sqx/modules/coupon/service/SelfCouponUserService.java b/src/main/java/com/sqx/modules/coupon/service/SelfCouponUserService.java new file mode 100644 index 0000000..e56ac62 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/service/SelfCouponUserService.java @@ -0,0 +1,31 @@ +package com.sqx.modules.coupon.service; + +import com.sqx.modules.coupon.entity.SelfCouponUser; +import com.sqx.modules.coupon.utils.Result; + +import java.math.BigDecimal; + +public interface SelfCouponUserService { + //列表 + Result findAll(Integer page, Integer size, String couponName,String nickName); + + //用户端优惠券列表 + Result userList(Integer page, Integer size, Long userId, String goodsId, Integer type, BigDecimal money,Integer status); + + Result useList(Long userId, String goodsId); + + //查询 + Result findOne(Long id); + + //删除 + Result delete(Long id); + + //添加 + Result saveBody(SelfCouponUser entity); + + //修改 + Result updateBody(SelfCouponUser entity); + + Result sendUserCoupon(String userIds,String couponIds,Integer type); + +} diff --git a/src/main/java/com/sqx/modules/coupon/service/SelfCouponUserServiceImpl.java b/src/main/java/com/sqx/modules/coupon/service/SelfCouponUserServiceImpl.java new file mode 100644 index 0000000..6f42b30 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/service/SelfCouponUserServiceImpl.java @@ -0,0 +1,215 @@ +package com.sqx.modules.coupon.service; + +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.coupon.entity.SelfCoupon; +import com.sqx.modules.coupon.entity.SelfCouponIssue; +import com.sqx.modules.coupon.entity.SelfCouponUser; +import com.sqx.modules.coupon.respository.SelfCouponIssueJpaRepository; +import com.sqx.modules.coupon.respository.SelfCouponJpaRepository; +import com.sqx.modules.coupon.respository.SelfCouponUserJpaRepository; +import com.sqx.modules.coupon.utils.DateUtil; +import com.sqx.modules.coupon.utils.Result; +import com.sqx.modules.coupon.utils.ResultUtil; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Service +public class SelfCouponUserServiceImpl implements SelfCouponUserService { + @Autowired + private SelfCouponUserJpaRepository jpaRepository; + @Autowired + private SelfCouponIssueJpaRepository couponIssueJpaRepository; + @Autowired + private SelfCouponJpaRepository couponJpaRepository; + @Autowired + private UserService userService; + + @Override + public Result findAll(Integer page, Integer size, String couponName,String nickName) { + Pageable pageable = PageRequest.of(page, size); + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + if (StringUtils.isNotEmpty(couponName)) { + predicateList.add(criteriaBuilder.equal(root.get("couponName"), couponName)); + } + if (StringUtils.isNotEmpty(nickName)) { + predicateList.add(criteriaBuilder.equal(root.get("nickName"), nickName)); + } + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + Page all = jpaRepository.findAll(queryCondition, pageable); + return ResultUtil.success(all); + } + + /** + * 用户优惠券列表 + */ + @Override + public Result userList(Integer page, Integer size, Long userId, String goodsId, Integer type, BigDecimal money,Integer status) { + Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime"))); + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + predicateList.add(criteriaBuilder.equal(root.get("userId"), userId)); + if (StringUtils.isNotEmpty(goodsId)) { + predicateList.add(criteriaBuilder.like(root.get("goodsIds"), "%"+goodsId+"%")); + } + if (type!=null && type != 0) { + predicateList.add(criteriaBuilder.equal(root.get("type"), type)); + } + if(money!=null){ + predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("minMoney"),money)); + } + if(status!=null){ + predicateList.add(criteriaBuilder.equal(root.get("status"), status)); + } + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + Page all = jpaRepository.findAll(queryCondition, pageable); + return ResultUtil.success(all); + } + + /** + * 用户优惠券使用列表 + */ + @Override + public Result useList(Long userId, String goodsId) { + Specification queryCondition = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { + List predicateList = new ArrayList<>(); + predicateList.add(criteriaBuilder.equal(root.get("userId"), userId)); + if (StringUtils.isNotEmpty(goodsId)) { + predicateList.add(criteriaBuilder.like(root.get("goodsIds"), "%"+goodsId+"%")); + } + predicateList.add(criteriaBuilder.equal(root.get("status"), 1)); //未使用 + return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); + } + }; + List list = jpaRepository.findAll(queryCondition); + return ResultUtil.success(list); + } + + @Override + public Result sendUserCoupon(String userIds,String couponIds,Integer type) { + if(type==1){ + for(String sCouponId:couponIds.split(",")){ + Long couponId=Long.parseLong(sCouponId); + SelfCoupon selfCoupon = couponJpaRepository.findById(couponId).orElse(null); + for(String sUserId:userIds.split(",")){ + Long userId=Long.parseLong(sUserId); + SelfCouponUser selfCouponUser=new SelfCouponUser(); + selfCouponUser.setStatus(1); + String time = DateUtil.createTime(); + selfCouponUser.setCreateTime(time); + Integer days = selfCoupon.getValidDay(); + selfCouponUser.setFailureTime(DateUtil.addDays(time, days)); + selfCouponUser.setCouponId(selfCoupon.getCouponId()); + selfCouponUser.setCouponName(selfCoupon.getCouponName()); + selfCouponUser.setLessMoney(selfCoupon.getLessMoney()); + selfCouponUser.setMinMoney(selfCoupon.getMinMoney()); + UserEntity userEntity = userService.selectUserById(userId); + selfCouponUser.setNickName(userEntity.getUserName()); + selfCouponUser.setType(selfCoupon.getType()); + selfCouponUser.setUserId(userId); + jpaRepository.save(selfCouponUser); + } + } + }else{ + send(couponIds); + } + return ResultUtil.success(); + } + + @Async + public void send(String couponIds){ + List list = userService.list(); + for(UserEntity user:list){ + Long userId=user.getUserId(); + for(String sCouponId:couponIds.split(",")){ + Long couponId=Long.parseLong(sCouponId); + SelfCoupon selfCoupon = couponJpaRepository.findById(couponId).orElse(null); + SelfCouponUser selfCouponUser=new SelfCouponUser(); + selfCouponUser.setStatus(1); + String time = DateUtil.createTime(); + selfCouponUser.setCreateTime(time); + Integer days = selfCoupon.getValidDay(); + selfCouponUser.setFailureTime(DateUtil.addDays(time, days)); + selfCouponUser.setCouponId(selfCoupon.getCouponId()); + selfCouponUser.setCouponName(selfCoupon.getCouponName()); + selfCouponUser.setLessMoney(selfCoupon.getLessMoney()); + selfCouponUser.setMinMoney(selfCoupon.getMinMoney()); + UserEntity userEntity = userService.selectUserById(userId); + selfCouponUser.setNickName(userEntity.getUserName()); + selfCouponUser.setType(selfCoupon.getType()); + selfCouponUser.setUserId(userId); + jpaRepository.save(selfCouponUser); + } + } + } + + /** + * 领取优惠券 + * @param entity + * @return + */ + @Override + public Result saveBody(SelfCouponUser entity) { + SelfCouponIssue couponIssue = couponIssueJpaRepository.findById(entity.getCouponIssueId()).orElse(null); + if (couponIssue.getRemainNumber() < 1){ + return ResultUtil.error(-1, "优惠券领取完了"); + } + String time = DateUtil.createTime(); + entity.setCreateTime(time); //创建时间 + entity.setStatus(1); //状态(1未使用 2已使用 3已过期) + //失效时间 + SelfCoupon coupon = couponJpaRepository.findById(entity.getCouponId()).orElse(null); + Integer days = coupon.getValidDay(); + entity.setFailureTime(DateUtil.addDays(time, days)); + entity.setGoodsIds(coupon.getGoodsIds()); //商品id + //优惠券剩余数量-1 + couponIssue.setRemainNumber(couponIssue.getRemainNumber()-1); + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result updateBody(SelfCouponUser entity) { + return ResultUtil.success(jpaRepository.save(entity)); + } + + @Override + public Result findOne(Long id) { + return ResultUtil.success(jpaRepository.findById(id).orElse(null)); + } + + @Override + public Result delete(Long id) { + jpaRepository.deleteById(id); + return ResultUtil.success(); + } + + + + +} diff --git a/src/main/java/com/sqx/modules/coupon/utils/DateUtil.java b/src/main/java/com/sqx/modules/coupon/utils/DateUtil.java new file mode 100644 index 0000000..585da14 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/utils/DateUtil.java @@ -0,0 +1,529 @@ +package com.sqx.modules.coupon.utils; + +import org.apache.commons.lang3.StringUtils; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +public class DateUtil { + /** + * 判断是否是购物节日期 + * @param date + * @return true 是 + */ + public static boolean isShoppingFestival(Date date){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + int month = calendar.get(Calendar.MONTH)+1; + int day = calendar.get(Calendar.DAY_OF_MONTH); + + //判断是否是双十一 + if(month==11 && day==11){ + return true; + } + + //判断是否是双十二 + if(month==12 && day==12){ + return true; + } + + return false; + } + + /** + * 获取两个日期之间左右年月 + * @param minDate + * @param maxDate + * @return + * @throws ParseException + */ + public static List getMonthBetween(Date minDate, Date maxDate) throws ParseException { + ArrayList result = new ArrayList(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月 + + Calendar min = Calendar.getInstance(); + Calendar max = Calendar.getInstance(); + + min.setTime(minDate); + min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); + + max.setTime(maxDate); + max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); + + Calendar curr = min; + while (curr.before(max)) { + result.add(sdf.format(curr.getTime())); + curr.add(Calendar.MONTH, 1); + } + + return result; + } + + /** + * 获取指定月份天数 + * @param year 年份(四位数) + * @param month 月份(从1开始) + * @return + */ + public static int getMonthDays(int year, int month) { + if (month == 2) { + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { + return 29; + } else { + return 28; + } + } else if (month == 4 || month == 6 || month == 9 || month == 11) { + return 30; + } else { + return 31; + } + } + + /** + * 判断时间是否在时间段内 + * + * @param date + * 当前时间 yyyy-MM-dd HH:mm:ss + * @param strDateBegin + * 开始时间 00:00 + * @param strDateEnd + * 结束时间 00:05 + * @return 在时间段内返回true + */ + public static boolean isInDate(Date date, String strDateBegin, String strDateEnd) { + + if(date==null || StringUtils.isBlank(strDateBegin) || StringUtils.isBlank(strDateEnd)){ + return false; + } + + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); + String strDate = sdf.format(date); + // 截取当前时间时分秒 + int strDateH = Integer.parseInt(strDate.substring(0, 2)); + int strDateM = Integer.parseInt(strDate.substring(3, 5)); + // 截取开始时间时分秒 + int strDateBeginH = Integer.parseInt(strDateBegin.substring(0, 2)); + int strDateBeginM = Integer.parseInt(strDateBegin.substring(3, 5)); + // 截取结束时间时分秒 + int strDateEndH = Integer.parseInt(strDateEnd.substring(0, 2)); + int strDateEndM = Integer.parseInt(strDateEnd.substring(3, 5)); + + if(strDateH >= strDateBeginH && strDateH <= strDateEndH){ + + //判断开始时间和结束时间的小时是否一样 + if(strDateBeginH == strDateEndH){ //是 + + // + if(strDateH == strDateBeginH){ + if(strDateM >= strDateBeginM && strDateM <= strDateEndM){ + return true; + } + }else{ + return false; + } + + }else{ //否 + + if(strDateH == strDateBeginH){ + + if(strDateM >= strDateBeginM){ + return true; + }else{ + return false; + } + + }else if(strDateH == strDateEndH){ + + if(strDateM <= strDateEndM){ + return true; + }else{ + return false; + } + + }else{ + return true; + } + + } + }else{ + return false; + } + + return false; + } + /** + * + * @param pattern,字符串的format格式,例如:yyyy-MM-dd HH:mm:ss + * @param date,需要转换为指定格式的日期对象 + * @return + */ + public static String getFormatStrByPatternAndDate(String pattern,Date date){ + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); + return simpleDateFormat.format(date); + } + public static Date getDataByFormatString(String pattern,String dateFormatStr){ + try { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); + return simpleDateFormat.parse(dateFormatStr); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + + /** + * 将日期的时分秒转为 00:00:00 + * @param date + * @return + * @throws + */ + public static Date lowDate(Date date){ + String lowDate = getFormatStrByPatternAndDate("yyyy-MM-dd",date) + " 00:00:00"; + return getDataByFormatString("yyyy-MM-dd HH:mm:ss",lowDate); + } + + /** + * 将日期的时分秒转为 23:59:59 + * @param date + * @return + * @throws ParseException + */ + public static Date hightDate(Date date){ + String lowDate = getFormatStrByPatternAndDate("yyyy-MM-dd",date) + " 23:59:59"; + return getDataByFormatString("yyyy-MM-dd HH:mm:ss",lowDate); + } + + /** + * 计算d1 到 d2 相差多少时间 + * @param d1 未来的时间 + * @param d2 现在的时间 + * @return 数组下标 0 天 1 时 2 分 3 秒 + */ + public static long[] dateDiff(Date d1, Date d2) throws ParseException { + long nd = 1000*24*60*60;//一天的毫秒数 + long nh = 1000*60*60;//一小时的毫秒数 + long nm = 1000*60;//一分钟的毫秒数 + long ns = 1000;//一秒钟的毫秒数 + //获得两个时间的毫秒时间差异 + long diff = d1.getTime() - d2.getTime(); + long day = diff/nd;//计算差多少天 + long hour = diff%nd/nh;//计算差多少小时 + long min = diff%nd%nh/nm;//计算差多少分钟 + long sec = diff%nd%nh%nm/ns;//计算差多少秒 + return new long[]{day,hour,min,sec}; + } + + /** + * 判断 start 是否大于 end + * @param start + * @param end + * @return + * @throws ParseException + */ + public static boolean startThanEnd(Date start, Date end) throws ParseException{ + long[] result = dateDiff(start, end); + if(result[0]>=0 && result[1]>=0 && result[2]>=0 && result[3]>=0){ + return true; + } + return false; + } + + /** + * 获取指定日期指定分钟后的日期 + * @param date + * @param minute + * @return + */ + public static Date getLaterMinute(Date date, Long minute) { + minute = minute == null ? 0 : minute; + long curren = date.getTime(); + curren += minute * 60 * 1000; + return new Date(curren); + } + + /** + * 获取指定日期指定分钟前的日期 + * @param date + * @param minute + * @return + */ + public static Date getPreviouslyMinute(Date date, Long minute) { + minute = minute == null ? 0 : minute; + long curren = date.getTime(); + curren -= minute * 60 * 1000; + return new Date(curren); + } + + /** + * 获取指定日期指定天数后的日期 + * @param date 指定的时间 + * @param later 指定的天数 + * @return + */ + public static Date getLaterDay(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current + later * 24 * 60 * 60 * 1000); + } + + + /** + * 获取指定日期指定天数前的日期 + * @param date 指定的时间 + * @param later 指定的天数 + * @return + */ + public static Date getPreviouslyDay(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current - later * 24 * 60 * 60 * 1000); + } + + /** + * 获取指定日期指定小时后的日期 + * @param date 指定的时间 + * @param later 指定的小时 + * @return + */ + public static Date getLaterHour(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current + later * 60 * 60 * 1000); + } + + /** + * 获取指定日期指定小时前的日期 + * @param date 指定的时间 + * @param later 指定的小时 + * @return + */ + public static Date getPreviouslyHour(Date date, Long later){ + later = later == null ? 0 : later; + long current = date.getTime(); + return new Date(current - later * 60 * 60 * 1000); + } + + /** + * 得到本周周一 + * @return + */ + public static Date getMondayOfWeek() { + Calendar c = Calendar.getInstance(); + int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1; + if (day_of_week == 0){ + day_of_week = 7; + } + c.add(Calendar.DATE, -day_of_week + 1); + return c.getTime(); + } + + /** + * 得到本周周日 + * @return + */ + public static Date getSundayOfWeek() { + Calendar c = Calendar.getInstance(); + int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1; + if (day_of_week == 0){ + day_of_week = 7; + } + c.add(Calendar.DATE, -day_of_week + 7); + return c.getTime(); + } + + /** + * 获取当前月的第一天 + * @return + */ + public static Date getFirstDayOfMonth(){ + Calendar c = Calendar.getInstance(); + c.add(Calendar.MONTH, 0); + c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 + return c.getTime(); + } + + /** + * 获取当前月的最后一天 + * @return + */ + public static Date getLastDayOfMonth(){ + Calendar ca = Calendar.getInstance(); + ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); + return ca.getTime(); + } + + /** + * 获取上一个月的第一天 + * @return + */ + public static Date getFirstDayOfPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -1); + calendar.set(Calendar.DAY_OF_MONTH,1); + return calendar.getTime(); + } + + /** + * 获取上一个月的最后一天 + * @return + */ + public static Date getLastDayOfPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DAY_OF_MONTH, 0); + return calendar.getTime(); + } + + /** + * 获取上上一个月的第一天 + * @return + */ + public static Date getFirstDayOfPPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -2); + calendar.set(Calendar.DAY_OF_MONTH,1); + return calendar.getTime(); + } + + /** + * 获取上上一个月的最后一天 + * @return + */ + public static Date getLastDayOfPPreviouslyMonth(){ + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -1); + calendar.set(Calendar.DAY_OF_MONTH, 0); + return calendar.getTime(); + } + + /** + * 获取指定日期是星期几 + * @param date + * @return + */ + public static int getDayOfWeek(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + //一周第一天是否为星期天 + boolean isFirstSunday = (cal.getFirstDayOfWeek() == Calendar.SUNDAY); + //获取周几 + int weekDay = cal.get(Calendar.DAY_OF_WEEK); + //若一周第一天为星期天,则-1 + if (isFirstSunday) { + weekDay = weekDay - 1; + if (weekDay == 0) { + weekDay = 7; + } + } + return weekDay; + } + + /** + * 获取创建时间 + * @return + */ + public static String createTime() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + } + + /** + * 获取创建时间 + * @return + */ + public static String createDate() { + return new SimpleDateFormat("yyyy-MM-dd").format(new Date()); + } + + /** + * 结束时间 + * @return + */ + public static String endTime(Integer hours) { + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = DateUtils.addHours(new Date(), hours); + return sf.format(date); + } + + /** + * 结束时间 + * @param days 日期 + * @return + */ + public static String addDays(String nowTime, Integer days) { + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try{ + Date date = DateUtils.addDays(sf.parse(nowTime), days); + return sf.format(date); + }catch (Exception e){ + e.printStackTrace(); + return null; + } + } + + //判断是否在规定的时间内签到 nowTime 当前时间 beginTime规定开始时间 endTime规定结束时间 + public static boolean betweenStratEndTime(String startTime, String endTime) throws Exception{ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String now = sf.format(new Date()); + //设置当前时间 + Calendar date = Calendar.getInstance(); + date.setTime(sf.parse(now)); + //设置开始时间 + Calendar start = Calendar.getInstance(); + start.setTime(sf.parse(startTime));//开始时间 + //设置结束时间 + Calendar end = Calendar.getInstance(); + start.setTime(sf.parse(endTime));//开始时间 + //处于开始时间之后,和结束时间之前的判断 + + if ((start.after(date) && end.before(date))) { + return true; + } else { + return false; + } + } + + /** + * 获取当前日期的几天前/后的日期:传入-1为一天前 + * @return + */ + public static String getBeforeDay(int num){ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.DATE, num); + return sf.format(cal.getTime()); + } + + /** + * 获取当前日期的几月前/后的日期:传入-1为上月 + * @return + */ + public static String getBeforeMonth(int num){ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM"); + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.MONTH, num); + return sf.format(cal.getTime()); + } + + /** + * 是否开始 + * @param startTime 开始时间 + * @return true 已开始 + */ + public static boolean isStart(String startTime){ + try{ + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date f = sf.parse(startTime); + return f.before(new Date()); + }catch (Exception e){ + e.printStackTrace(); + } + return true; + } + + +} diff --git a/src/main/java/com/sqx/modules/coupon/utils/DateUtils.java b/src/main/java/com/sqx/modules/coupon/utils/DateUtils.java new file mode 100644 index 0000000..3810159 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/utils/DateUtils.java @@ -0,0 +1,253 @@ +package com.sqx.modules.coupon.utils; + +import org.apache.commons.lang3.time.DateFormatUtils; + +import java.lang.management.ManagementFactory; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * 时间工具类 + * + */ +public class DateUtils extends org.apache.commons.lang3.time.DateUtils +{ + public static String YYYY = "yyyy"; + + public static String YYYY_MM = "yyyy-MM"; + + public static String YYYY_MM_DD = "yyyy-MM-dd"; + + public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; + + public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + + private static String[] parsePatterns = { + "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", + "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", + "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; + + /** + * 获取当前Date型日期 + * + * @return Date() 当前日期 + */ + public static Date getNowDate() + { + return new Date(); + } + + /** + * 获取当前日期, 默认格式为yyyy-MM-dd + * + * @return String + */ + public static String getDate() + { + return dateTimeNow(YYYY_MM_DD); + } + + public static final String getTime() + { + return dateTimeNow(YYYY_MM_DD_HH_MM_SS); + } + + public static final String dateTimeNow() + { + return dateTimeNow(YYYYMMDDHHMMSS); + } + + public static final String dateTimeNow(final String format) + { + return parseDateToStr(format, new Date()); + } + + public static final String dateTime(final Date date) + { + return parseDateToStr(YYYY_MM_DD, date); + } + + public static final String parseDateToStr(final String format, final Date date) + { + return new SimpleDateFormat(format).format(date); + } + + public static final Date dateTime(final String format, final String ts) + { + try + { + return new SimpleDateFormat(format).parse(ts); + } + catch (ParseException e) + { + throw new RuntimeException(e); + } + } + + /** + * 日期路径 即年/月/日 如2018/08/08 + */ + public static final String datePath() + { + Date now = new Date(); + return DateFormatUtils.format(now, "yyyy/MM/dd"); + } + + /** + * 日期路径 即年/月/日 如20180808 + */ + public static final String dateTime() + { + Date now = new Date(); + return DateFormatUtils.format(now, "yyyyMMdd"); + } + + /** + * 日期型字符串转化为日期 格式 + */ + public static Date parseDate(Object str) + { + if (str == null) + { + return null; + } + try + { + return parseDate(str.toString(), parsePatterns); + } + catch (ParseException e) + { + return null; + } + } + + /** + * 获取服务器启动时间 + */ + public static Date getServerStartDate() + { + long time = ManagementFactory.getRuntimeMXBean().getStartTime(); + return new Date(time); + } + + /** + * 计算两个时间差 + */ + public static String getDatePoor(Date endDate, Date nowDate) + { + long nd = 1000 * 24 * 60 * 60; + long nh = 1000 * 60 * 60; + long nm = 1000 * 60; + // long ns = 1000; + // 获得两个时间的毫秒时间差异 + long diff = endDate.getTime() - nowDate.getTime(); + // 计算差多少天 + long day = diff / nd; + // 计算差多少小时 + long hour = diff % nd / nh; + // 计算差多少分钟 + long min = diff % nd % nh / nm; + // 计算差多少秒//输出结果 + // long sec = diff % nd % nh % nm / ns; + return day + "天" + hour + "小时" + min + "分钟"; + } + + /** + * 秒杀时间判断 + * @param startTime + * @param endTime + * @return + */ + public static String secKillTime(String startTime, String endTime){ + String s = ""; + SimpleDateFormat sf = new SimpleDateFormat(YYYY_MM_DD); + String nowTime = sf.format(new Date()); + try{ + long now = sf.parse(nowTime).getTime(); + long start = sf.parse(startTime).getTime(); + long end = sf.parse(endTime).getTime(); + if (now < start){ + s = "未开始"; + } else if (now >= start && now <= end) { + s = "进行中"; + }else{ + s = "已结束"; + } + }catch (Exception e){ + e.printStackTrace(); + } + return s; + } + + /** + * 用户端秒杀时段是否开始判断 + * @param startHours 整点开始 + * @return + */ + public static Integer secKillStartHours(Integer startHours, Integer nextHours){ + Integer result = 0; + String time = DateUtil.createTime().substring(11,13); + if (time.startsWith("0")){ + time = time.substring(1,2); + } + int now = Integer.parseInt(time); + int start = Integer.parseInt(startHours.toString()); + int end = Integer.parseInt(nextHours.toString()); + if (now < start){ + result = 3; //未开始 + } else if (now >= start && now < end) { + result = 2; //进行中 + }else{ + result = 1; //已结束 + } + return result; + } + + + /** + * 合同状态工具类 + * @param date 日期 + * @param years 年份 + * @return + */ + public static String getContractStatus(String date, String years){ + String status = "有效"; + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); + try{ + Date start = sf.parse(date); + Calendar c = Calendar.getInstance(); + c.setTime(start); + int year = Integer.parseInt(years); + c.add(Calendar.YEAR, + year); + start = c.getTime(); //得到过期时间 + long time = start.getTime(); + long now = new Date().getTime(); + if (time < now){ + status = "无效"; + } + }catch (Exception e){ + e.printStackTrace(); + } + return status; + } + + /** + * 是否过期 + * @param failureTime 过期时间 + * @return true 已过期 + */ + public static boolean checkTime(String failureTime){ + try{ + SimpleDateFormat sf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS); + Date f = sf.parse(failureTime); + return f.before(new Date()); + }catch (Exception e){ + e.printStackTrace(); + } + return true; + } + + +} diff --git a/src/main/java/com/sqx/modules/coupon/utils/DescribeException.java b/src/main/java/com/sqx/modules/coupon/utils/DescribeException.java new file mode 100644 index 0000000..777f422 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/utils/DescribeException.java @@ -0,0 +1,34 @@ +package com.sqx.modules.coupon.utils; + +public class DescribeException extends RuntimeException{ + + private Integer code; + + /** + * 继承exception,加入错误状态值 + * @param exceptionEnum + */ + public DescribeException(ExceptionEnum exceptionEnum) { + super(exceptionEnum.getMsg()); + this.code = exceptionEnum.getCode(); + } + + /** + * 自定义错误信息 + * @param message + * @param code + */ + public DescribeException(String message, Integer code) { + super(message); + this.code = code; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } +} + diff --git a/src/main/java/com/sqx/modules/coupon/utils/ExceptionEnum.java b/src/main/java/com/sqx/modules/coupon/utils/ExceptionEnum.java new file mode 100644 index 0000000..97d4c5d --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/utils/ExceptionEnum.java @@ -0,0 +1,49 @@ +package com.sqx.modules.coupon.utils; + +public enum ExceptionEnum { + UNKNOW_ERROR(-1, "未知错误"), + LIMIT_USER(-100, "当前账户受限制请联系管理员"), + USER_NOT_FIND(-101, "用户未注册"), + USER_IS_BIND_FOR_ANTHER_OPENID(-99, "当前手机号已经被其他微信绑定"), + WRONT_TOKEN(-102, "用户信息失效,请重新登录"), + USER_PWD_EMPTY(-103, "用户名密码不能为空"), + USER_PWD_ERROR(-104, "用户名或密码错误"), + USER_IS_EXITS(-105, "手机号已经注册!"), + ERROR(-106, "服务器内部错误"), + UPDATE_PWD_ERROR(-107, "密码修改失败"), + STATE_PWD_ERROR(-108, "状态修改失败"), + DATA_EMPTY(-109, "添加数据不能为空"), + Return_ATA_EMPTY(-110, "暂无数据"), + ADD_ERROR(-111, "提现失败"), + CODE_ERROR(-112, "验证码不正确"), + BIND_ERROR(-113, "手机号已经被其他账号绑定"), + SEND_ERROR(-114, "验证码发送失败"), + USER_PHONE_ERROR(-115, "用户名不能为空"), + OLD_PWD_ERROR(-116, "原始密码错误"), + IS_REGISTER(-117, "当前手机号已经绑定其他微信账号"), + IS_BIND(-118, "当前淘宝账号已经绑定其他手机号"), + IS_BIND_RELATION(-119, "当前账号已经绑定其他淘宝账号"), + OLD_NOT_SAME_NEW_PWD_ERROR(-120, "新密码不能等于和原始密码一致"), + USER_IS_REGISTER(-121, "用户已经注册请前往登录"), + RELATIONID_IS_REGISTER(-122, "淘宝账号已经授权绑定其他手机号"), + CODE_NOT_FOUND(-123, "邀请码不存在"), + COMMON_IS_EXITS(-124, "已经存在"), + COUPONS_ZERO(-125, "优惠券被领完了"), + COUPONS_GET_OUT(-126, "优惠券超过领取次数"), + COUPONS_TIME_OUT(-127, "优惠券已过期"); + private Integer code; + private String msg; + ExceptionEnum(Integer code, String msg) { + this.code = code; + this.msg = msg; + } + + public Integer getCode() { + return code; + } + + public String getMsg() { + return msg; + } +} + diff --git a/src/main/java/com/sqx/modules/coupon/utils/Result.java b/src/main/java/com/sqx/modules/coupon/utils/Result.java new file mode 100644 index 0000000..148145c --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/utils/Result.java @@ -0,0 +1,51 @@ +package com.sqx.modules.coupon.utils; + +public class Result { + + // error_code 状态值:0 极为成功,其他数值代表失败 + private Integer status; + + // error_msg 错误信息,若status为0时,为success + private String msg; + + // content 返回体报文的出参,使用泛型兼容不同的类型 + private T data; + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer code) { + this.status = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public T getData(Object object) { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public T getData() { + return data; + } + + @Override + public String toString() { + return "Result{" + + "status=" + status + + ", msg='" + msg + '\'' + + ", data=" + data + + '}'; + + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/coupon/utils/ResultUtil.java b/src/main/java/com/sqx/modules/coupon/utils/ResultUtil.java new file mode 100644 index 0000000..00328d6 --- /dev/null +++ b/src/main/java/com/sqx/modules/coupon/utils/ResultUtil.java @@ -0,0 +1,56 @@ +package com.sqx.modules.coupon.utils; + +public class ResultUtil { + + /** + * 返回成功,传入返回体具体出參 + * + * @param object + * @return + */ + public static Result success(Object object) { + Result result = new Result(); + result.setStatus(0); + result.setMsg("success"); + result.setData(object); + return result; + } + + /** + * 提供给部分不需要出參的接口 + * + * @return + */ + public static Result success() { + return success(null); + } + + /** + * 自定义错误信息 + * + * @param code + * @param msg + * @return + */ + public static Result error(Integer code, String msg) { + Result result = new Result(); + result.setStatus(code); + result.setMsg(msg); + result.setData(null); + return result; + } + + /** + * 返回异常信息,在已知的范围内 + * + * @param exceptionEnum + * @return + */ + public static Result error(ExceptionEnum exceptionEnum) { + Result result = new Result(); + result.setStatus(exceptionEnum.getCode()); + result.setMsg(exceptionEnum.getMsg()); + result.setData(null); + return result; + } +} diff --git a/src/main/java/com/sqx/modules/file/AliFileUploadController.java b/src/main/java/com/sqx/modules/file/AliFileUploadController.java new file mode 100644 index 0000000..e690632 --- /dev/null +++ b/src/main/java/com/sqx/modules/file/AliFileUploadController.java @@ -0,0 +1,253 @@ +package com.sqx.modules.file; + +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.sqx.common.utils.Result; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.file.utils.FileUploadUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.jaudiotagger.audio.AudioFileIO; +import org.jaudiotagger.audio.mp3.MP3AudioHeader; +import org.jaudiotagger.audio.mp3.MP3File; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 阿里云文件上传 + * @author fang + * @date 2020/7/13 + */ +@RestController +@Api(value = "阿里云文件上传", tags = {"阿里云文件上传"}) +@RequestMapping(value = "/alioss") +@Slf4j +public class AliFileUploadController { + + + private final CommonInfoService commonRepository; + + @Autowired + public AliFileUploadController(CommonInfoService commonRepository) { + this.commonRepository = commonRepository; + } + + @RequestMapping(value = "/upload", method = RequestMethod.POST) + @ApiOperation("文件上传") + @ResponseBody + public Result upload(@RequestParam("file") MultipartFile file){ + String value = commonRepository.findOne(234).getValue(); + if("1".equals(value)){ + // 创建OSSClient实例。 + OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue()); + String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".")); + // 上传文件流。 + InputStream inputStream = null; + try { + inputStream =new ByteArrayInputStream(file.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + String completePath=getPath(suffix); + ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream); + // 关闭OSSClient。 + ossClient.shutdown(); + // String src = commonRepository.findOne(72).getValue()+"/"+completePath; + String src = commonRepository.findOne(19).getValue()+"/img/"+completePath; + return Result.success().put("data",src); + }else{ + try + { + String http = commonRepository.findOne(19).getValue(); + String[] split = http.split("://"); + // 上传文件路径 + String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath"; + // 上传并返回新文件名称 + String fileName = FileUploadUtils.upload(filePath, file); + String url = http +fileName; + return Result.success().put("data",url); + } + catch (Exception e) + { + log.error("本地上传失败:"+e.getMessage(),e); + return Result.error(-100,"文件上传失败!"); + } + } + + } + + @RequestMapping(value = "/uploadUniApp", method = RequestMethod.POST) + @ApiOperation("文件上传") + @ResponseBody + public String uploadUniApp(@RequestParam("file") MultipartFile file){ + String value = commonRepository.findOne(234).getValue(); + if("1".equals(value)){ + // 创建OSSClient实例。 + OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue()); + String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".")); + // 上传文件流。 + InputStream inputStream = null; + try { + inputStream =new ByteArrayInputStream(file.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + String completePath=getPath(suffix); + ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream); + // 关闭OSSClient。 + ossClient.shutdown(); + return commonRepository.findOne(19).getValue()+"/img/"+completePath; + }else{ + try + { + String http = commonRepository.findOne(19).getValue(); + String[] split = http.split("://"); + // 上传文件路径 + String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath"; + // 上传并返回新文件名称 + String fileName = FileUploadUtils.upload(filePath, file); + String url = http +fileName; + return url; + } + catch (Exception e) + { + log.error("本地上传失败:"+e.getMessage(),e); + return null; + } + } + + } + + @RequestMapping(value = "/uploadMusic", method = RequestMethod.POST) + @ApiOperation("文件上传") + @ResponseBody + public Result uploadMusic(@RequestParam("file") MultipartFile file) { + String url=""; + String value = commonRepository.findOne(234).getValue(); + if("1".equals(value)){ + // 创建OSSClient实例。 + OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue()); + String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".")); + // 上传文件流。 + InputStream inputStream = null; + try { + inputStream =new ByteArrayInputStream(file.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + String completePath=getPath(suffix); + ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream); + // 关闭OSSClient。 + ossClient.shutdown(); + url = commonRepository.findOne(19).getValue()+"/img/"+completePath; + }else{ + try + { + String http = commonRepository.findOne(19).getValue(); + String[] split = http.split("://"); + // 上传文件路径 + String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath"; + // 上传并返回新文件名称 + String fileName = FileUploadUtils.upload(filePath, file); + url = http +fileName; + } + catch (Exception e) + { + log.error("本地上传失败:"+e.getMessage(),e); + return null; + } + } + if("/".equals(url.substring(url.length()-1,url.length()))){ + url=url.substring(0,url.length()-1); + } + int trackLength=0; + try { + File file1 = multipartFileToFile(file); + MP3File f = (MP3File) AudioFileIO.read(file1); + MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader(); + trackLength = audioHeader.getTrackLength(); + delteTempFile(file1); + } catch (Exception e) { + e.printStackTrace(); + } + Map result=new HashMap<>(); + result.put("url",url); + result.put("sec",trackLength); + return Result.success().put("data",result ); + } + + + /** + * MultipartFile 转 File + * + * @param file + * @throws Exception + */ + public static File multipartFileToFile(MultipartFile file) throws Exception { + + File toFile = null; + if (file.equals("") || file.getSize() <= 0) { + file = null; + } else { + InputStream ins = null; + ins = file.getInputStream(); + toFile = new File(file.getOriginalFilename()); + inputStreamToFile(ins, toFile); + ins.close(); + } + return toFile; + } + + //获取流文件 + private static void inputStreamToFile(InputStream ins, File file) { + try { + OutputStream os = new FileOutputStream(file); + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + } + os.close(); + ins.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 删除本地临时文件 + * @param file + */ + public static void delteTempFile(File file) { + if (file != null) { + File del = new File(file.toURI()); + del.delete(); + } + } + + private String getPath(String suffix) { + //生成uuid + String uuid = UUID.randomUUID().toString().replaceAll("-", ""); + //文件路径 + String path =format(new Date()) + "/" + uuid; + return path + suffix; + } + + + private String format(Date date) { + if(date != null){ + SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); + return df.format(date); + } + return null; + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/file/utils/DescribeException.java b/src/main/java/com/sqx/modules/file/utils/DescribeException.java new file mode 100644 index 0000000..8ad4cb8 --- /dev/null +++ b/src/main/java/com/sqx/modules/file/utils/DescribeException.java @@ -0,0 +1,34 @@ +package com.sqx.modules.file.utils; + +public class DescribeException extends RuntimeException{ + + private Integer code; + + /** + * 继承exception,加入错误状态值 + * @param exceptionEnum + */ + public DescribeException(ExceptionEnum exceptionEnum) { + super(exceptionEnum.getMsg()); + this.code = exceptionEnum.getCode(); + } + + /** + * 自定义错误信息 + * @param message + * @param code + */ + public DescribeException(String message, Integer code) { + super(message); + this.code = code; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } +} + diff --git a/src/main/java/com/sqx/modules/file/utils/ExceptionEnum.java b/src/main/java/com/sqx/modules/file/utils/ExceptionEnum.java new file mode 100644 index 0000000..d7750d2 --- /dev/null +++ b/src/main/java/com/sqx/modules/file/utils/ExceptionEnum.java @@ -0,0 +1,49 @@ +package com.sqx.modules.file.utils; + +public enum ExceptionEnum { + UNKNOW_ERROR(-1, "未知错误"), + LIMIT_USER(-100, "账号已经禁用,请联系管理员!"), + USER_NOT_FIND(-101, "用户未注册"), + USER_IS_BIND_FOR_ANTHER_OPENID(-99, "当前手机号已经被其他微信绑定"), + WRONT_TOKEN(-102, "用户信息失效,请重新登录"), + USER_PWD_EMPTY(-103, "用户名密码不能为空"), + USER_PWD_ERROR(-104, "用户名或密码错误"), + USER_IS_EXITS(-105, "手机号已经注册!"), + ERROR(-106, "服务器内部错误"), + UPDATE_PWD_ERROR(-107, "密码修改失败"), + STATE_PWD_ERROR(-108, "状态修改失败"), + DATA_EMPTY(-109, "添加数据不能为空"), + Return_ATA_EMPTY(-110, "暂无数据"), + ADD_ERROR(-111, "提现失败"), + CODE_ERROR(-112, "验证码不正确"), + BIND_ERROR(-113, "手机号已经被其他账号绑定"), + SEND_ERROR(-114, "验证码发送失败"), + USER_PHONE_ERROR(-115, "用户名不能为空"), + OLD_PWD_ERROR(-116, "原始密码错误"), + IS_REGISTER(-117, "当前手机号已经绑定其他微信账号"), + IS_BIND(-118, "当前淘宝账号已经绑定其他手机号"), + IS_BIND_RELATION(-119, "当前账号已经绑定其他淘宝账号"), + OLD_NOT_SAME_NEW_PWD_ERROR(-120, "新密码不能等于和原始密码一致"), + USER_IS_REGISTER(-121, "用户已经注册请前往登录"), + RELATIONID_IS_REGISTER(-122, "淘宝账号已经授权绑定其他手机号"), + CODE_NOT_FOUND(-123, "邀请码不存在"), + COMMON_IS_EXITS(-124, "已经存在"), + COUPONS_ZERO(-125, "优惠券被领完了"), + COUPONS_GET_OUT(-126, "优惠券超过领取次数"), + COUPONS_TIME_OUT(-127, "优惠券已过期"); + private Integer code; + private String msg; + ExceptionEnum(Integer code, String msg) { + this.code = code; + this.msg = msg; + } + + public Integer getCode() { + return code; + } + + public String getMsg() { + return msg; + } +} + diff --git a/src/main/java/com/sqx/modules/file/utils/FileUploadUtils.java b/src/main/java/com/sqx/modules/file/utils/FileUploadUtils.java new file mode 100644 index 0000000..87842ef --- /dev/null +++ b/src/main/java/com/sqx/modules/file/utils/FileUploadUtils.java @@ -0,0 +1,238 @@ +package com.sqx.modules.file.utils; + +import com.sqx.modules.common.service.CommonInfoService; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateFormatUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.util.Date; + +/** + * 文件上传工具类 + * + * @author ruoyi + */ +public class FileUploadUtils +{ + /** + * 默认大小 50M + */ + public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; + + /** + * 默认的文件名最大长度 100 + */ + public static final int DEFAULT_FILE_NAME_LENGTH = 100; + + private static int counter = 0; + + private static CommonInfoService commonRepository; + + @Autowired + public void setCommonRepository(CommonInfoService commonRepository) { + FileUploadUtils.commonRepository = commonRepository; + } + + public static String getDefaultBaseDir() + { + return commonRepository.findOne(19).getValue(); + } + + /** + * 以默认配置进行文件上传 + * + * @param file 上传的文件 + * @return 文件名称 + * @throws Exception + */ + public static final String upload(MultipartFile file) throws IOException + { + try + { + return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); + } + catch (Exception e) + { + throw new IOException(e.getMessage(), e); + } + } + + /** + * 根据文件路径上传 + * + * @param baseDir 相对应用的基目录 + * @param file 上传的文件 + * @return 文件名称 + * @throws IOException + */ + public static final String upload(String baseDir, MultipartFile file) throws IOException + { + try + { + return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); + } + catch (Exception e) + { + throw new IOException(e.getMessage(), e); + } + } + + /** + * 文件上传 + * + * @param baseDir 相对应用的基目录 + * @param file 上传的文件 + * @return 返回上传成功的文件名 + */ + public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) + throws DescribeException,IOException + { + int fileNamelength = file.getOriginalFilename().length(); + if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) + { + throw new DescribeException("文件名太长",-100); + } + + assertAllowed(file, allowedExtension); + + String fileName = extractFilename(file); + + File desc = getAbsoluteFile(baseDir, fileName); + file.transferTo(desc); + String pathFileName = getPathFileName(baseDir, fileName); + return pathFileName; + } + + /** + * 编码文件名 + */ + public static final String extractFilename(MultipartFile file) + { + String fileName = file.getOriginalFilename(); + String extension = getExtension(file); + fileName =datePath() + "/" + encodingFilename(fileName) + "." + extension; + return fileName; + } + + /** + * 日期路径 即年/月/日 如2018/08/08 + */ + public static final String datePath() + { + Date now = new Date(); + return DateFormatUtils.format(now, "yyyy/MM/dd"); + } + + + + private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException + { + File desc = new File(uploadDir + File.separator + fileName); + + if (!desc.getParentFile().exists()) + { + desc.getParentFile().mkdirs(); + } + if (!desc.exists()) + { + desc.createNewFile(); + } + return desc; + } + + private static final String getPathFileName(String uploadDir, String fileName) throws IOException + { + int dirLastIndex = uploadDir.lastIndexOf("/") + 1; + String currentDir = StringUtils.substring(uploadDir, dirLastIndex); + String pathFileName = "/file/" + currentDir + "/" + fileName; + return pathFileName; + } + + /** + * 编码文件名 + */ + private static final String encodingFilename(String fileName) + { + fileName = fileName.replace("_", " "); + fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++); + return fileName; + } + + /** + * 文件大小校验 + * + * @param file 上传的文件 + * @return + */ + public static final void assertAllowed(MultipartFile file, String[] allowedExtension) + throws DescribeException + { + long size = file.getSize(); + if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) + { + throw new DescribeException("文件太大",-100); + } + + String fileName = file.getOriginalFilename(); + String extension = getExtension(file); + if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) + { + if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) + { + throw new DescribeException("",-100); + } + else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) + { + throw new DescribeException("",-100); + } + else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) + { + throw new DescribeException("",-100); + } + else + { + throw new DescribeException("",-100); + } + } + + } + + /** + * 判断MIME类型是否是允许的MIME类型 + * + * @param extension + * @param allowedExtension + * @return + */ + public static final boolean isAllowedExtension(String extension, String[] allowedExtension) + { + for (String str : allowedExtension) + { + if (str.equalsIgnoreCase(extension)) + { + return true; + } + } + return false; + } + + /** + * 获取文件名的后缀 + * + * @param file 表单文件 + * @return 后缀名 + */ + public static final String getExtension(MultipartFile file) + { + String extension = FilenameUtils.getExtension(file.getOriginalFilename()); + if (StringUtils.isEmpty(extension)) + { + extension = MimeTypeUtils.getExtension(file.getContentType()); + } + return extension; + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/file/utils/FileUtils.java b/src/main/java/com/sqx/modules/file/utils/FileUtils.java new file mode 100644 index 0000000..b424a41 --- /dev/null +++ b/src/main/java/com/sqx/modules/file/utils/FileUtils.java @@ -0,0 +1,137 @@ +package com.sqx.modules.file.utils; + +import javax.servlet.http.HttpServletRequest; +import java.io.*; +import java.net.URLEncoder; + +/** + * 文件处理工具类 + * + * @author ruoyi + */ +public class FileUtils +{ + public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; + + /** + * 输出指定文件的byte数组 + * + * @param filePath 文件路径 + * @param os 输出流 + * @return + */ + public static void writeBytes(String filePath, OutputStream os) throws IOException + { + FileInputStream fis = null; + try + { + File file = new File(filePath); + if (!file.exists()) + { + throw new FileNotFoundException(filePath); + } + fis = new FileInputStream(file); + byte[] b = new byte[1024]; + int length; + while ((length = fis.read(b)) > 0) + { + os.write(b, 0, length); + } + } + catch (IOException e) + { + throw e; + } + finally + { + if (os != null) + { + try + { + os.close(); + } + catch (IOException e1) + { + e1.printStackTrace(); + } + } + if (fis != null) + { + try + { + fis.close(); + } + catch (IOException e1) + { + e1.printStackTrace(); + } + } + } + } + + /** + * 删除文件 + * + * @param filePath 文件 + * @return + */ + public static boolean deleteFile(String filePath) + { + boolean flag = false; + File file = new File(filePath); + // 路径为文件且不为空则进行删除 + if (file.isFile() && file.exists()) + { + file.delete(); + flag = true; + } + return flag; + } + + /** + * 文件名称验证 + * + * @param filename 文件名称 + * @return true 正常 false 非法 + */ + public static boolean isValidFilename(String filename) + { + return filename.matches(FILENAME_PATTERN); + } + + /** + * 下载文件名重新编码 + * + * @param request 请求对象 + * @param fileName 文件名 + * @return 编码后的文件名 + */ + public static String setFileDownloadHeader(HttpServletRequest request, String fileName) + throws UnsupportedEncodingException + { + final String agent = request.getHeader("USER-AGENT"); + String filename = fileName; + if (agent.contains("MSIE")) + { + // IE浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + filename = filename.replace("+", " "); + } + else if (agent.contains("Firefox")) + { + // 火狐浏览器 + filename = new String(fileName.getBytes(), "ISO8859-1"); + } + else if (agent.contains("Chrome")) + { + // google浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + } + else + { + // 其它浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + } + return filename; + } +} diff --git a/src/main/java/com/sqx/modules/file/utils/Md5Utils.java b/src/main/java/com/sqx/modules/file/utils/Md5Utils.java new file mode 100644 index 0000000..ac2b848 --- /dev/null +++ b/src/main/java/com/sqx/modules/file/utils/Md5Utils.java @@ -0,0 +1,140 @@ +package com.sqx.modules.file.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * Md5加密方法 + * + * @author ruoyi + */ +public class Md5Utils +{ + private static final Logger log = LoggerFactory.getLogger(Md5Utils.class); + + private static byte[] md5(String s) + { + MessageDigest algorithm; + try + { + algorithm = MessageDigest.getInstance("MD5"); + algorithm.reset(); + algorithm.update(s.getBytes("UTF-8")); + byte[] messageDigest = algorithm.digest(); + return messageDigest; + } + catch (Exception e) + { + log.error("MD5 Error...", e); + } + return null; + } + + private static final String toHex(byte hash[]) + { + if (hash == null) + { + return null; + } + StringBuffer buf = new StringBuffer(hash.length * 2); + int i; + + for (i = 0; i < hash.length; i++) + { + if ((hash[i] & 0xff) < 0x10) + { + buf.append("0"); + } + buf.append(Long.toString(hash[i] & 0xff, 16)); + } + return buf.toString(); + } + + public static String hash(String s) + { + try + { + return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8"); + } + catch (Exception e) + { + log.error("not supported charset...{}", e); + return s; + } + } + + public static String md5s(String plainText) { + StringBuffer buf = null; + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(plainText.getBytes()); + byte b[] = md.digest(); + int i; + buf = new StringBuffer(""); + for (int offset = 0; offset < b.length; offset++) { + i = b[offset]; + if (i < 0) + i += 256; + if (i < 16) + buf.append("0"); + buf.append(Integer.toHexString(i)); + } + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return buf.toString(); + } + + public static String encodeUrlString(String str, String charset) { + String strret = null; + if (str == null){ + return str; + } + try { + strret = java.net.URLEncoder.encode(str, charset); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + return strret; + } + + public static String request(String httpUrl, String httpArg) { + BufferedReader reader = null; + String result = null; + StringBuffer sbf = new StringBuffer(); + httpUrl = httpUrl + "?" + httpArg; + + try { + URL url = new URL(httpUrl); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + InputStream is = connection.getInputStream(); + reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); + String strRead = reader.readLine(); + if (strRead != null) { + sbf.append(strRead); + while ((strRead = reader.readLine()) != null) { + sbf.append("\n"); + sbf.append(strRead); + } + } + reader.close(); + result = sbf.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + +} diff --git a/src/main/java/com/sqx/modules/file/utils/MimeTypeUtils.java b/src/main/java/com/sqx/modules/file/utils/MimeTypeUtils.java new file mode 100644 index 0000000..3fcef59 --- /dev/null +++ b/src/main/java/com/sqx/modules/file/utils/MimeTypeUtils.java @@ -0,0 +1,59 @@ +package com.sqx.modules.file.utils; + +/** + * 媒体类型工具类 + * + * @author ruoyi + */ +public class MimeTypeUtils +{ + public static final String IMAGE_PNG = "image/png"; + + public static final String IMAGE_JPG = "image/jpg"; + + public static final String IMAGE_JPEG = "image/jpeg"; + + public static final String IMAGE_BMP = "image/bmp"; + + public static final String IMAGE_GIF = "image/gif"; + + public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" }; + + public static final String[] FLASH_EXTENSION = { "swf", "flv" }; + + public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", + "asf", "rm", "rmvb" }; + + public static final String[] DEFAULT_ALLOWED_EXTENSION = { + // 图片 + "bmp", "gif", "jpg", "jpeg", "png", + // word excel powerpoint + "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", + // 压缩文件 + "rar", "zip", "gz", "bz2", + // 安卓ios更新包 + "apk", "ipa", + //视频格式 + "mp4","mp3","3GP","AVI","mov","rmvb", + // pdf + "pdf" }; + + public static String getExtension(String prefix) + { + switch (prefix) + { + case IMAGE_PNG: + return "png"; + case IMAGE_JPG: + return "jpg"; + case IMAGE_JPEG: + return "jpeg"; + case IMAGE_BMP: + return "bmp"; + case IMAGE_GIF: + return "gif"; + default: + return ""; + } + } +} diff --git a/src/main/java/com/sqx/modules/helpCenter/controller/HelpWordController.java b/src/main/java/com/sqx/modules/helpCenter/controller/HelpWordController.java new file mode 100644 index 0000000..54ed66e --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/controller/HelpWordController.java @@ -0,0 +1,112 @@ +package com.sqx.modules.helpCenter.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.helpCenter.entity.HelpClassify; +import com.sqx.modules.helpCenter.entity.HelpWord; +import com.sqx.modules.helpCenter.service.HelpClassifyService; +import com.sqx.modules.helpCenter.service.HelpWordService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; +import java.util.List; + +@RestController +@Api(value = "帮助中心", tags = {"帮助中心"}) +@RequestMapping(value = "/helpWord") +public class HelpWordController { + + @Autowired + private HelpClassifyService helpClassifyService; + @Autowired + private HelpWordService helpWordService; + + + @PostMapping("/insertHelpClassify") + @ApiOperation("添加帮助分类") + public Result insertHelpClassify(@RequestBody HelpClassify helpClassify){ + helpClassify.setCreateTime(DateUtils.format(new Date())); + helpClassifyService.save(helpClassify); + return Result.success(); + } + + @PostMapping("/updateHelpClassify") + @ApiOperation("修改帮助分类") + public Result updateHelpClassify(@RequestBody HelpClassify helpClassify){ + helpClassifyService.updateById(helpClassify); + return Result.success(); + } + + @PostMapping("/deleteHelpClassify") + @ApiOperation("删除帮助分类") + public Result deleteHelpClassify(Long helpClassifyId){ + helpClassifyService.removeById(helpClassifyId); + return Result.success(); + } + + + @GetMapping("/selectHelpClassifyList") + @ApiOperation("查询帮助分类") + public Result selectHelpClassifyList(Integer page,Integer limit,Long parentId,Integer types,String helpClassifyName){ + if(page==null || limit==null){ + List page1 = helpClassifyService.list( + new QueryWrapper() + .eq(types!=null,"types",types) + .eq(StringUtils.isNotBlank(helpClassifyName), "help_classify_name", helpClassifyName) + .eq(parentId != null, "parent_id", parentId).orderByAsc("sort")); + return Result.success().put("data",page1); + } + IPage page1 = helpClassifyService.page(new Page<>(page, limit), + new QueryWrapper() + .eq(types!=null,"types",types) + .eq(StringUtils.isNotBlank(helpClassifyName), "help_classify_name", helpClassifyName) + .eq(parentId != null, "parent_id", parentId).orderByAsc("sort")); + return Result.success().put("data",new PageUtils(page1)); + } + + + @PostMapping("/insertHelpWord") + @ApiOperation("添加帮助文档") + public Result insertHelpWord(@RequestBody HelpWord helpWord){ + helpWord.setCreateTime(DateUtils.format(new Date())); + helpWordService.save(helpWord); + return Result.success(); + } + + @PostMapping("/updateHelpWord") + @ApiOperation("修改帮助文档") + public Result updateHelpWord(@RequestBody HelpWord helpWord){ + helpWordService.updateById(helpWord); + return Result.success(); + } + + @PostMapping("/deleteHelpWord") + @ApiOperation("删除帮助文档") + public Result deleteHelpWord(Long helpWordId){ + helpWordService.removeById(helpWordId); + return Result.success(); + } + + + @GetMapping("/selectHelpWordList") + @ApiOperation("查询帮助文档") + public Result selectHelpWordList(Integer page,Integer limit,Long helpClassifyId,String helpWordTitle){ + IPage page1 = helpWordService.page(new Page<>(page, limit), new QueryWrapper() + .eq(helpClassifyId != null, "help_classify_id", helpClassifyId) + .eq(StringUtils.isNotBlank(helpWordTitle), "help_word_title", helpWordTitle).orderByAsc("sort")); + return Result.success().put("data",new PageUtils(page1)); + } + + + + + +} diff --git a/src/main/java/com/sqx/modules/helpCenter/controller/app/AppHelpWordController.java b/src/main/java/com/sqx/modules/helpCenter/controller/app/AppHelpWordController.java new file mode 100644 index 0000000..8087f97 --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/controller/app/AppHelpWordController.java @@ -0,0 +1,48 @@ +package com.sqx.modules.helpCenter.controller.app; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.helpCenter.entity.HelpClassify; +import com.sqx.modules.helpCenter.entity.HelpWord; +import com.sqx.modules.helpCenter.service.HelpClassifyService; +import com.sqx.modules.helpCenter.service.HelpWordService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@Api(value = "帮助中心", tags = {"帮助中心"}) +@RequestMapping(value = "/app/helpWord") +public class AppHelpWordController { + + + @Autowired + private HelpClassifyService helpClassifyService; + @Autowired + private HelpWordService helpWordService; + + @GetMapping("/selectHelpList") + @ApiOperation("查询帮助列表") + public Result selectHelpList(Integer types){ + List helpClassifyList = helpClassifyService.list(new QueryWrapper().eq(types!=null,"types",types).orderByAsc("sort")); + for(HelpClassify helpClassify:helpClassifyList){ + List helpWordList = helpWordService.list(new QueryWrapper().eq("help_classify_id", helpClassify.getHelpClassifyId()).orderByAsc("sort")); + helpClassify.setHelpWordList(helpWordList); + } + return Result.success().put("data",helpClassifyList); + } + + @GetMapping("/selectHelpWordDetails") + @ApiOperation("查询文档详情") + public Result selectHelpWordDetails(Long helpWordId){ + return Result.success().put("data",helpWordService.getById(helpWordId)); + } + + + +} diff --git a/src/main/java/com/sqx/modules/helpCenter/dao/HelpClassifyDao.java b/src/main/java/com/sqx/modules/helpCenter/dao/HelpClassifyDao.java new file mode 100644 index 0000000..1fbeac4 --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/dao/HelpClassifyDao.java @@ -0,0 +1,12 @@ +package com.sqx.modules.helpCenter.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.helpCenter.entity.HelpClassify; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface HelpClassifyDao extends BaseMapper { + + + +} diff --git a/src/main/java/com/sqx/modules/helpCenter/dao/HelpWordDao.java b/src/main/java/com/sqx/modules/helpCenter/dao/HelpWordDao.java new file mode 100644 index 0000000..5969b72 --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/dao/HelpWordDao.java @@ -0,0 +1,12 @@ +package com.sqx.modules.helpCenter.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.helpCenter.entity.HelpWord; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface HelpWordDao extends BaseMapper { + + + +} diff --git a/src/main/java/com/sqx/modules/helpCenter/entity/HelpClassify.java b/src/main/java/com/sqx/modules/helpCenter/entity/HelpClassify.java new file mode 100644 index 0000000..ad1e52f --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/entity/HelpClassify.java @@ -0,0 +1,60 @@ +package com.sqx.modules.helpCenter.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * @description help_classify + * @author fang + * @date 2022-06-06 + */ +@Data +public class HelpClassify implements Serializable { + + private static final long serialVersionUID = 1L; + + + /** + * 帮助中心分类 + */ + @TableId(type = IdType.AUTO) + private Long helpClassifyId; + + /** + * 分类名称 + */ + private String helpClassifyName; + + /** + * 排序 + */ + private Integer sort; + + /** + * 上级id + */ + private Long parentId; + + /** + * 创建时间 + */ + private String createTime; + + /** + * 类型 + */ + private Integer types; + + @TableField(exist = false) + private List helpClassifyList; + + @TableField(exist = false) + private List helpWordList; + + public HelpClassify() {} +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/helpCenter/entity/HelpWord.java b/src/main/java/com/sqx/modules/helpCenter/entity/HelpWord.java new file mode 100644 index 0000000..2c27591 --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/entity/HelpWord.java @@ -0,0 +1,51 @@ +package com.sqx.modules.helpCenter.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description help_word + * @author fang + * @date 2022-06-06 + */ +@Data +public class HelpWord implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 帮助文档id + */ + private Long helpWordId; + + /** + * 帮助标题 + */ + private String helpWordTitle; + + /** + * 帮助分类 + */ + private Integer helpClassifyId; + + /** + * 帮助文档内容 + */ + private String helpWordContent; + + /** + * 排序 + */ + private Integer sort; + + /** + * 创建时间 + */ + private String createTime; + + public HelpWord() {} +} diff --git a/src/main/java/com/sqx/modules/helpCenter/service/HelpClassifyService.java b/src/main/java/com/sqx/modules/helpCenter/service/HelpClassifyService.java new file mode 100644 index 0000000..d68ee43 --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/service/HelpClassifyService.java @@ -0,0 +1,10 @@ +package com.sqx.modules.helpCenter.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.helpCenter.entity.HelpClassify; + + +public interface HelpClassifyService extends IService { + + +} diff --git a/src/main/java/com/sqx/modules/helpCenter/service/HelpWordService.java b/src/main/java/com/sqx/modules/helpCenter/service/HelpWordService.java new file mode 100644 index 0000000..fd054ca --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/service/HelpWordService.java @@ -0,0 +1,11 @@ +package com.sqx.modules.helpCenter.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.helpCenter.entity.HelpWord; + + +public interface HelpWordService extends IService { + + + +} diff --git a/src/main/java/com/sqx/modules/helpCenter/service/impl/HelpClassifyServiceImpl.java b/src/main/java/com/sqx/modules/helpCenter/service/impl/HelpClassifyServiceImpl.java new file mode 100644 index 0000000..559656e --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/service/impl/HelpClassifyServiceImpl.java @@ -0,0 +1,23 @@ +package com.sqx.modules.helpCenter.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.helpCenter.dao.HelpClassifyDao; +import com.sqx.modules.helpCenter.entity.HelpClassify; +import com.sqx.modules.helpCenter.service.HelpClassifyService; +import org.springframework.stereotype.Service; + +@Service +public class HelpClassifyServiceImpl extends ServiceImpl implements HelpClassifyService { + + + + + +} + + + + + + + diff --git a/src/main/java/com/sqx/modules/helpCenter/service/impl/HelpWordServiceImpl.java b/src/main/java/com/sqx/modules/helpCenter/service/impl/HelpWordServiceImpl.java new file mode 100644 index 0000000..77ed575 --- /dev/null +++ b/src/main/java/com/sqx/modules/helpCenter/service/impl/HelpWordServiceImpl.java @@ -0,0 +1,23 @@ +package com.sqx.modules.helpCenter.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.helpCenter.dao.HelpWordDao; +import com.sqx.modules.helpCenter.entity.HelpWord; +import com.sqx.modules.helpCenter.service.HelpWordService; +import org.springframework.stereotype.Service; + +@Service +public class HelpWordServiceImpl extends ServiceImpl implements HelpWordService { + + + + + +} + + + + + + + diff --git a/src/main/java/com/sqx/modules/integral/controller/AdminUserIntegralController.java b/src/main/java/com/sqx/modules/integral/controller/AdminUserIntegralController.java new file mode 100644 index 0000000..ac904fe --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/controller/AdminUserIntegralController.java @@ -0,0 +1,28 @@ +package com.sqx.modules.integral.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.integral.service.UserIntegralService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags={"管理端-积分"}) +@RestController +@RequestMapping("/admin/userintegral") +public class AdminUserIntegralController { + + @Autowired + private UserIntegralService userIntegralService; + + @ApiOperation("管理端给用户添加积分") + @PostMapping(value = "addAdminIntegral") + public Result addAdminIntegral(Long userId, Integer sum, Integer type){ + + return userIntegralService.addAdminIntegral(userId, sum, type); + } + + +} diff --git a/src/main/java/com/sqx/modules/integral/controller/app/UserIntegralController.java b/src/main/java/com/sqx/modules/integral/controller/app/UserIntegralController.java new file mode 100644 index 0000000..b27502d --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/controller/app/UserIntegralController.java @@ -0,0 +1,72 @@ +package com.sqx.modules.integral.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.integral.service.UserIntegralService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags={"用户端-积分"}) +@RestController +@RequestMapping("/app/userintegral") +public class UserIntegralController { + + @Autowired + private UserIntegralService userIntegralService; + + @Login + @ApiOperation("判断用户是否已签到") + @GetMapping(value = "/isSignIn") + public Result isSignIn(@RequestAttribute Long userId){ + + return userIntegralService.isSignIn(userId); + } + + @Login + @ApiOperation("计算今日签到应得积分数") + @GetMapping(value = "/todayIntegral") + public Result todayIntegral(@RequestAttribute Long userId){ + + return userIntegralService.todayIntegral(userId); + } + + @Login + @ApiOperation("查看连续签到天数") + @GetMapping(value = "continuousDay") + public Result continuousDay(@RequestAttribute Long userId){ + + return userIntegralService.continuousDay(userId); + } + + + @Login + @ApiOperation("每日签到") + @GetMapping(value = "/signIn") + public Result signIn(@RequestAttribute Long userId){ + + return userIntegralService.signIn(userId); + } + + @Login + @ApiOperation("查看积分") + @GetMapping(value = "/selectUserIntegral") + public Result selectUserIntegral(@RequestAttribute Long userId){ + + return userIntegralService.selectUserIntegral(userId); + } + + @Login + @ApiOperation("用户积分、优惠券、钱包余额") + @GetMapping(value = "/findUserMessage") + public Result findUserMessage(@RequestAttribute Long userId){ + + return userIntegralService.findUserMessage(userId); + } + + +} diff --git a/src/main/java/com/sqx/modules/integral/controller/app/UserIntegralDetailsController.java b/src/main/java/com/sqx/modules/integral/controller/app/UserIntegralDetailsController.java new file mode 100644 index 0000000..26a1083 --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/controller/app/UserIntegralDetailsController.java @@ -0,0 +1,32 @@ +package com.sqx.modules.integral.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.integral.service.UserIntegralDetailsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags={"用户端-积分明细"}) +@RestController +@RequestMapping("/app/userintegraldetails") +public class UserIntegralDetailsController { + + @Autowired + private UserIntegralDetailsService userIntegralDetailsService; + + @Login + @ApiOperation("查看积分明细") + @GetMapping(value = "selectIntegraldetailsList") + public Result selectIntegraldetailsList(@RequestAttribute Long userId, Integer page, Integer limit, Integer classify,Integer type){ + + return userIntegralDetailsService.selectIntegraldetailsList(userId, page, limit, classify,type); + } + + + +} diff --git a/src/main/java/com/sqx/modules/integral/dao/UserIntegralDao.java b/src/main/java/com/sqx/modules/integral/dao/UserIntegralDao.java new file mode 100644 index 0000000..8d48015 --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/dao/UserIntegralDao.java @@ -0,0 +1,15 @@ +package com.sqx.modules.integral.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.integral.entity.UserIntegral; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +@Mapper +public interface UserIntegralDao extends BaseMapper { + + int addUserIntegral(@Param("num") Integer num, @Param("userId") Long userId); + + int updateUserIntegral(@Param("userId") Long userId,@Param("needIntegral") Integer needIntegral); + +} diff --git a/src/main/java/com/sqx/modules/integral/dao/UserIntegralDetailsDao.java b/src/main/java/com/sqx/modules/integral/dao/UserIntegralDetailsDao.java new file mode 100644 index 0000000..1ac699b --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/dao/UserIntegralDetailsDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.integral.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.integral.entity.UserIntegralDetails; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +@Mapper +public interface UserIntegralDetailsDao extends BaseMapper { + + UserIntegralDetails isSignIn(@Param("userId") Long userId,@Param("format") String format); + + IPage selectIntegraldetailsList(Page pages, Long userId, Integer classify,Integer type); + + IPage selectSignIn(Page pages,@Param("userId") Long userId); + + UserIntegralDetails selectUserIntegralDetails(@Param("userId") Long userId, @Param("date") String date); +} diff --git a/src/main/java/com/sqx/modules/integral/entity/UserIntegral.java b/src/main/java/com/sqx/modules/integral/entity/UserIntegral.java new file mode 100644 index 0000000..cfb1947 --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/entity/UserIntegral.java @@ -0,0 +1,32 @@ +package com.sqx.modules.integral.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +@ApiModel("user_integral") +public class UserIntegral implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + + @ApiModelProperty("id") + private Long id; + + + @ApiModelProperty("用户id") + private Long userId; + + + @ApiModelProperty("积分数量") + private BigDecimal integralNum; + + public UserIntegral() {} +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/integral/entity/UserIntegralDetails.java b/src/main/java/com/sqx/modules/integral/entity/UserIntegralDetails.java new file mode 100644 index 0000000..bd3bac3 --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/entity/UserIntegralDetails.java @@ -0,0 +1,50 @@ +package com.sqx.modules.integral.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +@Data +@ApiModel("user_integral_details") +public class UserIntegralDetails implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + + @ApiModelProperty("积分详情id") + private Integer id; + + + @ApiModelProperty("内容") + private String content; + + + @ApiModelProperty("获取类型 1签到 2积分兑换优惠券 3系统赠送积分") + private Integer classify; + + + @ApiModelProperty("分类 1增加 2减少") + private Integer type; + + + @ApiModelProperty("数量") + private Integer num; + + + @ApiModelProperty("用户id") + private Long userId; + + + @ApiModelProperty("创建时间") + private String createTime; + + @ApiModelProperty("连续签到天数") + private Integer day; + + public UserIntegralDetails() {} +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/integral/service/UserIntegralDetailsService.java b/src/main/java/com/sqx/modules/integral/service/UserIntegralDetailsService.java new file mode 100644 index 0000000..c99842f --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/service/UserIntegralDetailsService.java @@ -0,0 +1,13 @@ +package com.sqx.modules.integral.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.integral.entity.UserIntegralDetails; + +public interface UserIntegralDetailsService extends IService { + + Result selectIntegraldetailsList(Long userId, Integer page, Integer limit, Integer classify,Integer type); + + Result selectSignIn(Integer page, Integer limit, Long userId); + +} diff --git a/src/main/java/com/sqx/modules/integral/service/UserIntegralService.java b/src/main/java/com/sqx/modules/integral/service/UserIntegralService.java new file mode 100644 index 0000000..ad3a524 --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/service/UserIntegralService.java @@ -0,0 +1,25 @@ +package com.sqx.modules.integral.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.integral.entity.UserIntegral; + +public interface UserIntegralService extends IService { + + Result isSignIn(Long userId); + + Result signIn(Long userId); + + Result selectUserIntegral(Long userId); + + UserIntegral selectUserIntegrals(Long userId); + + Result todayIntegral(Long userId); + + Result findUserMessage(Long userId); + + Result continuousDay(Long userId); + + Result addAdminIntegral(Long userId, Integer sum, Integer type); + +} diff --git a/src/main/java/com/sqx/modules/integral/service/impl/UserIntegralDetailsServiceImpl.java b/src/main/java/com/sqx/modules/integral/service/impl/UserIntegralDetailsServiceImpl.java new file mode 100644 index 0000000..e91f94d --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/service/impl/UserIntegralDetailsServiceImpl.java @@ -0,0 +1,32 @@ +package com.sqx.modules.integral.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.integral.dao.UserIntegralDetailsDao; +import com.sqx.modules.integral.entity.UserIntegralDetails; +import com.sqx.modules.integral.service.UserIntegralDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class UserIntegralDetailsServiceImpl extends ServiceImpl implements UserIntegralDetailsService { + + @Autowired + private UserIntegralDetailsDao userIntegralDetailsDao; + + @Override + public Result selectIntegraldetailsList(Long userId, Integer page, Integer limit, Integer classify,Integer type) { + Page pages=new Page<>(page,limit); + PageUtils pageUtils = new PageUtils(userIntegralDetailsDao.selectIntegraldetailsList(pages, userId, classify,type)); + return Result.success().put("data", pageUtils); + } + + @Override + public Result selectSignIn(Integer page, Integer limit, Long userId) { + Page pages=new Page<>(page,limit); + PageUtils pageUtils = new PageUtils(userIntegralDetailsDao.selectSignIn(pages, userId)); + return Result.success().put("data", pageUtils); + } +} diff --git a/src/main/java/com/sqx/modules/integral/service/impl/UserIntegralServiceImpl.java b/src/main/java/com/sqx/modules/integral/service/impl/UserIntegralServiceImpl.java new file mode 100644 index 0000000..7bae41d --- /dev/null +++ b/src/main/java/com/sqx/modules/integral/service/impl/UserIntegralServiceImpl.java @@ -0,0 +1,233 @@ +package com.sqx.modules.integral.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserMoneyDao; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.integral.dao.UserIntegralDao; +import com.sqx.modules.integral.dao.UserIntegralDetailsDao; +import com.sqx.modules.integral.entity.UserIntegral; +import com.sqx.modules.integral.entity.UserIntegralDetails; +import com.sqx.modules.integral.service.UserIntegralService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Locale; + +@Service +public class UserIntegralServiceImpl extends ServiceImpl implements UserIntegralService { + + @Autowired + private UserIntegralDao userIntegralDao; + @Autowired + private UserIntegralDetailsDao userIntegralDetailsDao; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private UserIntegralService userIntegralService; + @Autowired + private UserMoneyDao userMoneyDao; + + @Override + public Result isSignIn(Long userId) { + String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); + UserIntegralDetails signIn = userIntegralDetailsDao.isSignIn(userId, format); + if(signIn!=null){ + return Result.success().put("data", "今日已签到"); + } + return Result.success().put("data", "今日未签到"); + } + + @Override + public Result selectUserIntegral(Long userId) { + UserIntegral userIntegral = userIntegralDao.selectOne(new QueryWrapper().eq("user_id", userId)); + if(userIntegral==null){ + userIntegral=new UserIntegral(); + userIntegral.setUserId(userId); + userIntegral.setIntegralNum(BigDecimal.ZERO); + baseMapper.insert(userIntegral); + userIntegral = userIntegralDao.selectOne(new QueryWrapper().eq("user_id", userId)); + } + return Result.success().put("data", userIntegral); + } + + @Override + public UserIntegral selectUserIntegrals(Long userId) { + UserIntegral userIntegral = userIntegralDao.selectOne(new QueryWrapper().eq("user_id", userId)); + if(userIntegral==null){ + userIntegral=new UserIntegral(); + userIntegral.setUserId(userId); + userIntegral.setIntegralNum(BigDecimal.ZERO); + baseMapper.insert(userIntegral); + userIntegral = userIntegralDao.selectOne(new QueryWrapper().eq("user_id", userId)); + } + return userIntegral; + } + + @Override + public Result continuousDay(Long userId) { + HashMap hashMap = new HashMap(); + Integer dayNum; + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.DATE, -1); + String yesterday = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime()); + UserIntegralDetails userIntegralDetailsYesterday = userIntegralDetailsDao.selectUserIntegralDetails(userId, yesterday); + String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + UserIntegralDetails userIntegralDetailsToday = userIntegralDetailsDao.selectUserIntegralDetails(userId, date); + if(userIntegralDetailsYesterday==null){ + if(userIntegralDetailsToday==null){ + dayNum = 0; + }else { + dayNum = 1; + } + }else { + if(userIntegralDetailsToday==null){ + dayNum = userIntegralDetailsYesterday.getDay(); + }else { + dayNum = userIntegralDetailsToday.getDay(); + } + } + hashMap.put("dayNum", dayNum); + CommonInfo one = commonInfoService.findOne(118); + Integer daySum = Integer.valueOf(one.getValue()); + hashMap.put("daySum", daySum); + return Result.success().put("data", hashMap); + } + + @Override + public Result addAdminIntegral(Long userId, Integer sum, Integer type) { + UserIntegral userIntegral = selectUserIntegrals(userId); + //添加积分赠送记录 + UserIntegralDetails userIntegralDetails = new UserIntegralDetails(); + if(type.equals(1)){ + BigDecimal integral = userIntegral.getIntegralNum().add(BigDecimal.valueOf(sum)); + userIntegral.setIntegralNum(integral); + baseMapper.updateById(userIntegral); + userIntegralDetails.setContent("系统赠送积分"); + }else if(type.equals(2)){ + BigDecimal integral = userIntegral.getIntegralNum().subtract(BigDecimal.valueOf(sum)); + userIntegral.setIntegralNum(integral); + baseMapper.updateById(userIntegral); + userIntegralDetails.setContent("系统扣除积分"); + } + userIntegralDetails.setClassify(3); + userIntegralDetails.setType(type); + userIntegralDetails.setNum(sum); + userIntegralDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + userIntegralDetails.setUserId(userId); + userIntegralDetailsDao.insert(userIntegralDetails); + return Result.success(); + } + + @Override + public Result findUserMessage(Long userId) { + HashMap hashMap = new HashMap(); + + UserIntegral userIntegral = selectUserIntegrals(userId); + UserMoney userMoney = userMoneyDao.selectOne(new QueryWrapper().eq("user_id", userId)); + hashMap.put("userIntegral", userIntegral.getIntegralNum()); + hashMap.put("userMoney", userMoney.getMoney()); + return Result.success().put("data", hashMap); + } + + public static String getCurrDayOfWeek() { + Date date = new Date(); + SimpleDateFormat dateFm = new SimpleDateFormat("EEEE", Locale.CHINA); + return dateFm.format(date); + } + + //计算今日签到应得积分数 + @Override + public Result todayIntegral(Long userId) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.DATE, -1); + String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime()); + UserIntegralDetails userIntegralDetails = userIntegralDetailsDao.selectUserIntegralDetails(userId, date); + if(userIntegralDetails==null){ + CommonInfo one = commonInfoService.findOne(119); + Integer num = Integer.valueOf(one.getValue()); + return Result.success().put("data", num); + }else { + Integer todayIntegral; + CommonInfo one = commonInfoService.findOne(118); + Integer value = Integer.valueOf(one.getValue()); + CommonInfo one1 = commonInfoService.findOne(120); + Integer add = Integer.valueOf(one1.getValue()); + if(userIntegralDetails.getDay() map=new HashMap<>(); + map.put("url",one.getValue()); + map.put("user",userEntity); + return Result.success().put("data",map); + } + + @RequestMapping(value = "/selectInviteByUserIdList", method = RequestMethod.GET) + @ApiOperation("查看我邀请的人员列表(只查看邀请成功成为会员))") + @ResponseBody + public Result selectInviteByUserIdList(int page,int limit,Long userId){ + PageUtils pageUtils = inviteService.selectInviteUser(page, limit, userId,1); + InviteMoney inviteMoney = inviteMoneyService.selectInviteMoneyByUserId(userId); + Map map=new HashMap<>(); + map.put("pageUtils",pageUtils); + map.put("inviteMoney",inviteMoney); + return Result.success().put("data",map); + } + + @GetMapping("/mpCreateQr") + @ApiOperation("小程序推广二维码") + public void mpCreateQr(@RequestParam String relation, HttpServletResponse response) { + SenInfoCheckUtil.getPoster(relation,response); + } + + + + + /*@RequestMapping(value = "/selectZhiFeiMoney", method = RequestMethod.GET) + @ApiOperation("查询直属非直属邀请收益") + @ResponseBody + public Result selectZhiFeiMoney(Long userId){ + UserEntity userEntity = userService.queryByUserId(userId); + //查询直属邀请人数数量 + Integer zhiUserInviteCount = userService.selectZhiUserInviteCount(userEntity.getInvitationCode()); + //查询非直属邀请人数量 + Integer feiUserInviteCount = userService.selectFeiUserInviteCount(userEntity.getInvitationCode()); + Map map=new HashMap<>(); + map.put("zhiUserInviteCount",zhiUserInviteCount); + map.put("feiUserInviteCount",feiUserInviteCount); + return Result.success().put("data",map); + }*/ + + /*@RequestMapping(value = "/selectZhiInviteByUserIdList", method = RequestMethod.GET) + @ApiOperation("直属") + @ResponseBody + public Result selectZhiInviteByUserIdList(int page,int limit,Long userId){ + return userService.selectZhiInviteByUserIdList(page,limit,userId); + } + + @RequestMapping(value = "/selectFeiInviteByUserIdList", method = RequestMethod.GET) + @ApiOperation("非直属用户") + @ResponseBody + public Result selectFeiInviteByUserIdList(int page,int limit,Long userId){ + return userService.selectFeiInviteByUserIdList(page,limit,userId); + }*/ + + + @RequestMapping(value = "/selectInviteByUserIdLists", method = RequestMethod.GET) + @ApiOperation("查看我邀请的人员列表(查看所有邀请列表)") + @ResponseBody + public Result selectInviteByUserIdLists(int page,int limit,Long userId){ + PageUtils pageUtils = inviteService.selectInviteUser(page, limit, userId,null); + Map map=new HashMap<>(); + map.put("pageUtils",pageUtils); + return Result.success().put("data",map); + } + + @RequestMapping(value = "/insertInvitationCode", method = RequestMethod.POST) + @ApiOperation("填写邀请码") + @ResponseBody + public Result insertInvitationCode(Long userId,String invitationCode) + { + if(StringUtils.isBlank(invitationCode)){ + return Result.error("邀请码不能为空!"); + } + //long inviteeUserId = InvitationCodeUtil.codeToId(invitationCode); + UserEntity userEntity = userService.queryByInvitationCode(invitationCode); + if(userEntity==null){ + return Result.error("邀请码填写错误!"); + } + inviteService.saveBody(userId,userEntity); + return Result.success(); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/invite/controller/app/AppInviteController.java b/src/main/java/com/sqx/modules/invite/controller/app/AppInviteController.java new file mode 100644 index 0000000..f20a208 --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/controller/app/AppInviteController.java @@ -0,0 +1,92 @@ +package com.sqx.modules.invite.controller.app; + + +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.invite.entity.InviteMoney; +import com.sqx.modules.invite.service.InviteMoneyService; +import com.sqx.modules.invite.service.InviteService; +import com.sqx.modules.utils.SenInfoCheckUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.Map; + +/** + * @author fang + * @date 2020/7/9 + */ +@Slf4j +@RestController +@Api(value = "邀请收益", tags = {"邀请收益"}) +@RequestMapping(value = "/app/invite") +public class AppInviteController { + + @Autowired + private InviteService inviteService; + @Autowired + private UserService userService; + @Autowired + private InviteMoneyService inviteMoneyService; + @Autowired + private CommonInfoService commonInfoService; + + @RequestMapping(value = "/selectInviteCount", method = RequestMethod.GET) + @ApiOperation("查看我邀请的人员数量") + @ResponseBody + public Result selectInviteCount(Integer state,Long userId){ + return Result.success().put("data",inviteService.selectInviteCount(state,userId)); + } + @Login + @RequestMapping(value = "/selectInviteAndPoster", method = RequestMethod.GET) + @ApiOperation("查看我的邀请码和海报二维码") + @ResponseBody + public Result selectInviteAndPoster(@RequestAttribute Long userId){ + UserEntity userEntity = userService.queryByUserId(userId); + CommonInfo one = commonInfoService.findOne(19); + Map map=new HashMap<>(); + map.put("url",one.getValue()); + map.put("user",userEntity); + return Result.success().put("data",map); + } + + @Login + @RequestMapping(value = "/selectInviteMoney", method = RequestMethod.GET) + @ApiOperation("我的收益") + @ResponseBody + public Result selectInviteMoney(@RequestAttribute("userId") Long userId){ + InviteMoney inviteMoney = inviteMoneyService.selectInviteMoneyByUserId(userId); + Integer inviteCount = inviteService.selectInviteCount(-1, userId); + Map result=new HashMap<>(); + result.put("inviteMoney",inviteMoney); + result.put("inviteCount",inviteCount); + return Result.success().put("data",result); + } + + @GetMapping("/mpCreateQr") + @ApiOperation("小程序推广二维码") + public void mpCreateQr(@RequestParam String invitationCode, HttpServletResponse response) { + SenInfoCheckUtil.getPoster(invitationCode,response); + } + + + @Login + @RequestMapping(value = "/selectInviteByUserIdLists", method = RequestMethod.GET) + @ApiOperation("查看我邀请的人员列表(查看所有邀请列表)") + @ResponseBody + public Result selectInviteByUserIdLists(int page,int limit,@RequestAttribute("userId") Long userId){ + PageUtils pageUtils = inviteService.selectInviteUser(page, limit, userId,null); + return Result.success().put("data",pageUtils); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/invite/dao/InviteDao.java b/src/main/java/com/sqx/modules/invite/dao/InviteDao.java new file mode 100644 index 0000000..ba1a321 --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/dao/InviteDao.java @@ -0,0 +1,41 @@ +package com.sqx.modules.invite.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.invite.entity.Invite; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.Date; +import java.util.Map; + +/** + * @author fang + * @date 2020/7/9 + */ +@Mapper +public interface InviteDao extends BaseMapper { + + IPage selectInviteList(Page> page, @Param("state") Integer state, @Param("userId") Long userId); + + Integer selectInviteCount(@Param("state") Integer state, @Param("userId") Long userId); + + Double selectInviteSum(@Param("state") Integer state, @Param("userId") Long userId); + + IPage> selectInviteUser(Page> page, @Param("userId") Long userId,@Param("state") Integer state); + + Invite selectInviteByUser(@Param("userId")Long userId,@Param("inviteeUserId") Long inviteeUserId); + + Integer selectInviteByUserIdCountNotTime(@Param("userId")Long userId); + + Integer selectInviteByUserIdCount(@Param("userId") Long userId, @Param("startTime")Date startTime,@Param("endTime")Date endTime); + + Double selectInviteByUserIdSum(@Param("userId") Long userId, @Param("startTime")Date startTime,@Param("endTime")Date endTime); + + Double sumInviteMoney(@Param("time")String time,@Param("flag")Integer flag); + + IPage> inviteAnalysis(Page> page,@Param("time")String time,@Param("flag")Integer flag); + + +} diff --git a/src/main/java/com/sqx/modules/invite/dao/InviteMoneyDao.java b/src/main/java/com/sqx/modules/invite/dao/InviteMoneyDao.java new file mode 100644 index 0000000..99ad3bb --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/dao/InviteMoneyDao.java @@ -0,0 +1,23 @@ +package com.sqx.modules.invite.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.invite.entity.InviteMoney; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + * 邀请收益钱包 + * + */ +@Mapper +public interface InviteMoneyDao extends BaseMapper { + + + InviteMoney selectInviteMoneyByUserId(Long userId); + + int updateInviteMoneySum(@Param("money") Double money,@Param("userId") Long userId); + + int updateInviteMoneyCashOut(@Param("type") Integer type,@Param("money") Double money,@Param("userId") Long userId); + + +} diff --git a/src/main/java/com/sqx/modules/invite/entity/Invite.java b/src/main/java/com/sqx/modules/invite/entity/Invite.java new file mode 100644 index 0000000..956ffe7 --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/entity/Invite.java @@ -0,0 +1,50 @@ +package com.sqx.modules.invite.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author fang + * @date 2020/7/9 + */ +@Data +@TableName("invite") +public class Invite implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 邀请id + */ + @TableId(type = IdType.INPUT) + private Long id; + + /** + * 邀请人id + */ + private Long userId; + + /** + * 被邀请人id + */ + private Long inviteeUserId; + + /** + * 状态 0非会员 1会员 + */ + private Integer state; + + /** + * 收益 + */ + private Double money; + + /** + * 创建时间 + */ + private String createTime; + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/invite/entity/InviteMoney.java b/src/main/java/com/sqx/modules/invite/entity/InviteMoney.java new file mode 100644 index 0000000..34b5a7b --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/entity/InviteMoney.java @@ -0,0 +1,44 @@ +package com.sqx.modules.invite.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * invite_money + * @author fang 2020-07-28 + */ +@Data +public class InviteMoney implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 邀请收益钱包id + */ + private Long id; + + /** + * 用户id + */ + private Long userId; + + /** + * 总获取收益 + */ + private Double moneySum; + + /** + * 当前金额 + */ + private Double money; + + /** + * 累计提现 + */ + private Double cashOut; + + public InviteMoney() { + } + +} diff --git a/src/main/java/com/sqx/modules/invite/service/InviteMoneyService.java b/src/main/java/com/sqx/modules/invite/service/InviteMoneyService.java new file mode 100644 index 0000000..7e66944 --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/service/InviteMoneyService.java @@ -0,0 +1,20 @@ +package com.sqx.modules.invite.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.invite.entity.InviteMoney; + +/** + * 邀请收益 + * + */ +public interface InviteMoneyService extends IService { + + InviteMoney selectInviteMoneyByUserId(Long userId); + + int updateInviteMoneySum(Double money,Long userId); + + int updateInviteMoneyCashOut(Double money,Long userId); + + +} diff --git a/src/main/java/com/sqx/modules/invite/service/InviteService.java b/src/main/java/com/sqx/modules/invite/service/InviteService.java new file mode 100644 index 0000000..76e948f --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/service/InviteService.java @@ -0,0 +1,33 @@ +package com.sqx.modules.invite.service; + + +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.app.entity.UserEntity; + +import java.util.Date; + +public interface InviteService { + + PageUtils selectInviteList(int page, int limit, Integer state, Long userId); + + Integer selectInviteCount(Integer state,Long userId); + + Double selectInviteSum(Integer state,Long userId); + + int saveBody(Long userId, UserEntity userEntity); + + PageUtils selectInviteUser(int page,int limit,Long userId,Integer state); + + Integer selectInviteByUserIdCountNotTime(Long userId); + + Integer selectInviteByUserIdCount(Long userId, Date startTime, Date endTime); + + Double selectInviteByUserIdSum(Long userId, Date startTime,Date endTime); + + Double sumInviteMoney(String time,Integer flag); + + PageUtils inviteAnalysis(int page,int limit, String time, Integer flag); + + void updateInvite(UserEntity userEntity,String format,Long userId); + +} diff --git a/src/main/java/com/sqx/modules/invite/service/impl/InviteMoneyServiceImpl.java b/src/main/java/com/sqx/modules/invite/service/impl/InviteMoneyServiceImpl.java new file mode 100644 index 0000000..237a3da --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/service/impl/InviteMoneyServiceImpl.java @@ -0,0 +1,42 @@ +package com.sqx.modules.invite.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.invite.dao.InviteMoneyDao; +import com.sqx.modules.invite.entity.InviteMoney; +import com.sqx.modules.invite.service.InviteMoneyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +@Service("InviteMoneyService") +public class InviteMoneyServiceImpl extends ServiceImpl implements InviteMoneyService { + + @Autowired + private InviteMoneyDao inviteMoneyDao; + + + @Override + public InviteMoney selectInviteMoneyByUserId(Long userId) { + InviteMoney inviteMoney = inviteMoneyDao.selectInviteMoneyByUserId(userId); + if(inviteMoney==null){ + inviteMoney=new InviteMoney(); + inviteMoney.setCashOut(0.00); + inviteMoney.setUserId(userId); + inviteMoney.setMoney(0.00); + inviteMoney.setMoneySum(0.00); + inviteMoneyDao.insert(inviteMoney); + } + return inviteMoney; + } + + @Override + public int updateInviteMoneySum(Double money, Long userId) { + return inviteMoneyDao.updateInviteMoneySum(money,userId); + } + + @Override + public int updateInviteMoneyCashOut(Double money, Long userId) { + return inviteMoneyDao.updateInviteMoneySum(money,userId); + } +} diff --git a/src/main/java/com/sqx/modules/invite/service/impl/InviteServiceImpl.java b/src/main/java/com/sqx/modules/invite/service/impl/InviteServiceImpl.java new file mode 100644 index 0000000..3932d87 --- /dev/null +++ b/src/main/java/com/sqx/modules/invite/service/impl/InviteServiceImpl.java @@ -0,0 +1,189 @@ +package com.sqx.modules.invite.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.invite.dao.InviteDao; +import com.sqx.modules.invite.entity.Invite; +import com.sqx.modules.invite.service.InviteMoneyService; +import com.sqx.modules.invite.service.InviteService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.utils.AmountCalUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.Random; + +/** + * 邀请记录 + */ +@Service +public class InviteServiceImpl extends ServiceImpl implements InviteService { + + + @Autowired + private InviteDao inviteDao; + @Autowired + private UserService userService; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private InviteMoneyService inviteMoneyService; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private MessageService messageService; + + @Override + public PageUtils selectInviteList(int page,int limit,Integer state,Long userId){ + Page> pages=new Page<>(page,limit); + if(state==null || state==-1){ + state=null; + } + return new PageUtils(inviteDao.selectInviteList(pages,state,userId)); + } + + + @Override + public PageUtils selectInviteUser(int page,int limit,Long userId,Integer state){ + Page> pages=new Page<>(page,limit); + return new PageUtils(inviteDao.selectInviteUser(pages,userId,state)); + } + + @Override + public Integer selectInviteByUserIdCountNotTime(Long userId) { + return inviteDao.selectInviteByUserIdCountNotTime(userId); + } + + @Override + public Integer selectInviteByUserIdCount(Long userId, Date startTime, Date endTime) { + return inviteDao.selectInviteByUserIdCount(userId,startTime,endTime); + } + + @Override + public Double selectInviteByUserIdSum(Long userId, Date startTime, Date endTime) { + return inviteDao.selectInviteByUserIdSum(userId,startTime,endTime); + } + + @Override + public Double sumInviteMoney(String time, Integer flag) { + return inviteDao.sumInviteMoney(time,flag); + } + + @Override + public PageUtils inviteAnalysis(int page,int limit, String time, Integer flag) { + Page> pages=new Page<>(page,limit); + return new PageUtils(inviteDao.inviteAnalysis(pages,time,flag)); + } + + @Override + public Integer selectInviteCount(Integer state,Long userId){ + if(state==null || state==-1){ + state=null; + } + return inviteDao.selectInviteCount(state,userId); + } + + @Override + public Double selectInviteSum(Integer state, Long userId) { + if(state==null || state==-1){ + state=null; + } + return inviteDao.selectInviteSum(state,userId); + } + + + @Transactional + @Override + public int saveBody(Long userId, UserEntity userEntity){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String format = sdf.format(new Date()); + Invite invite=new Invite(); + invite.setState(0); + invite.setMoney(0.00); + invite.setUserId(userEntity.getUserId()); + invite.setInviteeUserId(userId); + invite.setCreateTime(format); + inviteDao.insert(invite); + //给被邀请者增加上级id + UserEntity user=new UserEntity(); + user.setUserId(userId); + user.setInviterCode(userEntity.getInvitationCode()); + userService.updateById(user); + updateInvite(userEntity,format,userId); + return 1; + } + + + @Override + public void updateInvite(UserEntity userEntity,String format,Long userId){ + Invite invite1 = inviteDao.selectInviteByUser(userEntity.getUserId(), userId); + if(invite1==null){ + Invite invite=new Invite(); + invite.setState(0); + invite.setMoney(0.00); + invite.setUserId(userEntity.getUserId()); + invite.setInviteeUserId(userId); + invite.setCreateTime(format); + inviteDao.insert(invite); + invite1 = inviteDao.selectInviteByUser(userEntity.getUserId(), userId); + } + if(invite1.getState()==0){ + CommonInfo one = commonInfoService.findOne(189); + if(one!=null && StringUtils.isNotEmpty(one.getValue()) && Integer.parseInt(one.getValue())>0){ + Double money=Double.parseDouble(one.getValue()); + invite1.setState(1); + invite1.setMoney(money); + inviteDao.updateById(invite1); + inviteMoneyService.updateInviteMoneySum(money,userEntity.getUserId()); + userMoneyService.updateMoney(1,userEntity.getUserId(),BigDecimal.valueOf(money)); + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setClassify(40); + userMoneyDetails.setUserId(userEntity.getUserId()); + UserEntity userEntity1 = userService.selectUserById(userId); + userMoneyDetails.setTitle("[邀请好友]好友名称:"+userEntity1.getUserName()); + userMoneyDetails.setContent("增加金额:"+money); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(new BigDecimal(money)); + userMoneyDetails.setCreateTime(format); + userMoneyDetailsService.save(userMoneyDetails); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("恭喜您,邀请的好友注册成功了,赠送您:"+money+""); + messageInfo.setTitle("邀请赏金"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + messageInfo.setCreateAt(sdf.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if(StringUtils.isNotEmpty(userEntity.getClientid())){ + userService.pushToSingle("邀请赏金","恭喜您,邀请的好友注册成功了,赠送您:"+money,userEntity.getClientid()); + } + + + + } + } + } + + +} diff --git a/src/main/java/com/sqx/modules/laundry/controller/LaundryController.java b/src/main/java/com/sqx/modules/laundry/controller/LaundryController.java new file mode 100644 index 0000000..455f4d0 --- /dev/null +++ b/src/main/java/com/sqx/modules/laundry/controller/LaundryController.java @@ -0,0 +1,90 @@ +package com.sqx.modules.laundry.controller; + +import com.sqx.modules.chats.utils.Result; +import com.sqx.modules.chats.utils.ResultUtil; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.laundry.service.LaundryService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "站点", tags = {"站点"}) +@RequestMapping(value = "/laundry") +public class LaundryController { + + @Autowired + private LaundryService laundryService; + + @PostMapping("/saveLaundry") + @ApiOperation("添加站点") + public Result saveLaundry(@RequestBody Laundry laundry){ + return laundryService.saveLaundry(laundry); + } + + @PostMapping("/updateLaundry") + @ApiOperation("修改站点") + public Result updateLaundry(@RequestBody Laundry laundry){ + return laundryService.updateLaundry(laundry); + } + + @PostMapping("/updateLaundryIsOpen") + @ApiOperation("修改站点") + public Result updateLaundryIsOpen(Long laundryId,Integer isOpen){ + return laundryService.updateLaundryIsOpen(laundryId,isOpen); + } + + @GetMapping("/selectLaundryById") + @ApiOperation("根据id查询站点") + public Result selectLaundryById(Long laundryId){ + return laundryService.selectLaundryById(laundryId); + } + + @GetMapping("/selectLaundryList") + @ApiOperation("查询站点列表") + public Result selectLaundryList(Integer page,Integer size,String nickName,Integer status,String laundryName,String laundryPhone,String longitude,String latitude){ + return laundryService.selectLaundryList(page, size, nickName,laundryPhone,status,laundryName,longitude,latitude); + } + + @PostMapping("/deleteLaundry") + @ApiOperation("删除站点") + public Result deleteLaundry(Long laundryId){ + return laundryService.deleteLaundryById(laundryId); + } + + @GetMapping("/selectLaundryByDistance") + @ApiOperation("查询距离自己最近的站点") + public Result selectLaundryByDistance(String longitude,String latitude,Long goodsId){ + return laundryService.selectLaundryByDistance(longitude, latitude,goodsId); + } + + @GetMapping("/selectLaundryDetails") + @ApiOperation("根据id查询站点(管理端)") + public Result selectLaundryDetails(Long laundryId){ + return laundryService.selectLaundryDetails(laundryId); + } + + + @GetMapping("/selectLaundryMoneyStatistics") + @ApiOperation("站点收益排行榜") + public Result selectLaundryMoneyStatistics(Integer page,Integer size ,String laundryName){ + return laundryService.selectLaundryMoneyStatistics(page,size ,laundryName); + } + + @GetMapping("/selectLaundryMoneyByLaundryId") + @ApiOperation("站点收益排行榜") + public Result selectLaundryMoneyByLaundryId(String laundryId){ + return ResultUtil.success(laundryService.selectLaundryMoneyByLaundryId(laundryId)); + } + /** + * 移除站点师傅 + * @param laundryId + * @param userId + * @return + */ + @PostMapping("deleteWork") + public Result deleteWork(Long laundryId, Long userId){ + return laundryService.deleteWork(laundryId,userId); + } +} diff --git a/src/main/java/com/sqx/modules/laundry/controller/app/AppLaundryController.java b/src/main/java/com/sqx/modules/laundry/controller/app/AppLaundryController.java new file mode 100644 index 0000000..434d113 --- /dev/null +++ b/src/main/java/com/sqx/modules/laundry/controller/app/AppLaundryController.java @@ -0,0 +1,30 @@ +package com.sqx.modules.laundry.controller.app; + +import com.sqx.modules.chats.utils.Result; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.laundry.service.LaundryService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "站点", tags = {"站点"}) +@RequestMapping(value = "/app/laundry") +public class AppLaundryController { + + @Autowired + private LaundryService laundryService; + + @GetMapping("/selectLaundryList") + @ApiOperation("查询站点列表") + public Result selectLaundryList(Integer page, Integer size, String nickName, Integer status, String laundryName, String laundryPhone, String longitude, String latitude) { + return laundryService.selectLaundryList(page, size, nickName, laundryPhone, status, laundryName, longitude, latitude); + } + + @GetMapping("/selectLaundryByDistance") + @ApiOperation("查询距离自己最近的站点") + public Result selectLaundryByDistance(String longitude, String latitude,Long goodsId) { + return laundryService.selectLaundryByDistance(longitude, latitude,goodsId); + } +} diff --git a/src/main/java/com/sqx/modules/laundry/dao/LaundryRepository.java b/src/main/java/com/sqx/modules/laundry/dao/LaundryRepository.java new file mode 100644 index 0000000..c21e244 --- /dev/null +++ b/src/main/java/com/sqx/modules/laundry/dao/LaundryRepository.java @@ -0,0 +1,103 @@ +package com.sqx.modules.laundry.dao; + +import com.sqx.modules.laundry.model.Laundry; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +@Repository +public interface LaundryRepository extends JpaRepository { + + @Query(value = "select l.laundry_id as laundryId,l.laundry_name as laundryName,l.laundry_address as laundryAddress,l.longitude,l.latitude,l.sn_code as snCode,l.value, " + + "l.laundry_phone as laundryPhone,l.license_front as licenseFront,l.license_reverse as licenseReverse,l.laundry_user_id as laundryUserId," + + "l.laundry_user_ids as laundryUserIds,l.status,l.create_time as createTime,l.audit_content as auditContent,u.user_name as nickName," + + "l.remark,l.is_open as isOpen,l.scope as scope,l.max_scope as maxScope,l.rate,l.sys_user_ids as sysUserIds " + + "from laundry l " + + "left join tb_user u on l.laundry_user_id=u.user_id " + + "where l.laundry_id=:laundryId " + ,nativeQuery = true) + Map selectLaundryById(@Param("laundryId") Long laundryId); + + @Query(value = "select l.laundry_id as laundryId,l.laundry_name as laundryName,l.laundry_address as laundryAddress,l.longitude,l.latitude,l.sn_code as snCode,l.value, " + + "l.laundry_phone as laundryPhone,l.license_front as licenseFront,l.license_reverse as licenseReverse,l.laundry_user_id as laundryUserId," + + "l.laundry_user_ids as laundryUserIds,l.status,l.create_time as createTime,l.audit_content as auditContent,u.user_name as nickName ," + + "l.remark,l.is_open as isOpen,l.scope as scope,l.max_scope as maxScope,l.rate,l.sys_user_ids as sysUserIds " + + "from laundry l " + + "left join tb_user u on l.laundry_user_id=u.user_id " + + "where if(:nickName!='',u.user_name like concat('%',:nickName,'%'),1=1) " + + "and if(:laundryPhone!='',l.laundry_phone like concat('%',:laundryPhone,'%'),1=1) " + + "and if(:status!=-1,l.status=:status,1=1) " + + "and if(:laundryName!='',laundry_name like concat('%',:laundryName,'%'),1=1) order by l.create_time desc ", + countQuery = "select count(*) from laundry l " + + "left join tb_user u on l.laundry_user_id=u.user_id " + + "where if(:nickName!='',u.user_name like concat('%',:nickName,'%'),1=1) " + + "and if(:laundryPhone!='',l.laundry_phone like concat('%',:laundryPhone,'%'),1=1) " + + "and if(:status!=-1,l.status=:status,1=1) " + + "and if(:laundryName!='',laundry_name like concat('%',:laundryName,'%'),1=1) " + ,nativeQuery = true) + Page> selectLaundryList(Pageable pageable,@Param("nickName") String nickName,@Param("laundryPhone") String laundryPhone,@Param("status") Integer status,@Param("laundryName") String laundryName); + + @Query(value = "select l.laundry_id as laundryId,l.laundry_name as laundryName,l.laundry_address as laundryAddress,l.longitude,l.latitude,l.sn_code as snCode,l.value, " + + "l.laundry_phone as laundryPhone,l.license_front as licenseFront,l.license_reverse as licenseReverse,l.laundry_user_id as laundryUserId," + + "l.laundry_user_ids as laundryUserIds,l.status,l.create_time as createTime,l.audit_content as auditContent,u.user_name as nickName ," + + "l.remark,l.is_open as isOpen,l.scope as scope,l.max_scope as maxScope,l.rate,l.sys_user_ids as sysUserIds " + + "from laundry l " + + "left join tb_user u on l.laundry_user_id=u.user_id " + + "where if(:nickName!='',u.user_name like concat('%',:nickName,'%'),1=1) " + + "and if(:status!=-1,l.status=:status,1=1) " + + "and if(:laundryPhone!='',l.laundry_phone like concat('%',:laundryPhone,'%'),1=1) " + + "and if(:laundryName!='',laundry_name like concat('%',:laundryName,'%'),1=1) order by l.create_time desc ", + nativeQuery = true) + List> selectLaundryList(@Param("nickName") String nickName,@Param("laundryPhone") String laundryPhone, @Param("status") Integer status, @Param("laundryName") String laundryName); + + + @Query(value = "select * from (select (st_distance (point (l.longitude,l.latitude),point(:longitude,:latitude) ) *111195) AS distance,l.laundry_id as laundryId,l.laundry_name as laundryName,l.laundry_address as laundryAddress,l.longitude,l.latitude, " + + "l.laundry_phone as laundryPhone,l.license_front as licenseFront,l.license_reverse as licenseReverse,l.laundry_user_id as laundryUserId,l.sn_code as snCode,l.value," + + "l.laundry_user_ids as laundryUserIds,l.status,l.create_time as createTime,l.audit_content as auditContent,u.user_name as nickName ," + + "l.remark,l.is_open as isOpen,l.scope as scope,l.max_scope as maxScope,l.rate,l.sys_user_ids as sysUserIds " + + "from laundry l " + + "left join tb_user u on l.laundry_user_id=u.user_id " + + "where if(:nickName!='',u.user_name like concat('%',:nickName,'%'),1=1) " + + "and if(:status!=-1,l.status=:status,1=1) " + + "and if(:laundryPhone!='',l.laundry_phone like concat('%',:laundryPhone,'%'),1=1) " + + "and if(:laundryName!='',laundry_name like concat('%',:laundryName,'%'),1=1) ) a order by distance ", + countQuery = "select count(*) from laundry l " + + "left join tb_user u on l.laundry_user_id=u.user_id " + + "where if(:nickName!='',u.user_name like concat('%',:nickName,'%'),1=1) " + + "and if(:status!=-1,l.status=:status,1=1) " + + "and if(:laundryPhone!='',l.laundry_phone like concat('%',:laundryPhone,'%'),1=1) " + + "and if(:laundryName!='',laundry_name like concat('%',:laundryName,'%'),1=1) " + ,nativeQuery = true) + Page> selectLaundryLists(Pageable pageable,@Param("nickName") String nickName,@Param("laundryPhone") String laundryPhone,@Param("status") Integer status,@Param("laundryName") String laundryName,@Param("longitude") String longitude,@Param("latitude") String latitude); + + + + @Query(value = "select * from (select (st_distance (point (l.longitude,l.latitude),point(:longitude,:latitude) ) *111195) AS distance,l.* " + + " from laundry l,order_taking o where l.status=1 AND o.laundry_ids LIKE CONCAT('%',l.laundry_id,'%') and if(:goodsId!='', o.id =:goodsId,1=1)) a order by distance limit 1 ",nativeQuery = true) + Map selectLaundryByDistance(@Param("longitude") String longitude,@Param("latitude") String latitude,@Param("goodsId") Long goodsId); + + @Query(value = "select * from (select l.laundry_id as laundryId,l.laundry_name as laundryName," + + "(select ifnull(sum(o.laundry_money),0.00) from orders o where o.laundry_id=l.laundry_id) as money from laundry l " + + "where if(:laundryName!='',l.laundry_name like concat('%',:laundryName,'%'),1=1) " + + ") a order by money desc ", + countQuery = "select count(*) from laundry where if(:laundryName!='',l.laundry_name like concat('%',:laundryName,'%'),1=1) " + ,nativeQuery = true) + Page> selectLaundryMoneyStatistics(Pageable pageable, String laundryName); + + @Query(value = "select ifnull(sum(laundry_money),0.00) from orders where laundry_id=:laundryId and status=2 ",nativeQuery = true) + BigDecimal selectLaundryMoneyByLaundryId(String laundryId); + + @Query(value = "select * from laundry where laundry_user_id = :userId and if(:laundryName!='', laundry_name like concat('%',:laundryName,'%'), 1=1)",nativeQuery = true) + List getMyAllLaundryList(@Param("userId") Long userId,@Param("laundryName") String laundryName); + + @Query(value = "select * from laundry where laundry_user_id = :userId and if(:laundryName!='', laundry_name like concat('%',:laundryName,'%'), 1=1)",nativeQuery = true) + Page getMyAllLaundryLists(Pageable pageable, @Param("userId") Long userId,@Param("laundryName") String laundryName); + +} diff --git a/src/main/java/com/sqx/modules/laundry/model/Laundry.java b/src/main/java/com/sqx/modules/laundry/model/Laundry.java new file mode 100644 index 0000000..d19a3db --- /dev/null +++ b/src/main/java/com/sqx/modules/laundry/model/Laundry.java @@ -0,0 +1,166 @@ +package com.sqx.modules.laundry.model; + +import com.sqx.modules.app.entity.UserEntity; +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +/** + * @description laundry + * @author fang + * @date 2021-11-08 + */ +@Entity +@Data +@Table(name="laundry") +public class Laundry implements Serializable { + + private static final long serialVersionUID = 1L; + + + /** + * 站点 + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="laundry_id") + private Long laundryId; + + /** + * 名称 + */ + @Column(name="laundry_name") + private String laundryName; + + /** + * 地址 + */ + @Column(name="laundry_address") + private String laundryAddress; + + /** + * 电话 + */ + @Column(name="laundry_phone") + private String laundryPhone; + + /** + * 营业执照 正面 + */ + @Column(name="license_front") + private String licenseFront; + + + /** + * 营业执照 背面 + */ + @Column(name="license_reverse") + private String licenseReverse; + + + /** + * 用户id + */ + @Column(name="laundry_user_ids") + private String laundryUserIds; + + @Column + private Long laundryUserId; + /** + * 状态 + */ + @Column(name="status") + private Integer status; + + /** + * 创建时间 + */ + @Column(name="create_time") + private String createTime; + + /** + * 审核内容 + */ + @Column(name = "audit_content") + private String auditContent; + + /** + * 经度 + */ + @Column + private String longitude; + + /** + * 纬度 + */ + @Column + private String latitude; + + + /** + * sn码 飞鹅打印机参数 + */ + @Column + private String snCode; + + /** + * value 飞鹅打印机参数 + */ + @Column + private String value; + + /** + * 站点备注 + */ + @Column + private String remark; + + /** + * 是否打烊 1打烊 + */ + @Column + private Integer isOpen; + + /** + * 包邮范围 + */ + @Column + private Integer scope; + + /** + * 最大范围 + */ + @Column + private Integer maxScope; + + /** + * 站点抽成 + */ + @Column + private BigDecimal rate; + + @Column + private String sysUserIds; + + @Transient + private String teamPhone; + + /** + * 站长 + */ + @Transient + private UserEntity masterUser; + //师傅列表 + @Transient + private List workUserList; + //站点收益 + @Transient + private BigDecimal allMoney; + + public Laundry() { + } + +} diff --git a/src/main/java/com/sqx/modules/laundry/service/LaundryService.java b/src/main/java/com/sqx/modules/laundry/service/LaundryService.java new file mode 100644 index 0000000..7c5de7e --- /dev/null +++ b/src/main/java/com/sqx/modules/laundry/service/LaundryService.java @@ -0,0 +1,34 @@ +package com.sqx.modules.laundry.service; + + +import com.sqx.modules.chats.utils.Result; +import com.sqx.modules.laundry.model.Laundry; + +import java.math.BigDecimal; + +public interface LaundryService { + + Result saveLaundry(Laundry laundry); + + Result updateLaundry(Laundry laundry); + + Result updateLaundryIsOpen(Long laundryId,Integer isOpen); + + Result selectLaundryById(Long laundryId); + + Result selectLaundryDetails(Long laundryId); + + Result selectLaundryList(Integer page,Integer size,String nickName,String laundryPhone,Integer status,String laundryName,String longitude,String latitude); + + Result deleteLaundryById(Long laundryId); + + Result selectLaundryByDistance(String longitude,String latitude,Long goodsId); + + Result selectLaundryMoneyStatistics(Integer page,Integer size,String laundryName); + + BigDecimal selectLaundryMoneyByLaundryId(String laundryId); + + + Result deleteWork(Long laundryId, Long userId); + +} diff --git a/src/main/java/com/sqx/modules/laundry/service/LaundryServiceImpl.java b/src/main/java/com/sqx/modules/laundry/service/LaundryServiceImpl.java new file mode 100644 index 0000000..3a48b35 --- /dev/null +++ b/src/main/java/com/sqx/modules/laundry/service/LaundryServiceImpl.java @@ -0,0 +1,328 @@ +package com.sqx.modules.laundry.service; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.chats.utils.Result; +import com.sqx.modules.chats.utils.ResultUtil; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.service.SysUserService; +import com.sqx.modules.utils.fieYun.FeiYunUtils; +import org.apache.commons.lang3.StringUtils; +import org.checkerframework.checker.units.qual.A; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.*; + +@Service +public class LaundryServiceImpl implements LaundryService { + + @Autowired + private LaundryRepository laundryRepository; + @Autowired + private UserService userService; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private SysUserService sysUserService; + + + @Override + public Result saveLaundry(Laundry laundry) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + laundry.setCreateTime(sdf.format(new Date())); + laundry.setStatus(1); + if (laundry.getIsOpen() == null) { + laundry.setIsOpen(1); + } + Laundry save = laundryRepository.save(laundry); + if (StringUtils.isNotEmpty(laundry.getLaundryUserIds())) { + for (String userIdStr : laundry.getLaundryUserIds().split(",")) { + Long userId = Long.parseLong(userIdStr); + UserEntity userInfo = userService.selectUserById(userId); + //如果这个人是其他站点的人 则需要清空其他站点的信息 + if (userInfo.getLaundryId() != null && !userInfo.getLaundryId().equals(save.getLaundryId())) { + Laundry oldLaundry = laundryRepository.findById(userInfo.getLaundryId()).orElse(null); + if (oldLaundry != null) { + StringBuilder stringBuilder = new StringBuilder(); + for (String userIds : oldLaundry.getLaundryUserIds().split(",")) { + if (!userIds.equals(String.valueOf(userId))) { + stringBuilder.append(userIds).append(","); + } + } + String str = stringBuilder.toString(); + if (StringUtils.isNotEmpty(str)) { + if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') { + str = stringBuilder.substring(0, stringBuilder.length() - 1); + } + } + oldLaundry.setLaundryUserIds(str); + laundryRepository.save(oldLaundry); + } + } + userInfo.setLaundryId(save.getLaundryId()); + userService.updateById(userInfo); + } + } + + if (StringUtils.isNotEmpty(laundry.getSysUserIds())) { + for (String sysUserIdStr : laundry.getSysUserIds().split(",")) { + long sysUserId = Long.parseLong(sysUserIdStr); + SysUserEntity sysUserEntity = sysUserService.getById(sysUserId); + if (sysUserEntity.getLaundryId() != null && !sysUserEntity.getLaundryId().equals(save.getLaundryId())) { + Laundry oldLaundry = laundryRepository.findById(sysUserEntity.getLaundryId()).orElse(null); + if (oldLaundry != null) { + StringBuilder stringBuilder = new StringBuilder(); + for (String sysUserIdS : oldLaundry.getSysUserIds().split(",")) { + if (!sysUserIdS.equals(String.valueOf(sysUserId))) { + stringBuilder.append(sysUserIdS).append(","); + } + } + String str = stringBuilder.toString(); + if (StringUtils.isNotEmpty(str)) { + if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') { + str = stringBuilder.substring(0, stringBuilder.length() - 1); + } + } + oldLaundry.setSysUserIds(str); + laundryRepository.save(oldLaundry); + } + } + sysUserEntity.setLaundryId(save.getLaundryId()); + sysUserService.updateById(sysUserEntity); + } + } + + return ResultUtil.success(); + } + + @Override + public Result updateLaundry(Laundry laundry) { + //先清空之前绑定的 站长 + userService.updateUserInfoLaundryIdIsNull(laundry.getLaundryId()); + StringBuilder stringBuilder = new StringBuilder(); + if (StringUtils.isNotEmpty(laundry.getLaundryUserIds())) { + for (String userIdStr : laundry.getLaundryUserIds().split(",")) { + Long userId = Long.parseLong(userIdStr); + UserEntity userInfo = userService.selectUserById(userId); + if (userInfo != null) { + if (userInfo.getLaundryId() != null && !userInfo.getLaundryId().equals(laundry.getLaundryId())) { + Laundry oldLaundry = laundryRepository.findById(userInfo.getLaundryId()).orElse(null); + if (oldLaundry != null) { + StringBuilder stringBuilders = new StringBuilder(); + for (String userIds : oldLaundry.getLaundryUserIds().split(",")) { + if (!userIds.equals(String.valueOf(userId))) { + stringBuilders.append(userIds).append(","); + } + } + String str = stringBuilders.toString(); + if (StringUtils.isNotEmpty(str)) { + if (stringBuilders.charAt(stringBuilders.length() - 1) == ',') { + str = stringBuilders.substring(0, stringBuilders.length() - 1); + } + } + oldLaundry.setLaundryUserIds(str); + laundryRepository.save(oldLaundry); + } + } + + userInfo.setLaundryId(laundry.getLaundryId()); + userService.updateById(userInfo); + stringBuilder.append(userId).append(","); + } + + } + } + + + String str = stringBuilder.toString(); + if (StringUtils.isNotEmpty(str)) { + if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') { //s.length()-1获取字符串最后一位字符的索引,传入charAt方法获取索引对应的字符,判断是否为逗号 + str = stringBuilder.substring(0, stringBuilder.length() - 1); + } + } + laundry.setLaundryUserIds(str); + + + stringBuilder = new StringBuilder(); + if (StringUtils.isNotEmpty(laundry.getSysUserIds())) { + for (String userIdStr : laundry.getSysUserIds().split(",")) { + Long userId = Long.parseLong(userIdStr); + SysUserEntity userInfo = sysUserService.getById(userId); + if (userInfo != null) { + if (userInfo.getLaundryId() != null && !userInfo.getLaundryId().equals(laundry.getLaundryId())) { + Laundry oldLaundry = laundryRepository.findById(userInfo.getLaundryId()).orElse(null); + if (oldLaundry != null) { + StringBuilder stringBuilders = new StringBuilder(); + for (String userIds : oldLaundry.getSysUserIds().split(",")) { + if (!userIds.equals(String.valueOf(userId))) { + stringBuilders.append(userIds).append(","); + } + } + str = stringBuilders.toString(); + if (StringUtils.isNotEmpty(str)) { + if (stringBuilders.charAt(stringBuilders.length() - 1) == ',') { + str = stringBuilders.substring(0, stringBuilders.length() - 1); + } + } + oldLaundry.setSysUserIds(str); + laundryRepository.save(oldLaundry); + } + } + + userInfo.setLaundryId(laundry.getLaundryId()); + sysUserService.updateById(userInfo); + stringBuilder.append(userId).append(","); + } + + } + + str = stringBuilder.toString(); + if (StringUtils.isNotEmpty(str)) { + if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') { //s.length()-1获取字符串最后一位字符的索引,传入charAt方法获取索引对应的字符,判断是否为逗号 + str = stringBuilder.substring(0, stringBuilder.length() - 1); + } + } + laundry.setSysUserIds(str); + } + + + laundryRepository.save(laundry); + return ResultUtil.success(); + } + + @Override + public Result updateLaundryIsOpen(Long laundryId, Integer isOpen) { + Laundry laundry = laundryRepository.findById(laundryId).orElse(null); + laundry.setIsOpen(isOpen); + laundryRepository.save(laundry); + return ResultUtil.success(); + } + + + @Override + public Result selectLaundryById(Long laundryId) { + Map map = laundryRepository.selectLaundryById(laundryId); + return ResultUtil.success(map); + } + + @Override + public Result selectLaundryDetails(Long laundryId) { + Map map = laundryRepository.selectLaundryById(laundryId); + Map result = new HashMap<>(); + List userInfoList = new ArrayList<>(); + String laundryUserIds = String.valueOf(map.get("laundryUserIds")); + if (StringUtils.isNotEmpty(laundryUserIds) && !"null".equals(laundryUserIds)) { + String[] split = laundryUserIds.split(","); + for (String id : split) { + UserEntity userById = userService.selectUserById(Long.parseLong(id)); + userInfoList.add(userById); + } + } + List sysUserList = new ArrayList<>(); + String sysUserIds = String.valueOf(map.get("sysUserIds")); + if (StringUtils.isNotEmpty(sysUserIds) && !"null".equals(sysUserIds)) { + String[] split = sysUserIds.split(","); + for (String id : split) { + SysUserEntity userById = sysUserService.getById(Long.parseLong(id)); + sysUserList.add(userById); + } + } + result.put("sysUserList", userInfoList); + result.put("userInfoList", userInfoList); + for (String key : map.keySet()) { + result.put(key, map.get(key)); + } + return ResultUtil.success(result); + } + + @Override + public Result selectLaundryList(Integer page, Integer size, String nickName, String laundryPhone, Integer status, String laundryName, String longitude, String latitude) { + if (page == null || size == null) { + return ResultUtil.success(laundryRepository.selectLaundryList(nickName, laundryPhone, status != null ? status : -1, laundryName != null ? laundryName : "")); + } + Pageable pageable = PageRequest.of(page, size); + if (StringUtils.isNotEmpty(latitude) && StringUtils.isNotEmpty(longitude)) { + return ResultUtil.success(laundryRepository.selectLaundryLists(pageable, nickName, laundryPhone, status != null ? status : -1, laundryName != null ? laundryName : "", longitude, latitude)); + } + return ResultUtil.success(laundryRepository.selectLaundryList(pageable, nickName, laundryPhone, status != null ? status : -1, laundryName != null ? laundryName : "")); + } + + @Override + public Result deleteLaundryById(Long laundryId) { + laundryRepository.deleteById(laundryId); + return ResultUtil.success(); + } + @Override + public Result selectLaundryByDistance(String longitude, String latitude,Long goodsId) { + return ResultUtil.success(laundryRepository.selectLaundryByDistance(longitude, latitude,goodsId)); + } + + /** + * 绑定打印机推送 + * + * @param laundry + * @return + */ + public String addPrinter(Laundry laundry) { + String snlist = laundry.getSnCode() + "#" + laundry.getValue() + "#" + laundry.getLaundryName(); + String method = FeiYunUtils.addprinter(snlist); + JSONObject jsonObject = JSON.parseObject(method); + if (jsonObject != null) { + if ("0".equals(jsonObject.getString("ret"))) { + JSONObject data = jsonObject.getJSONObject("data"); + JSONArray no = data.getJSONArray("no"); + if (no.size() > 0) { + return no.getString(0); + } + return "ok"; + } + return jsonObject.getString("msg"); + } + return "pos机添加失败!"; + } + + @Override + public Result selectLaundryMoneyStatistics(Integer page, Integer size, String laundryName) { + Pageable pageable = PageRequest.of(page, size); + return ResultUtil.success(laundryRepository.selectLaundryMoneyStatistics(pageable, laundryName)); + } + + @Override + public BigDecimal selectLaundryMoneyByLaundryId(String laundryId) { + return laundryRepository.selectLaundryMoneyByLaundryId(laundryId); + } + + + @Override + public Result deleteWork(Long laundryId, Long userId) { + userService.setUserLaundry(userId); + StringBuilder buffer = new StringBuilder(); + Laundry laundry = laundryRepository.getOne(laundryId); + String[] split = laundry.getLaundryUserIds().split(","); + for (String s : split) { + if (!s.equals(userId.toString())) { + if (buffer.length() > 0) { + buffer.append(","); + } + buffer.append(s); + } + } + laundry.setLaundryUserIds(buffer.toString()); + laundryRepository.save(laundry); + return ResultUtil.success(); + + } + +} diff --git a/src/main/java/com/sqx/modules/member/controller/MemberController.java b/src/main/java/com/sqx/modules/member/controller/MemberController.java new file mode 100644 index 0000000..370f8b8 --- /dev/null +++ b/src/main/java/com/sqx/modules/member/controller/MemberController.java @@ -0,0 +1,56 @@ +package com.sqx.modules.member.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.member.entity.Member; +import com.sqx.modules.member.service.MemberService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "会员特权", tags = {"会员特权"}) +@RequestMapping(value = "/member") +public class MemberController { + + + @Autowired + private MemberService memberService; + + @GetMapping("/selectMemberList") + @ApiOperation("查询列表(不带分页)") + public Result selectMemberList(){ + return memberService.selectMemberList(); + } + + + @GetMapping("/selectMemberPage") + @ApiOperation("查询列表(带分页") + public Result selectMemberPage(Integer page,Integer limit){ + return memberService.selectMemberPage(page, limit); + } + + @PostMapping("/updateMember") + @ApiOperation("修改会员特权") + public Result updateMember(@RequestBody Member member){ + return memberService.updateMember(member); + } + + + @PostMapping("/deleteMemberById") + @ApiOperation("删除会员特权") + public Result deleteMemberById(Long memberId){ + return memberService.deleteMemberById(memberId); + } + + @PostMapping("/insertMember") + @ApiOperation("新增会员特权") + public Result insertMember(@RequestBody Member member){ + return memberService.insertMember(member); + } + + + + + +} diff --git a/src/main/java/com/sqx/modules/member/controller/app/AppMemberController.java b/src/main/java/com/sqx/modules/member/controller/app/AppMemberController.java new file mode 100644 index 0000000..eb1dad2 --- /dev/null +++ b/src/main/java/com/sqx/modules/member/controller/app/AppMemberController.java @@ -0,0 +1,27 @@ +package com.sqx.modules.member.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.member.entity.Member; +import com.sqx.modules.member.service.MemberService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "会员特权", tags = {"会员特权"}) +@RequestMapping(value = "/app/member") +public class AppMemberController { + + + @Autowired + private MemberService memberService; + + @GetMapping("/selectMemberList") + @ApiOperation("查询列表(不带分页)") + public Result selectMemberList(){ + return memberService.selectMemberList(); + } + + +} diff --git a/src/main/java/com/sqx/modules/member/dao/MemberDao.java b/src/main/java/com/sqx/modules/member/dao/MemberDao.java new file mode 100644 index 0000000..d2ff401 --- /dev/null +++ b/src/main/java/com/sqx/modules/member/dao/MemberDao.java @@ -0,0 +1,12 @@ +package com.sqx.modules.member.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.member.entity.Member; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface MemberDao extends BaseMapper { + + + +} diff --git a/src/main/java/com/sqx/modules/member/entity/Member.java b/src/main/java/com/sqx/modules/member/entity/Member.java new file mode 100644 index 0000000..0eb0c4c --- /dev/null +++ b/src/main/java/com/sqx/modules/member/entity/Member.java @@ -0,0 +1,42 @@ +package com.sqx.modules.member.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description member + * @author fang + * @date 2021-06-19 + */ +@Data +public class Member implements Serializable { + + private static final long serialVersionUID = 1L; + + + /** + * 会员特权id + */ + @TableId(type = IdType.AUTO) + private Integer memberId; + + /** + * 特权图标 + */ + private String memberImg; + + /** + * 特权名称 + */ + private String memberName; + + /** + * 排序 + */ + private String sort; + + public Member() {} +} diff --git a/src/main/java/com/sqx/modules/member/service/MemberService.java b/src/main/java/com/sqx/modules/member/service/MemberService.java new file mode 100644 index 0000000..655e9a2 --- /dev/null +++ b/src/main/java/com/sqx/modules/member/service/MemberService.java @@ -0,0 +1,19 @@ +package com.sqx.modules.member.service; + +import com.sqx.common.utils.Result; +import com.sqx.modules.member.entity.Member; + + +public interface MemberService { + + Result insertMember(Member member); + + Result updateMember(Member member); + + Result deleteMemberById(Long memberId); + + Result selectMemberList(); + + Result selectMemberPage(Integer page,Integer limit); + +} diff --git a/src/main/java/com/sqx/modules/member/service/impl/MemberServiceImpl.java b/src/main/java/com/sqx/modules/member/service/impl/MemberServiceImpl.java new file mode 100644 index 0000000..742e2a0 --- /dev/null +++ b/src/main/java/com/sqx/modules/member/service/impl/MemberServiceImpl.java @@ -0,0 +1,56 @@ +package com.sqx.modules.member.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.member.dao.MemberDao; +import com.sqx.modules.member.entity.Member; +import com.sqx.modules.member.service.MemberService; +import org.springframework.stereotype.Service; + +@Service +public class MemberServiceImpl extends ServiceImpl implements MemberService { + + + @Override + public Result insertMember(Member member){ + baseMapper.insert(member); + return Result.success(); + } + + @Override + public Result updateMember(Member member){ + baseMapper.updateById(member); + return Result.success(); + } + + @Override + public Result deleteMemberById(Long memberId){ + baseMapper.deleteById(memberId); + return Result.success(); + } + + @Override + public Result selectMemberList(){ + return Result.success().put("data",baseMapper.selectList(new QueryWrapper().orderByAsc("sort"))); + } + + @Override + public Result selectMemberPage(Integer page,Integer limit){ + IPage pages=new Page<>(page,limit); + return Result.success().put("data",new PageUtils(baseMapper.selectPage(pages,new QueryWrapper().orderByAsc("sort")))); + } + + + +} + + + + + + + diff --git a/src/main/java/com/sqx/modules/message/controller/ActivityMessageController.java b/src/main/java/com/sqx/modules/message/controller/ActivityMessageController.java new file mode 100644 index 0000000..89bca5a --- /dev/null +++ b/src/main/java/com/sqx/modules/message/controller/ActivityMessageController.java @@ -0,0 +1,84 @@ +package com.sqx.modules.message.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.message.entity.ActivityMessageInfo; +import com.sqx.modules.message.service.ActivityMessageService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @author fang + * @date 2020/7/13 + */ +@RestController +@Api(value = "消息管理", tags = {"消息管理"}) +@RequestMapping(value = "/ActivityMessage") +public class ActivityMessageController { + + @Autowired + private ActivityMessageService activityMessageService; + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台公告详情") + @ResponseBody + public Result getMessage(@PathVariable Integer id) { + return Result.success().put("data",activityMessageService.findOne(Long.valueOf(id))); + } + + @RequestMapping(value = "/add", method = RequestMethod.POST) + @ApiOperation("管理平台和用户端通用接口添加公告") + @ResponseBody + public Result addMessage(@RequestBody ActivityMessageInfo messageInfo) { + activityMessageService.saveBody(messageInfo); + return Result.success(); + } + + @RequestMapping(value = "/update", method = RequestMethod.POST) + @ApiOperation("管理平台修改公告接口") + @ResponseBody + public Result uUpdate(@RequestBody ActivityMessageInfo messageInfo) { + activityMessageService.updateBody(messageInfo); + return Result.success(); + } + + @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台删除公告接口") + public Result deleteMessage(@PathVariable int id) { + activityMessageService.delete(id); + return Result.success(); + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + @ApiOperation("管理平台获取全部公告接口") + @ResponseBody + public Result getMessageList() { + List all = activityMessageService.findAll(); + return Result.success().put("data",all); + } + + @RequestMapping(value = "/page/{state}/{page}/{limit}", method = RequestMethod.GET) + @ApiOperation("管理平台分页查询公告接口") + @ResponseBody + public Result getBodyPage(@PathVariable String state, @PathVariable Integer page, @PathVariable int limit) { + return Result.success().put("data",activityMessageService.find(state, page,limit)); + } + + @RequestMapping(value = "/type/{type}/{page}/{limit}", method = RequestMethod.GET) + @ApiOperation("管理平台通过类型获取接口 type1为公告2位用户反馈 3为系统消息 4为订单信息 5为用户消息 6客服消息") + @ResponseBody + public Result findType(@PathVariable Integer type, @PathVariable Integer page, @PathVariable int limit) { + return Result.success().put("data",activityMessageService.findType(type, page,limit)); + } + + @RequestMapping(value = "/findType/{userId}/{type}/{page}/{limit}", method = RequestMethod.GET) + @ApiOperation("用户端获取消息列表 type 4为订单信息 5为用户消息") + @ResponseBody + public Result findType(@PathVariable String userId, @PathVariable String type, @PathVariable Integer page, @PathVariable int limit) { + return Result.success().put("data",activityMessageService.findTypeByUserId(type, userId,page,limit)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/message/controller/MessageController.java b/src/main/java/com/sqx/modules/message/controller/MessageController.java new file mode 100644 index 0000000..817c0d0 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/controller/MessageController.java @@ -0,0 +1,144 @@ +package com.sqx.modules.message.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author fang + * @date 2020/7/13 + */ +@RestController +@Api(value = "消息管理", tags = {"消息管理"}) +@RequestMapping(value = "/message") +public class MessageController { + + @Autowired + private MessageService messageService; + + @PostMapping("/auditMessage") + @ApiOperation("审核投诉") + public Result auditMessage(Long messageId,Integer status,String auditContent){ + return messageService.auditMessage(messageId,status,auditContent); + } + + + @RequestMapping(value = "/selectMessageByUserId", method = RequestMethod.GET) + @ApiOperation("查询用户消息") + @ResponseBody + public Result selectUserRecharge(int page, int limit, Long userId,Integer state){ + Map map=new HashMap<>(); + map.put("page",page); + map.put("limit",limit); + map.put("userId",userId); + map.put("state",state); + return Result.success().put("data",messageService.selectMessageList(map)); + } + + @RequestMapping(value = "/selectMessageByType", method = RequestMethod.GET) + @ApiOperation("获取消息 type1为公告2位用户反馈 3为系统消息 4为订单信息 5为用户消息 6客服消息 ") + @ResponseBody + public Result selectMessageByType(int page, int limit,Integer state){ + Map map=new HashMap<>(); + map.put("page",page); + map.put("limit",limit); + map.put("userId",null); + map.put("state",state); + return Result.success().put("data",messageService.selectMessageList(map)); + } + + @RequestMapping(value = "/selectMessageDetails", method = RequestMethod.GET) + @ApiOperation("获取消息详细信息") + @ResponseBody + public Result selectMessageDetails(Long id){ + return Result.success().put("data",messageService.selectMessageById(id)); + } + + @RequestMapping(value = "/updateMessage", method = RequestMethod.POST) + @ApiOperation("修改消息") + @ResponseBody + public Result updateMessage(@RequestBody MessageInfo messageInfo){ + return Result.success().put("data",messageService.update(messageInfo)); + } + + + @RequestMapping(value = "/deleteMessageById", method = RequestMethod.POST) + @ApiOperation("删除消息") + @ResponseBody + public Result deleteMessageById(Long id){ + return Result.success().put("data",messageService.delete(id)); + } + + @RequestMapping(value = "/insertMessage", method = RequestMethod.POST) + @ApiOperation("添加消息") + @ResponseBody + public Result insertMessage(MessageInfo messageInfo){ + return Result.success().put("data",messageService.saveBody(messageInfo)); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台公告详情") + @ResponseBody + public Result getMessage(@PathVariable Long id) { + return Result.success().put("data",messageService.selectMessageById(id)); + } + + @RequestMapping(value = "/add", method = RequestMethod.POST) + @ApiOperation("管理平台和用户端通用接口添加公告") + @ResponseBody + public Result addMessage(@RequestBody MessageInfo messageInfo) { + messageService.saveBody(messageInfo); + return Result.success(); + } + + @RequestMapping(value = "/update", method = RequestMethod.POST) + @ApiOperation("管理平台修改公告接口") + @ResponseBody + public Result uUpdate(@RequestBody MessageInfo messageInfo) { + messageService.update(messageInfo); + return Result.success(); + } + + @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) + @ApiOperation("管理平台删除公告接口") + public Result deleteMessage(@PathVariable Long id) { + messageService.delete(id); + return Result.success(); + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + @ApiOperation("管理平台获取全部公告接口") + @ResponseBody + public Result getMessageList(int page,int limit) { + Map map=new HashMap<>(); + map.put("page",page); + map.put("limit",limit); + map.put("userId",null); + map.put("state",null); + map.put("type",null); + return Result.success().put("data",messageService.selectMessageList(map)); + } + + @RequestMapping(value = "/page/{state}/{page}/{limit}", method = RequestMethod.GET) + @ApiOperation("管理平台分页查询公告接口") + @ResponseBody + public Result getBodyPage(@PathVariable Integer state, @PathVariable Integer page, @PathVariable int limit) { + Map map=new HashMap<>(); + map.put("page",page); + map.put("limit",limit); + map.put("state",state); + map.put("type",null); + map.put("userId",null); + return Result.success().put("data",messageService.selectMessageList(map)); + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/message/controller/app/AppMessageController.java b/src/main/java/com/sqx/modules/message/controller/app/AppMessageController.java new file mode 100644 index 0000000..913c424 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/controller/app/AppMessageController.java @@ -0,0 +1,94 @@ +package com.sqx.modules.message.controller.app; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author fang + * @date 2020/7/13 + */ +@RestController +@Api(value = "消息管理", tags = {"消息管理"}) +@RequestMapping(value = "/app/message") +public class AppMessageController { + + @Autowired + private MessageService messageService; + + @Login + @RequestMapping(value = "/selectMessageByUserId", method = RequestMethod.GET) + @ApiOperation("查询用户消息") + @ResponseBody + public Result selectUserRecharge(int page, int limit,@RequestAttribute("userId") Long userId,Integer state,Integer platform,Integer status){ + Map map=new HashMap<>(); + map.put("page",page); + map.put("limit",limit); + map.put("userId",userId); + map.put("state",state); + map.put("platform",platform); + map.put("status",status); + PageUtils pageUtils = messageService.selectMessageList(map); + messageService.updateSendState(userId,state); + return Result.success().put("data",pageUtils); + } + + @Login + @RequestMapping(value = "/selectMessageByUserIdLimit1", method = RequestMethod.GET) + @ApiOperation("查询用户消息") + @ResponseBody + public Result selectMessageByUserIdLimit1(@RequestAttribute("userId") Long userId){ + Map map=new HashMap<>(); + map.put("page",1); + map.put("limit",1); + map.put("userId",userId); + return Result.success().put("data",messageService.selectMessageList(map)); + } + + @Login + @GetMapping("/selectMessageById") + @ApiOperation("根据id查详情") + public Result selectMessageById(Long id){ + return Result.success().put("data",messageService.getById(id)); + } + + + @Login + @PostMapping("/insertMessage") + @ApiOperation("添加投诉") + public Result insertMessage(@RequestBody MessageInfo messageInfo){ + messageInfo.setIsSee("2"); + messageService.saveBody(messageInfo); + return Result.success(); + } + + @Login + @PostMapping("/updateMessage") + @ApiOperation("修改") + public Result updateMessage(@RequestBody MessageInfo messageInfo){ + messageService.update(messageInfo); + return Result.success(); + } + + @Login + @PostMapping("/deleteMessage") + @ApiOperation("删除") + public Result deleteMessage(Long id){ + messageService.delete(id); + return Result.success(); + } + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/message/dao/ActivityMessageInfoDao.java b/src/main/java/com/sqx/modules/message/dao/ActivityMessageInfoDao.java new file mode 100644 index 0000000..55204d0 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/dao/ActivityMessageInfoDao.java @@ -0,0 +1,28 @@ +package com.sqx.modules.message.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.message.entity.ActivityMessageInfo; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + * @author fang + * @date 2020/7/9 + */ +@Mapper +public interface ActivityMessageInfoDao extends BaseMapper { + + IPage find(Page page,@Param("state") String state); + + IPage findType(Page page,@Param("type") Integer type); + + IPage findTypeByUserId(Page page,@Param("type")String type,@Param("userId") String userId); + + Integer updateState(@Param("state") String state, @Param("id") Long id); + + Integer updateSendState(@Param("sendState") String sendState, @Param("id") Long id); + + +} diff --git a/src/main/java/com/sqx/modules/message/dao/MessageInfoDao.java b/src/main/java/com/sqx/modules/message/dao/MessageInfoDao.java new file mode 100644 index 0000000..ce118bb --- /dev/null +++ b/src/main/java/com/sqx/modules/message/dao/MessageInfoDao.java @@ -0,0 +1,21 @@ +package com.sqx.modules.message.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.Result; +import com.sqx.modules.message.entity.MessageInfo; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + * @author fang + * @date 2020/7/9 + */ +@Mapper +public interface MessageInfoDao extends BaseMapper { + + int updateSendState(@Param("userId") Long userId,@Param("state") Integer state); + + int getNewOrderCount(@Param("userId") Long userId); + +} diff --git a/src/main/java/com/sqx/modules/message/entity/ActivityMessageInfo.java b/src/main/java/com/sqx/modules/message/entity/ActivityMessageInfo.java new file mode 100644 index 0000000..ec4bbce --- /dev/null +++ b/src/main/java/com/sqx/modules/message/entity/ActivityMessageInfo.java @@ -0,0 +1,49 @@ +package com.sqx.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author fang + * @date 2020/7/13 + */ +@Data +@TableName("activity_message_info") +public class ActivityMessageInfo implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.INPUT) + private long id; + + private String createAt; + + private String content; + + private String title; + + private String image; + + private String url; + + private String sendState; + + private String sendTime; + + private String isSee; + + private String state; + + private String type; + + private String userId; + + private String userName; + + private String platform; + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/message/entity/MessageInfo.java b/src/main/java/com/sqx/modules/message/entity/MessageInfo.java new file mode 100644 index 0000000..1e55e90 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/entity/MessageInfo.java @@ -0,0 +1,125 @@ +package com.sqx.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.taking.entity.OrderTaking; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author fang + * @date 2020/7/13 + */ +@Data +@TableName("message_info") +public class MessageInfo implements Serializable { + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 消息id + */ + private Long id; + + /** + * 内容 + */ + private String content; + + /** + * 创建时间 + */ + private String createAt; + + /** + * 图片 + */ + private String image; + + /** + * is_see + */ + private String isSee; + + /** + * send_state + */ + private String sendState; + + /** + * send_time + */ + private String sendTime; + + /** + * 分类 + */ + private String state; + + /** + * 标题 + */ + private String title; + + /** + * 地址 + */ + private String url; + + /** + * type + */ + private String type; + + /** + * platform + */ + private Integer platform; + + /** + * 用户id + */ + private String userId; + + /** + * 用户名 + */ + private String userName; + + /** + * 审核内容 + */ + private String auditContent; + + /** + * 审核状态 1不做处理 2封号 3下架内容 + */ + private Integer status; + + /** + * 被举报用户 + */ + private String byUserId; + + @TableField(exist = false) + private String byUserName; + + /** + * 来源id + */ + private Long platformId; + + + @TableField(exist = false) + private Orders orders; + + @TableField(exist = false) + private OrderTaking orderTaking; + + public MessageInfo() {} + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/message/service/ActivityMessageService.java b/src/main/java/com/sqx/modules/message/service/ActivityMessageService.java new file mode 100644 index 0000000..ca9db21 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/service/ActivityMessageService.java @@ -0,0 +1,34 @@ +package com.sqx.modules.message.service; + + +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.message.entity.ActivityMessageInfo; + +import java.util.List; + +public interface ActivityMessageService { + + int saveBody(ActivityMessageInfo messageInfo); + + List findAll(); + + ActivityMessageInfo findOne(long id); + + ActivityMessageInfo selectById(long id); + + int delete(long id); + + PageUtils find(String state, int page,int limit); + + int updateBody(ActivityMessageInfo userInfo); + + PageUtils findType(Integer type, int page,int limit); + + int updateState(String state, Long id); + + int updateSendState(String state, Long id); + + PageUtils findTypeByUserId( String type,String userId, int page,int limit); + + +} diff --git a/src/main/java/com/sqx/modules/message/service/MessageService.java b/src/main/java/com/sqx/modules/message/service/MessageService.java new file mode 100644 index 0000000..91a05b6 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/service/MessageService.java @@ -0,0 +1,30 @@ +package com.sqx.modules.message.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.message.entity.MessageInfo; +import org.apache.ibatis.annotations.Param; +import org.springframework.web.bind.annotation.RequestAttribute; + +import java.util.Map; + +public interface MessageService extends IService { + + PageUtils selectMessageList(Map params); + + int saveBody(MessageInfo messageInfo); + + int update(MessageInfo messageInfo); + + int delete(Long id); + + MessageInfo selectMessageById(Long id); + + int updateSendState(Long userId,Integer state); + + Result auditMessage(Long messageId,Integer status,String auditContent); + + int getNewOrderCount(Long userId); +} diff --git a/src/main/java/com/sqx/modules/message/service/impl/ActivityMessageServiceImpl.java b/src/main/java/com/sqx/modules/message/service/impl/ActivityMessageServiceImpl.java new file mode 100644 index 0000000..1a295a7 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/service/impl/ActivityMessageServiceImpl.java @@ -0,0 +1,94 @@ +package com.sqx.modules.message.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.message.dao.ActivityMessageInfoDao; +import com.sqx.modules.message.entity.ActivityMessageInfo; +import com.sqx.modules.message.service.ActivityMessageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * 消息 + */ +@Service +public class ActivityMessageServiceImpl extends ServiceImpl implements ActivityMessageService { + + @Autowired + private ActivityMessageInfoDao activityMessageInfoDao; + + @Override + public List findAll() { + return activityMessageInfoDao.selectList(null); + } + + @Override + public int saveBody(ActivityMessageInfo messageInfo) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + messageInfo.setCreateAt(sdf.format(now)); + return activityMessageInfoDao.insert(messageInfo); + } + + @Override + public ActivityMessageInfo findOne(long id) { + return activityMessageInfoDao.selectById(id); + } + + @Override + public ActivityMessageInfo selectById(long id) { + return activityMessageInfoDao.selectById(id); + } + + @Override + public int delete(long id) { + activityMessageInfoDao.deleteById(id); + return 1; + } + + @Override + public PageUtils find(String state, int page,int limit) { + Page pages = new Page<>(page, limit); + return new PageUtils(activityMessageInfoDao.find(pages,state)); + } + + @Override + @Transactional + public int updateBody(ActivityMessageInfo userInfo) { + activityMessageInfoDao.updateById(userInfo); + return 1; + } + + @Override + public PageUtils findType(Integer type, int page,int limit) { + Page pages = new Page<>(page, limit); + return new PageUtils(activityMessageInfoDao.findType(pages,type)); + } + + @Override + @Transactional + public int updateState(String state, Long id) { + return activityMessageInfoDao.updateState(state,id); + } + + @Override + @Transactional + public int updateSendState(String state, Long id) { + return activityMessageInfoDao.updateSendState(state,id); + } + + @Override + public PageUtils findTypeByUserId( String type,String userId, int page,int limit) { + Page pages = new Page<>(page, limit); + return new PageUtils(activityMessageInfoDao.findTypeByUserId(pages,type,userId)); + } + + + +} diff --git a/src/main/java/com/sqx/modules/message/service/impl/MessageServiceImpl.java b/src/main/java/com/sqx/modules/message/service/impl/MessageServiceImpl.java new file mode 100644 index 0000000..8246433 --- /dev/null +++ b/src/main/java/com/sqx/modules/message/service/impl/MessageServiceImpl.java @@ -0,0 +1,182 @@ +package com.sqx.modules.message.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.message.dao.MessageInfoDao; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.taking.dao.OrderTakingDao; +import com.sqx.modules.taking.entity.Game; +import com.sqx.modules.taking.entity.OrderTaking; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * 消息 + */ +@Service +public class MessageServiceImpl extends + ServiceImpl implements MessageService { + + @Autowired + private MessageInfoDao messageInfoDao; + @Autowired + private OrdersService ordersService; + @Autowired + private OrderTakingDao orderTakingDao; + @Autowired + private UserService userService; + + @Override + public Result auditMessage(Long messageId, Integer status, String auditContent) { + MessageInfo messageInfo = baseMapper.selectById(messageId); + messageInfo.setStatus(status); + UserEntity byId = userService.getById(messageInfo.getByUserId()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if (status == 2) { + if (byId.getStatus().equals(1)) { + + //2封号 + byId.setStatus(2); + userService.updateById(byId); + //任务下架 + orderTakingDao.updateTakingStatusByUserId(byId.getUserId()); + MessageInfo messageInfos = new MessageInfo(); + messageInfos.setContent("当前账号存在违规行为,已被系统封禁,如有疑问,请联系客服!"); + messageInfos.setTitle("账号封禁通知"); + messageInfos.setState(String.valueOf(4)); + messageInfos.setUserName(byId.getUserName()); + messageInfos.setUserId(String.valueOf(byId.getUserId())); + messageInfos.setCreateAt(sdf.format(new Date())); + messageInfos.setIsSee("0"); + baseMapper.insert(messageInfos); + } + + } else if (status == 3) { + //3下架 + if (messageInfo.getPlatform() == 3) { + + } else if (messageInfo.getPlatform() == 4) { + OrderTaking orderTaking = orderTakingDao.selectById(messageInfo.getPlatformId()); + if (orderTaking != null) { + byId = userService.getById(orderTaking.getUserId()); + orderTakingDao.deleteById(messageInfo.getPlatformId()); + MessageInfo messageInfos = new MessageInfo(); + String content = orderTaking.getGameId(); + if (content.length() > 5) { + content = content.substring(0, 5) + "..."; + } + messageInfos.setContent("您发布的服务:" + content + ",涉及违规,已做删除处理,如有疑问请联系客服!"); + messageInfos.setTitle("接单封禁通知"); + messageInfos.setState(String.valueOf(4)); + messageInfos.setUserName(byId.getUserName()); + messageInfos.setUserId(String.valueOf(byId.getUserId())); + messageInfos.setCreateAt(sdf.format(new Date())); + messageInfos.setIsSee("0"); + baseMapper.insert(messageInfos); + } + } + } + messageInfo.setAuditContent(auditContent); + baseMapper.updateById(messageInfo); + return Result.success(); + } + + @Override + public int getNewOrderCount(Long userId) { + int newOrderCount = baseMapper.getNewOrderCount(userId); + + baseMapper.updateSendState(userId, 6); + return newOrderCount; + } + + @Override + public PageUtils selectMessageList(Map params) { + Long userId = (Long) params.get("userId"); + Integer state = (Integer) params.get("state"); + Integer type = (Integer) params.get("type"); + IPage page = this.page( + new Query().getPage(params), + new QueryWrapper() + .eq(userId != null, "user_id", userId) + .eq(state != null, "state", state) + .eq(type != null, "type", type).orderByDesc("create_at") + ); + List records = page.getRecords(); + if (records.size() > 0) { + for (MessageInfo messageInfo : records) { + if (state != null && state == 9) { + if (StringUtils.isNotEmpty(messageInfo.getType())) { + Orders orders = ordersService.getById(Long.parseLong(messageInfo.getType())); + messageInfo.setOrders(orders); + if (orders != null) { + OrderTaking orderTaking = orderTakingDao.selectById(orders.getOrderTakingId()); + messageInfo.setOrderTaking(orderTaking); + } + } + } + if (messageInfo.getUserId() != null) { + UserEntity user = userService.getById(messageInfo.getUserId()); + if (user != null) { + messageInfo.setUserName(user.getUserName()); + } + } + if (messageInfo.getByUserId() != null) { + UserEntity user = userService.getById(messageInfo.getByUserId()); + if (user != null) { + messageInfo.setByUserName(user.getUserName()); + } + } + + } + } + + return new PageUtils(page); + } + + @Override + public int saveBody(MessageInfo messageInfo) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + messageInfo.setCreateAt(sdf.format(now)); + messageInfo.setStatus(0); + return messageInfoDao.insert(messageInfo); + } + + @Override + public int update(MessageInfo messageInfo) { + return messageInfoDao.updateById(messageInfo); + } + + @Override + public int delete(Long id) { + return messageInfoDao.deleteById(id); + } + + @Override + public MessageInfo selectMessageById(Long id) { + return messageInfoDao.selectById(id); + } + + @Override + public int updateSendState(Long userId, Integer state) { + return messageInfoDao.updateSendState(userId, state); + } + + +} diff --git a/src/main/java/com/sqx/modules/operatorsLog/controller/AdminOperatorsLogController.java b/src/main/java/com/sqx/modules/operatorsLog/controller/AdminOperatorsLogController.java new file mode 100644 index 0000000..8240934 --- /dev/null +++ b/src/main/java/com/sqx/modules/operatorsLog/controller/AdminOperatorsLogController.java @@ -0,0 +1,54 @@ +package com.sqx.modules.operatorsLog.controller; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.operatorsLog.entity.OperatorsLog; +import com.sqx.modules.operatorsLog.service.OperatorsLogService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + *

+ * 前端控制器 + *

+ * + * @author www.javacoder.top + * @since 2022-11-17 + */ +@RestController +@Api(value = "压桶修改日志", tags = {"压桶修改日志"}) +@RequestMapping("/admin/operatorsLog/") +public class AdminOperatorsLogController { + @Autowired + private OperatorsLogService operatorsLogService; + + @GetMapping(value = "getOperatorsLogList") + @ApiOperation("获取压桶修改日志列表") + public Result getOperatorsLogList(Integer page, Integer limit, OperatorsLog operatorsLog) { + return Result.success().put("data", operatorsLogService.getOperatorsLogList(page, limit, operatorsLog)); + } + + @RequestMapping(value = "deleteLogById") + @ApiOperation("根据id删除日志") + public Result deleteLogById(Long logId) { + operatorsLogService.removeById(logId); + return Result.success(); + } + + @RequestMapping(value = "deleteLogAll") + @ApiOperation("删除所有日志") + public Result deleteLogAll() { + operatorsLogService.remove(new QueryWrapper().eq("1", 1)); + return Result.success(); + } + @ApiOperation("获取压桶统计") + @GetMapping(value = "getBucketData") + public Result getBucketData(String time,Integer flag) { + return Result.success().put("data", operatorsLogService.getBucketData(time,flag)); + } + +} + diff --git a/src/main/java/com/sqx/modules/operatorsLog/controller/AppOperatorsLogController.java b/src/main/java/com/sqx/modules/operatorsLog/controller/AppOperatorsLogController.java new file mode 100644 index 0000000..1401173 --- /dev/null +++ b/src/main/java/com/sqx/modules/operatorsLog/controller/AppOperatorsLogController.java @@ -0,0 +1,42 @@ +package com.sqx.modules.operatorsLog.controller; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.operatorsLog.entity.OperatorsLog; +import com.sqx.modules.operatorsLog.service.OperatorsLogService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + *

+ * 前端控制器 + *

+ * + * @author www.javacoder.top + * @since 2022-11-17 + */ +@RestController +@Api(value = "压桶修改日志", tags = {"压桶修改日志"}) +@RequestMapping("/app/operatorsLog/") +public class AppOperatorsLogController { + @Autowired + private OperatorsLogService operatorsLogService; + + @Login + @GetMapping(value = "getOperatorsLogList") + @ApiOperation("获取压桶修改日志列表") + public Result getOperatorsLogList(@RequestAttribute("userId") Long userId, Integer page, Integer limit, OperatorsLog operatorsLog) { + operatorsLog.setUserId(userId); + return Result.success().put("data", operatorsLogService.getOperatorsLogList(page, limit, operatorsLog)); + } + + +} + diff --git a/src/main/java/com/sqx/modules/operatorsLog/dao/OperatorsLogDao.java b/src/main/java/com/sqx/modules/operatorsLog/dao/OperatorsLogDao.java new file mode 100644 index 0000000..0591506 --- /dev/null +++ b/src/main/java/com/sqx/modules/operatorsLog/dao/OperatorsLogDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.operatorsLog.dao; + +import com.sqx.modules.operatorsLog.entity.OperatorsLog; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + *

+ * Mapper 接口 + *

+ * + * @author www.javacoder.top + * @since 2022-11-17 + */ +@Mapper +public interface OperatorsLogDao extends BaseMapper { + + Integer getBucketData(@Param("time") String time, @Param("flag") Integer flag, @Param("type") Integer type); +} diff --git a/src/main/java/com/sqx/modules/operatorsLog/entity/OperatorsLog.java b/src/main/java/com/sqx/modules/operatorsLog/entity/OperatorsLog.java new file mode 100644 index 0000000..5cd8ef6 --- /dev/null +++ b/src/main/java/com/sqx/modules/operatorsLog/entity/OperatorsLog.java @@ -0,0 +1,96 @@ +package com.sqx.modules.operatorsLog.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.SqlCondition; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; +import org.apache.ibatis.jdbc.SQL; + +import java.io.Serializable; +import java.util.Date; + +/** + *

+ * + *

+ * + * @author www.javacoder.top + * @since 2022-11-17 + */ +@Data +public class OperatorsLog implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 日志id + */ + @TableId(value = "log_id", type = IdType.AUTO) + private Long logId; + + /** + * 1管理员 2商户 + */ + private Integer userType; + + /** + * 修改人id + */ + private Long updateUserId; + + /** + * 修改人昵称 + */ + @TableField(condition = SqlCondition.LIKE) + private String updateUserName; + /** + * 修改人手机号码 + */ + private String updateUserPhone; + /** + * 用户id + */ + private Long userId; + + /** + * 用户昵称 + */ + @TableField(condition = SqlCondition.LIKE) + private String userName; + + /** + * 用户手机号码 + */ + private String userPhone; + + /** + * 用户上一次压桶数 + */ + private Integer lastBucket; + + /** + * 1增加 2减少 + */ + private Integer operator; + + /** + * 修改数量 + */ + private Integer operatorNum; + /** + * 0待审核 1已通过 2已拒绝 + */ + private Integer status; + + /** + * 修改后的压桶数 + */ + private Integer nextBucket; + /** + * 修改时间 + */ + private Date updateTime; + + +} diff --git a/src/main/java/com/sqx/modules/operatorsLog/service/OperatorsLogService.java b/src/main/java/com/sqx/modules/operatorsLog/service/OperatorsLogService.java new file mode 100644 index 0000000..d94c16a --- /dev/null +++ b/src/main/java/com/sqx/modules/operatorsLog/service/OperatorsLogService.java @@ -0,0 +1,24 @@ +package com.sqx.modules.operatorsLog.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.modules.operatorsLog.entity.OperatorsLog; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.util.HashMap; + +/** + *

+ * 服务类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-17 + */ +public interface OperatorsLogService extends IService { + + void addUpdateUserBucketLog(OperatorsLog operatorsLog); + + IPage getOperatorsLogList(Integer page, Integer limit, OperatorsLog operatorsLog); + + HashMap getBucketData(String time,Integer flag); +} diff --git a/src/main/java/com/sqx/modules/operatorsLog/service/impl/OperatorsLogServiceImpl.java b/src/main/java/com/sqx/modules/operatorsLog/service/impl/OperatorsLogServiceImpl.java new file mode 100644 index 0000000..ae163b3 --- /dev/null +++ b/src/main/java/com/sqx/modules/operatorsLog/service/impl/OperatorsLogServiceImpl.java @@ -0,0 +1,93 @@ +package com.sqx.modules.operatorsLog.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.operatorsLog.entity.OperatorsLog; +import com.sqx.modules.operatorsLog.dao.OperatorsLogDao; +import com.sqx.modules.operatorsLog.service.OperatorsLogService; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.service.SysUserService; +import org.apache.catalina.User; +import org.checkerframework.checker.units.qual.A; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.HashMap; + +/** + *

+ * 服务实现类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-17 + */ +@Service +public class OperatorsLogServiceImpl extends ServiceImpl implements OperatorsLogService { + + @Autowired + private OperatorsLogDao operatorsLogDao; + @Autowired + private SysUserService sysUserService; + @Autowired + private UserService userService; + + @Override + public void addUpdateUserBucketLog(OperatorsLog operatorsLog) { + //管理员修改 + if (operatorsLog.getUserType() == 1) { + SysUserEntity userEntity = sysUserService.getById(operatorsLog.getUpdateUserId()); + operatorsLog.setUpdateUserId(userEntity.getUserId()); + operatorsLog.setUpdateUserName(userEntity.getUsername()); + operatorsLog.setUpdateUserPhone(userEntity.getMobile()); + //商户修改 + } else if (operatorsLog.getUserType() == 2){ + UserEntity userEntity = userService.getById(operatorsLog.getUpdateUserId()); + operatorsLog.setUpdateUserId(userEntity.getUserId()); + operatorsLog.setUpdateUserName(userEntity.getUserName()); + operatorsLog.setUpdateUserPhone(userEntity.getPhone()); + //用户自己修改 + }else if (operatorsLog.getUserType() == 3){ + UserEntity userEntity = userService.getById(operatorsLog.getUpdateUserId()); + operatorsLog.setUpdateUserId(userEntity.getUserId()); + operatorsLog.setUpdateUserName(userEntity.getUserName()); + operatorsLog.setUpdateUserPhone(userEntity.getPhone()); + } + + operatorsLog.setUpdateTime(new Date()); + operatorsLogDao.insert(operatorsLog); + } + + @Override + public IPage getOperatorsLogList(Integer page, Integer limit, OperatorsLog operatorsLog) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + return operatorsLogDao.selectPage(pages, new QueryWrapper<>(operatorsLog).orderByDesc("update_time")); + } + + @Override + public HashMap getBucketData(String time, Integer flag) { + HashMap hashMap = new HashMap<>(); + //发出的数量 + Integer issue = operatorsLogDao.getBucketData(time, flag, 1); + //回收的数量 + Integer recovery = operatorsLogDao.getBucketData(time, flag, 2); + //当前总发出的数量 + Integer allBucket = userService.getAllBucket(); + hashMap.put("recovery", recovery); + hashMap.put("issue", issue); + hashMap.put("allBucket", allBucket); + return hashMap; + } + +} diff --git a/src/main/java/com/sqx/modules/orders/controller/OrdersController.java b/src/main/java/com/sqx/modules/orders/controller/OrdersController.java new file mode 100644 index 0000000..8bccba9 --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/controller/OrdersController.java @@ -0,0 +1,174 @@ +package com.sqx.modules.orders.controller; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.utils.excel.ExcelData; +import com.sqx.modules.utils.excel.ExportExcelUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/orders") +@Api(value = "订单信息", tags = {"订单信息"}) +public class OrdersController { + @Autowired + private OrdersService ordersService; + @Autowired + private UserService userService; + /** + * 查看所有订单 + * + * @param page + * @param limit + * @param name + * @param status + * @return + */ + @RequestMapping("/queryOrders") + public Result queryOrdersAll(Long page, Long limit, Long type, String name, Long status,Long userId,String ordersNo, + String startTime,String endTime,Long laundryId,Long orderTakingUserId ) { + return ordersService.queryOrdersAll(page, limit, type, name, status,userId,ordersNo,startTime,endTime,laundryId,orderTakingUserId); + } + + @GetMapping("/ordersListExcel") + @ApiOperation("订单导出") + public void ordersListExcel(Long type, String name, Long status,Long userId,String ordersNo,String startTime,String endTime,Long laundryId, HttpServletResponse response) throws Exception { + ExcelData data = ordersService.ordersListExcel(type, name, status,userId,ordersNo,startTime,endTime,laundryId); + ExportExcelUtils.exportExcel(response,"订单列表.xlsx",data); + } + + /** + * 删除订单 + */ + @RequestMapping("/deleteOrders") + public Result deleteOrders(Long id) { + return ordersService.deleteOrder(id); + } + + @GetMapping("/selectMyTakeOrders") + @ApiOperation("查询我的接单") + public Result selectMyTakeOrders(Integer page, Integer limit,Long userId, Integer status){ + return ordersService.selectMyTakeOrders(page,limit,userId,status); + } + + @ApiOperation("修改订单状态") + @GetMapping("/cancelOrder") + public Result cancelOrder(Long id, String status) { + Orders orders = ordersService.getById(id); + return ordersService.cancelOrder(id, status,orders.getCode(),null,null, null); + } + + @ApiOperation("转单") + @PostMapping("/giveOrdersUser") + public Result giveOrdersUser(Long userId,Long ordersId){ + UserEntity userEntity = userService.queryByUserId(userId); + return ordersService.giveOrdersUser(userEntity,ordersId); + } + + @PostMapping("/updateOrdersStartTime") + @ApiOperation("修改预约时间") + public Result updateOrdersStartTime(Long id,String startTime,String remarks){ + Orders orders = ordersService.getById(id); + orders.setStartTime(startTime); + orders.setRemarks(remarks); + ordersService.updateById(orders); + return Result.success(); + } + + @GetMapping("/selectTeamOrdersList") + @ApiOperation("获取团队订单") + public Result selectTeamOrdersList(Long userId, Integer page, Integer limit, Integer type, Integer status){ + return ordersService.selectTeamOrdersList(page,limit,userId,type,status); + } + + + @GetMapping("/selectTeamUserList") + @ApiOperation("获取团队列表") + public Result selectTeamUserList(Long userId, Integer page, Integer limit, Integer type){ + UserEntity user = userService.selectUserById(userId); + return ordersService.selectTeamUserList(page,limit,user.getInvitationCode(),type,userId); + } + + @GetMapping("/selectTeamStatistics") + @ApiOperation("团队统计") + public Result selectTeamStatistics(Long userId,Integer type){ + UserEntity user = userService.selectUserById(userId); + Double teamMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), type,null); + Integer teamCount = ordersService.selectUserCountByInvitationCode(user.getInvitationCode(), type); + Map result=new HashMap<>(); + result.put("teamMoney",teamMoney); + result.put("teamCount",teamCount); + return Result.success().put("data",result); + } + + @GetMapping("/selectOrdersDate") + @ApiOperation("订单统计") + public Result selectOrdersDate(Integer flag,String time){ + //订单状态 0待支付 1进行中 2已完成 3已退款 4待抢单 5待服务 + Integer sumXCOrdersCount = ordersService.selectOrdersCount(null, 1, flag, time); + Integer dzfXCOrdersCount = ordersService.selectOrdersCount(0, 1, flag, time); + Integer jxzXCOrdersCount = ordersService.selectOrdersCount(1, 1, flag, time); + Integer ywcXCOrdersCount = ordersService.selectOrdersCount(2, 1, flag, time); + Integer ytkXCOrdersCount = ordersService.selectOrdersCount(3, 1, flag, time); + Integer dqdXCOrdersCount = ordersService.selectOrdersCount(4, 1, flag, time); + Integer dfwXCOrdersCount = ordersService.selectOrdersCount(5, 1, flag, time); + //订单数量 + Integer sumXCOrdersNumber = ordersService.selectOrdersNumber(null, 1, flag, time); + Integer dzfXCOrdersNumber = ordersService.selectOrdersNumber(0, 1, flag, time); + Integer jxzXCOrdersNumber = ordersService.selectOrdersNumber(1, 1, flag, time); + Integer ywcXCOrdersNumber = ordersService.selectOrdersNumber(2, 1, flag, time); + Integer ytkXCOrdersNumber = ordersService.selectOrdersNumber(3, 1, flag, time); + Integer dqdXCOrdersNumber = ordersService.selectOrdersNumber(4, 1, flag, time); + Integer dfwXCOrdersNumber = ordersService.selectOrdersNumber(5, 1, flag, time); + + //钱 + Double sumCourseOrdersMoney = ordersService.selectOrdersMoney(null, 1, flag, time); + Double dzfCourseOrdersMoney = ordersService.selectOrdersMoney(0, 1, flag, time); + Double jxzCourseOrdersMoney = ordersService.selectOrdersMoney(1, 1, flag, time); + Double ywcCourseOrdersMoney = ordersService.selectOrdersMoney(2, 1, flag, time); + Double ytkCourseOrdersMoney = ordersService.selectOrdersMoney(3, 1, flag, time); + Double dqdCourseOrdersMoney = ordersService.selectOrdersMoney(4, 1, flag, time); + Double dfwCourseOrdersMoney = ordersService.selectOrdersMoney(5, 1, flag, time); + //会员订单 总 待 完 退 + Integer sumMemberOrdersCount = ordersService.selectOrdersCount(null, 2, flag, time); + Integer daiMemberOrdersCount = ordersService.selectOrdersCount(0, 2, flag, time); + Integer wanMemberOrdersCount = ordersService.selectOrdersCount(2, 2, flag, time); + Integer tuiMemberOrdersCount = ordersService.selectOrdersCount(3, 2, flag, time); + //会员钱 + Double sumMemberOrdersMoney = ordersService.selectOrdersMoney(null, 2, flag, time); + Double daiMemberOrdersMoney = ordersService.selectOrdersMoney(0, 2, flag, time); + Double wanMemberOrdersMoney = ordersService.selectOrdersMoney(2, 2, flag, time); + Double tuiMemberOrdersMoney = ordersService.selectOrdersMoney(3, 2, flag, time); + Map result=new HashMap<>(); + result.put("sumXCOrdersCount",sumXCOrdersCount);result.put("dzfXCOrdersCount",dzfXCOrdersCount); + result.put("jxzXCOrdersCount",jxzXCOrdersCount);result.put("ywcXCOrdersCount",ywcXCOrdersCount); + result.put("ytkXCOrdersCount",ytkXCOrdersCount);result.put("dqdXCOrdersCount",dqdXCOrdersCount); + result.put("dfwXCOrdersCount",dfwXCOrdersCount); + + result.put("sumXCOrdersNumber",sumXCOrdersNumber);result.put("dzfXCOrdersNumber",dzfXCOrdersNumber); + result.put("jxzXCOrdersNumber",jxzXCOrdersNumber);result.put("ywcXCOrdersNumber",ywcXCOrdersNumber); + result.put("ytkXCOrdersNumber",ytkXCOrdersNumber);result.put("dqdXCOrdersNumber",dqdXCOrdersNumber); + result.put("dfwXCOrdersNumber",dfwXCOrdersNumber); + + result.put("sumCourseOrdersMoney",sumCourseOrdersMoney);result.put("dzfCourseOrdersMoney",dzfCourseOrdersMoney); + result.put("jxzCourseOrdersMoney",jxzCourseOrdersMoney);result.put("ywcCourseOrdersMoney",ywcCourseOrdersMoney); + result.put("ytkCourseOrdersMoney",ytkCourseOrdersMoney);result.put("dqdCourseOrdersMoney",dqdCourseOrdersMoney); + result.put("dfwCourseOrdersMoney",dfwCourseOrdersMoney); + + result.put("sumMemberOrdersCount",sumMemberOrdersCount);result.put("daiMemberOrdersCount",daiMemberOrdersCount); + result.put("wanMemberOrdersCount",wanMemberOrdersCount);result.put("tuiMemberOrdersCount",tuiMemberOrdersCount); + result.put("sumMemberOrdersMoney",sumMemberOrdersMoney);result.put("daiMemberOrdersMoney",daiMemberOrdersMoney); + result.put("wanMemberOrdersMoney",wanMemberOrdersMoney);result.put("tuiMemberOrdersMoney",tuiMemberOrdersMoney); + return Result.success().put("data",result); + } + + +} diff --git a/src/main/java/com/sqx/modules/orders/controller/app/AppOrdersController.java b/src/main/java/com/sqx/modules/orders/controller/app/AppOrdersController.java new file mode 100644 index 0000000..ca3fd01 --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/controller/app/AppOrdersController.java @@ -0,0 +1,306 @@ +package com.sqx.modules.orders.controller.app; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.annotation.LoginUser; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.response.MyOrderResponse; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.AllArgsConstructor; +import oracle.net.ns.Message; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/app/orders") +@Api(value = "app订单信息", tags = {"app订单信息"}) +public class AppOrdersController { + + @Autowired + private OrdersService ordersService; + @Autowired + private UserService userService; + @Autowired + private MessageService messageService; + + + @Login + @ApiOperation("生成订单") + @GetMapping("/generateOrder") + public Result generateOrder(String province,String district,String name,String phone,@RequestAttribute Long userId, @ApiParam("接单/会员id") Long id, @ApiParam("订单类型") Long type,String city,String detailsAddress,String latitude ,String longitude, @ApiParam("订单数量") Integer orderNumber, @ApiParam("备注") String remarks,Long addressId,String startTime,String startImg,Integer isShopping,Long skuId,String detailJson, Long couponId,Long laundryId,Integer userType) { + return ordersService.generateOrder(province,district,name,phone,userId, id, type, city,detailsAddress,longitude,latitude,orderNumber, remarks,addressId,startTime,startImg,isShopping,skuId,detailJson,couponId,laundryId,userType); + } + + @Login + @ApiOperation("修改订单地址") + @PostMapping("/updateOrdersAddress") + public Result updateOrdersAddress(Long ordersId,Long addressId){ + return ordersService.updateOrdersAddress(ordersId, addressId); + } + + @Login + @ApiOperation("修改购物车商品数量") + @PostMapping("/updateShoppingNum") + public Result updateShoppingNum(Long id,Integer type){ + return ordersService.updateShoppingNum(id, type); + } + + + @Login + @PostMapping("/payShopping") + @ApiOperation("结算购物车商品") + public Result payShopping(@RequestBody List ordersList){ + return ordersService.payShopping(ordersList); + } + + @Login + @PostMapping("/ticketPayMoney") + @ApiOperation("水票支付") + public Result ticketPayMoney(@RequestBody List ordersList){ + return ordersService.ticketPayMoney(ordersList); + } + @Login + @ApiOperation("根据订单id查询订单") + @GetMapping("/selectOrderListByOrdersIds") + public Result selectOrderListByOrdersIds(String ordersIds){ + return ordersService.selectOrderListByOrdersIds(ordersIds); + } + + @Login + @ApiOperation("查询订单不同状态的数量") + @GetMapping("/selectMyOrdersCount") + public Result selectMyOrdersCount(@RequestAttribute Long userId){ + return ordersService.selectMyOrdersCount(userId); + } + + /** + * 查看我的订单 + */ + @Login + @ApiOperation("查看我的订单") + @GetMapping("/selectMyOrder") + public Result selectMyOrder(@RequestAttribute Long userId, Long page, Long limit, String status,Integer isShopping) { + if (page == null || limit == null) { + return Result.error("分页的条件为空"); + } else { + IPage iPage = new Page(page, limit); + return ordersService.selectMyOrder(userId, iPage, status,isShopping); + } + } + + @Login + @ApiOperation("查询抢单池") + @GetMapping("/selectOrderList") + public Result selectOrderList(Long page, Long limit,String createTime,String distance,String longitude,String latitude,Long laundryId) { + return ordersService.selectOrderList(page, limit,createTime,distance,longitude,latitude,laundryId); + } + + @Login + @ApiOperation("发起抢单") + @PostMapping("/insertMyOrders") + public Result insertMyOrders(Long ordersId,@RequestAttribute Long userId,String startImg){ + return ordersService.insertMyOrders(ordersId, userId,startImg); + } + @Login + @ApiOperation("开始配送") + @PostMapping("/startDelivery") + public Result startDelivery(Long ordersId,@RequestAttribute Long userId){ + return ordersService.startDelivery(ordersId, userId); + } + + + /** + * 生成充值订单 + */ + @Login + @ApiOperation("生成充值订单") + @GetMapping("/investOrder") + public Result investOrder(@RequestAttribute Long userId, @RequestParam Double money, @RequestParam Integer classify) { + + return ordersService.investOrder(userId, money, classify); + } + + /** + * 修改订单状态 + */ + @Login + @ApiOperation("修改订单状态") + @GetMapping("/cancelOrder") + public Result cancelOrder(@RequestAttribute Long userId,Long id, String status,String code,String endImg,String startImg,String noCodeFinishImg) { + Orders orders = ordersService.getById(id); + if(userId.equals(orders.getUserId())){ + code=orders.getCode(); + } + return ordersService.cancelOrder(id, status,code,endImg,startImg,noCodeFinishImg); + } + + @Login + @ApiOperation("转单") + @PostMapping("/giveOrdersUser") + public Result giveOrdersUser(String phone,Long ordersId){ + UserEntity userEntity = userService.queryByPhone(phone); + return ordersService.giveOrdersUser(userEntity,ordersId); + } + + + + /** + * 假删除订单 + */ + @Login + @ApiOperation("假删除订单") + @GetMapping("/deleteOrder") + public Result deleteOrder(Long id) { + + return ordersService.deleteOrder(id); + } + + /** + * 查看订单详情 + */ + @Login + @ApiOperation("查看订单详情") + @GetMapping("/queryOrders") + public Result queryOrders(Long id) { + return ordersService.queryOrders(id); + } + + + @Login + @GetMapping("/selectMyTakeOrders") + @ApiOperation("查询我的接单") + public Result selectMyTakeOrders(Integer page,Integer limit,@RequestAttribute Long userId,Integer status){ + return ordersService.selectMyTakeOrders(page,limit,userId,status); + } + + @Login + @GetMapping("/selectNowDayOrders") + @ApiOperation("今日订单") + public Result selectNowDayOrders(Integer page,Integer limit,@RequestAttribute Long userId){ + return ordersService.selectNowDayOrders(page, limit, userId); + } + + + + @Login + @PostMapping("/payMoney") + @ApiOperation("零钱去支付") + public Result payMoney(Long ordersId){ + return ordersService.payMoney(ordersId); + } + + @Login + @GetMapping("/getOrdersRemind") + @ApiOperation("获取服务订单") + public Result getOrdersRemind(@RequestAttribute Long userId){ + return Result.success().put("data",messageService.getNewOrderCount(userId)); + } + @Login + @GetMapping("/selectTeamOrdersList") + @ApiOperation("获取团队订单") + public Result selectTeamOrdersList(@RequestAttribute Long userId, Integer page, Integer limit, Integer type, Integer status){ + return ordersService.selectTeamOrdersList(page,limit,userId,type,status); + } + + @Login + @GetMapping("/selectTeamUserList") + @ApiOperation("获取团队列表") + public Result selectTeamUserList(@LoginUser UserEntity user, Integer page, Integer limit, Integer type){ + return ordersService.selectTeamUserList(page,limit,user.getInvitationCode(),type,user.getUserId()); + } + + @Login + @GetMapping("/selectTeamStatistics") + @ApiOperation("团队统计") + public Result selectTeamStatistics(@LoginUser UserEntity user){ + Double oneTeamMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), 1,null); + Integer oneTeamCount = ordersService.selectUserCountByInvitationCode(user.getInvitationCode(), 1); + Double twoTeamMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), 2,null); + Integer twoTeamCount = ordersService.selectUserCountByInvitationCode(user.getInvitationCode(), 2); + Integer teamCount=oneTeamCount+twoTeamCount; + BigDecimal teamMoney=BigDecimal.valueOf(oneTeamMoney).add(BigDecimal.valueOf(twoTeamMoney)); + Map result=new HashMap<>(); + result.put("teamMoney",teamMoney); + result.put("teamCount",teamCount); + result.put("oneTeamMoney",oneTeamMoney); + result.put("oneTeamCount",oneTeamCount); + result.put("twoTeamMoney",twoTeamMoney); + result.put("twoTeamCount",twoTeamCount); + return Result.success().put("data",result); + } + + + @Login + @GetMapping("/selectTeamStatisticsByType") + @ApiOperation("团队统计") + public Result selectTeamStatisticsByType(@LoginUser UserEntity user,Integer type){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + Double dayMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), type,sdf.format(new Date())); + sdf=new SimpleDateFormat("yyyy-MM"); + Double monthMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), type,sdf.format(new Date())); + sdf=new SimpleDateFormat("yyyy"); + Double yearMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), type,sdf.format(new Date())); + Double allMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), type,null); + Map result=new HashMap<>(); + result.put("allMoney",allMoney); + result.put("dayMoney",dayMoney); + result.put("monthMoney",monthMoney); + result.put("yearMoney",yearMoney); + return Result.success().put("data",result); + } + + + @GetMapping("/selectNewestOrders") + @ApiOperation("获取最新的下单信息") + public Result selectNewestOrders(){ + return ordersService.selectNewestOrders(); + } + + @GetMapping("/selectOrdersCount") + @ApiOperation("查询今日收入与订单数") + @Login + public Result selectOrdersCountAndMoney(@RequestAttribute Long userId){ + return ordersService.selectOrdersCountAndMoney(userId); + } + + @GetMapping("/selectStaffUserMoney") + @ApiOperation("查询商家数据统计") + @Login + public Result selectStaffUserMoney(@RequestAttribute Long userId){ + return ordersService.selectStaffUserMoney(userId); + } + + @GetMapping("/selectLaundryMoneyStatistics") + @ApiOperation("站点收益排行榜") + public Result selectLaundryMoneyStatistics(Integer page,Integer limit ,String laundryName){ + return ordersService.selectLaundryMoneyStatistics(page,limit ,laundryName); + } + + @GetMapping("/selectLaundryMoneyByLaundryId") + @ApiOperation("站点收益排行榜") + public Result selectLaundryMoneyByLaundryId(Long laundryId){ + return Result.success().put("data",ordersService.selectLaundryMoneyByLaundryId(laundryId)); + } + + + + +} diff --git a/src/main/java/com/sqx/modules/orders/controller/app/AppPayOrderController.java b/src/main/java/com/sqx/modules/orders/controller/app/AppPayOrderController.java new file mode 100644 index 0000000..3f2d6b9 --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/controller/app/AppPayOrderController.java @@ -0,0 +1,37 @@ +package com.sqx.modules.orders.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.orders.service.PayOrderService; +import io.swagger.annotations.Api; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.math.BigDecimal; + +@RestController +@RequestMapping("/app/appOrder") +@AllArgsConstructor +@Api(value = "app充值订单", tags = {"app充值订单"}) +public class AppPayOrderController { + private PayOrderService orderService; + + /** + * app充值订单 + * + * @param userId + * @param money + * @return + */ + @Login + @RequestMapping(value = "insertOrder", method = RequestMethod.POST) + public Result insertOrder(@RequestAttribute Long userId,Long payWay, BigDecimal money) { + + return orderService.insertOrder(userId, money); + } + + +} diff --git a/src/main/java/com/sqx/modules/orders/dao/OrdersDao.java b/src/main/java/com/sqx/modules/orders/dao/OrdersDao.java new file mode 100644 index 0000000..826f3df --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/dao/OrdersDao.java @@ -0,0 +1,106 @@ +package com.sqx.modules.orders.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.response.MyOrderResponse; +import com.sqx.modules.orders.response.OrderAllResponse; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Mapper +public interface OrdersDao extends BaseMapper { + + IPage selectMyOrder(IPage iPage, @Param("userId") Long userId, @Param("status") String status,Integer isShopping); + + IPage selectOrderList(Page page,String createTime,String distance,String longitude,String latitude,Long laundryId); + + + /** + * 查看所有订单 + */ + IPage queryOrdersAll(IPage iPage, @Param("type") Long type, @Param("name") String name, + @Param("status") Long status,@Param("userId") Long userId,@Param("ordersNo") String ordersNo, + @Param("startTime")String startTime,@Param("endTime")String endTime, + @Param("laundryId") Long laundryId,@Param("orderTakingUserId") Long orderTakingUserId); + + List ordersListExcel( @Param("type") Long type, @Param("name") String name, @Param("status") Long status, @Param("userId") Long userId, @Param("ordersNo") String ordersNo,@Param("startTime")String startTime,@Param("endTime")String endTime,@Param("laundryId") Long laundryId); + + IPage> selectMyTakeOrders(Page> page,@Param("userId") Long userId,@Param("status") Integer status); + + IPage> selectNowDayOrders(Page> page,@Param("userId") Long userId); + + Map selectOrdersCountAndMoney(Long userId); + + int selectMyOrdersCount(@Param("userId") Long userId,@Param("time") String time); + + int selectTakeOrdersCount(@Param("userId") Long userId,@Param("time") String time); + + Integer countOrdersByCreateTime(@Param("time")String time,@Param("flag")Integer flag); + + Double sumOrdersByCreateTime(@Param("time")String time,@Param("flag")Integer flag); + + IPage> incomeAnalysisOrders(Page> page,@Param("time")String time,@Param("flag")Integer flag); + + BigDecimal selectOrdersMoneyByUserId(Long userId,String startTime,String endTime); + + int selectOrdersCountByUserId(Long userId,String startTime,String endTime); + + BigDecimal selectOrderScoreByUserId(Long userId); + + BigDecimal selectOrdersRefundMoneyByUserId(Long userId,String startTime,String endTime); + + Integer selectOrdersRefundCountByUserId(Long userId,String startTime,String endTime ,Integer status); + + Integer getOrdersRemind(Long userId); + + int updateOrdersIsRemind(Long userId); + + Double selectOrdersMoneyCountByUserId(Long userId,Integer type,String time); + + Integer selectUserCountByInvitationCode(String invitationCode,Integer type); + + IPage> selectTeamOrdersList(Page> page,@Param("userId") Long userId,@Param("type") Integer type,@Param("status") Integer status); + + IPage> selectTeamUserList(Page> page,@Param("invitationCode") String invitationCode,@Param("type") Integer type,@Param("userId") Long userId); + + IPage> selectTeamUserList2(Page> page,@Param("type") Integer type,@Param("userId") Long userId); + + List> selectNewestOrders(); + + BigDecimal selectSumMoney(Long userId,@Param("startTime") String startTime,@Param("endTime") String endTime); + + BigDecimal selectEstimationSumMoneyBy(Long userId,@Param("time") String time,@Param("type") Integer type); + + BigDecimal getMoney(String time,Integer flag, @Param("state") Integer state,@Param("laundryId") Long laundryId); + + Integer orderCount(String time, Integer flag,@Param("state") Integer state,@Param("laundryId") Long laundryId); + + IPage> selectLaundryMoneyStatistics(Page> page,@Param("laundryName") String laundryName); + + BigDecimal selectLaundryMoneyByLaundryId(Long laundryId); + + List cleanOrdersByTime(String time); + + int updateOrdersStateByCreateTime(String time); + + Integer selectOrdersCount(Integer status,Integer ordersType,Integer flag,String time); + + Integer selectOrdersNumber(Integer status,Integer ordersType,Integer flag,String time); + + + Double selectOrdersMoney(Integer status,Integer ordersType,Integer flag,String time); + + + int sumOrderBucketCount(Long userId, String startTime, String endTime); + + List> getUserBucket(Integer flag, String date); + + Integer getUserBucketCount(Long userId); +} diff --git a/src/main/java/com/sqx/modules/orders/dao/PayOrderDao.java b/src/main/java/com/sqx/modules/orders/dao/PayOrderDao.java new file mode 100644 index 0000000..26edf13 --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/dao/PayOrderDao.java @@ -0,0 +1,10 @@ +package com.sqx.modules.orders.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.orders.entity.PayOrder; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface PayOrderDao extends BaseMapper { + +} diff --git a/src/main/java/com/sqx/modules/orders/entity/Orders.java b/src/main/java/com/sqx/modules/orders/entity/Orders.java new file mode 100644 index 0000000..acd5b48 --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/entity/Orders.java @@ -0,0 +1,151 @@ +package com.sqx.modules.orders.entity; + + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.taking.entity.Game; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +@ApiModel("订单表") +public class Orders implements Serializable { + @ApiModelProperty("订单id") + @TableId(type = IdType.AUTO) + private Long ordersId; + @ApiModelProperty("订单编号") + private String ordersNo; + @ApiModelProperty("用户id") + private Long userId; + @TableField(exist = false) + private UserEntity user; + @ApiModelProperty("接单id") + private Long orderTakingId; + @ApiModelProperty("支付金额") + private BigDecimal payMoney; + @ApiModelProperty("订单状态0待支付1进行中2已完成3已退款 4待抢单 5待服务") + private String state; + @ApiModelProperty("创建时间") + private String createTime; + @ApiModelProperty("退款原因") + private String refundContent; + @ApiModelProperty("订单种类1接单2会员") + private Long ordersType; + @ApiModelProperty("备注") + private String remarks; + + @TableField(exist = false) + @ApiModelProperty("是否需要压桶 0否 1是") + private Integer isNeedBucket; + @ApiModelProperty("订单数量") + private Integer orderNumber; + @ApiModelProperty("评分") + private Double orderScore; + @ApiModelProperty("修改时间") + private String updateTime; + @ApiModelProperty("会员类型id") + private Long vipDetailsId; + @ApiModelProperty("用户类型") + private Long type; + @ApiModelProperty("假删除") + private Long isdelete; + @TableField(exist = false) + private Game game; + private BigDecimal money; + @TableField(exist = false) + private OrderTaking orderTaking; + @ApiModelProperty("省") + private String province; + @ApiModelProperty("市") + private String city; + @ApiModelProperty("区") + private String district; + @ApiModelProperty("详细地址") + private String detailsAddress; + @ApiModelProperty("纬度") + private String longitude; + @ApiModelProperty("经度") + private String latitude; + @ApiModelProperty("姓名") + private String name; + @ApiModelProperty("电话") + private String phone; + @ApiModelProperty("上门时间") + private String startTime; + private Integer isRemind; + @ApiModelProperty("技师佣金") + private BigDecimal rate; + @ApiModelProperty("一级佣金") + private BigDecimal zhiRate; + private Long zhiUserId; + @ApiModelProperty("二级佣金") + private BigDecimal feiRate; + private Long feiUserId; + @ApiModelProperty("平台利润") + private BigDecimal pingRate; + private String endTime; + private Long orderTakingUserId; + private String code; + @ApiModelProperty("支付方式 1零钱 2微信 3支付宝") + private Integer payWay; + private String startImg; + private String endImg; + private Integer isTransfer; + private Long skuId; + private String detailJson; + private Integer isShopping; + @ApiModelProperty("优惠券id") + private Long couponId; + @ApiModelProperty("优惠金额") + private BigDecimal couponMoney; + private Integer integralNum; + /** + * 1积分商品 其他普通商品 + */ + private Integer isIntegral; + /** + * 无需验证码 完成订单的图片 + */ + private String noCodeFinishImg; + /** + * 下单用户类型 1用户 2师傅 + */ + private Integer userType; + @TableField(exist = false) + private TbCouponUser couponUser; + /** + * 用户水票id + */ + private Long roleId; + @ApiModelProperty("站点id") + private Long laundryId; + @ApiModelProperty("站点收益") + private BigDecimal laundryMoney; + @ApiModelProperty("站点名称") + private String laundryName; + @ApiModelProperty("站点分成比例") + private String laundryRate; + @TableField(exist = false) + private String laundryPhone; + + /** + *是否已修改桶数量 0未修改 1已修改 + */ + private Integer isUpdateBucket; + /** + *是否已推送 + */ + private Integer isPushMeg; + +} diff --git a/src/main/java/com/sqx/modules/orders/entity/PayOrder.java b/src/main/java/com/sqx/modules/orders/entity/PayOrder.java new file mode 100644 index 0000000..fd0d98f --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/entity/PayOrder.java @@ -0,0 +1,87 @@ +package com.sqx.modules.orders.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * @author liyuan + * @description order + * @date 2021-08-24 + */ +@Data +@ApiModel("pay_order") +public class PayOrder implements Serializable { + + private static final long serialVersionUID = 1L; + @TableId(type = IdType.AUTO) + @ApiModelProperty("id") + private Long id; + + /** + * 订单标号 + */ + @ApiModelProperty("订单标号") + private String ordersNo; + + /** + * 支付宝支付单号 + */ + @ApiModelProperty("支付宝支付单号") + private String tradeNo; + + /** + * 金币金额 + */ + @ApiModelProperty("金币金额") + private BigDecimal money; + + /** + * 支付金额 + */ + @ApiModelProperty("支付金额") + private BigDecimal payMoney; + + /** + * 支付方式 1微信小程序 2微信公众号 3微信app 4支付宝 + */ + @ApiModelProperty("支付方式 1微信小程序 2微信公众号 3微信app 4支付宝") + private Integer payWay; + + /** + * 状态 0待支付 1已支付 2已退款 + */ + @ApiModelProperty("状态 0待支付 1已支付 2已退款") + private Integer state; + + /** + * 创建时间 + */ + @ApiModelProperty("创建时间") + private String createTime; + + /** + * 退款原因 + */ + @ApiModelProperty("退款原因") + private String refundContent; + + /** + * 更新时间 + */ + @ApiModelProperty("更新时间") + private String updateTime; + /** + * 用户id + */ + @ApiModelProperty("用户id") + private Long userId; + + public PayOrder() { + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/orders/response/MyOrderResponse.java b/src/main/java/com/sqx/modules/orders/response/MyOrderResponse.java new file mode 100644 index 0000000..9b91c4d --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/response/MyOrderResponse.java @@ -0,0 +1,99 @@ +package com.sqx.modules.orders.response; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +public class MyOrderResponse implements Serializable { + + private Long ordersId; + /** + * 订单状态0待支付1进行中2已完成3已退款 + */ + private String state; + /** + * 更新时间 + */ + private String updateTime; + /** + * 接单id + */ + private Long orderTakingId; + /** + *接单用户id + */ + private Long userId; + /** + * 头像 + */ + private String avatar; + /** + * 下单人手机号 + */ + private String phone; + /** + * 游戏名称 + */ + private String userName; + /** + *游戏名称 + */ + private String gameName; + /** + * 数量 + */ + private int orderNumber; + /** + * 价格 + */ + private Double payMoney; + + private String gameImg; + + + private Integer commentCount; + private Integer classify; + private String unit; + private String myLevel; + private String homepageImg; + private String province; + private String city; + private String district; + private String detailsAddress; + private BigDecimal rate; + private BigDecimal zhiRate; + private Long zhiUserId; + private BigDecimal feiRate; + private Long feiUserId; + private BigDecimal pingRate; + private String code; + private Integer isShopping; + private Long skuId; + private String detailJson; + private Integer isTransfer; + private Long couponId; + private BigDecimal couponMoney; + private String startImg; + private String endImg; + private String distance; + private String serviceName; + /** + *是否已修改桶数量 0未修改 1已修改 + */ + private Integer isUpdateBucket; + + @ApiModelProperty("是否需要压桶 0否 1是") + private Integer isNeedBucket; + private BigDecimal money; + private String startTime; + private Long laundryId; + private BigDecimal laundryMoney; + private String laundryName; + /** + * 无需验证码 完成订单的图片 + */ + private String noCodeFinishImg; +} diff --git a/src/main/java/com/sqx/modules/orders/response/OrderAllResponse.java b/src/main/java/com/sqx/modules/orders/response/OrderAllResponse.java new file mode 100644 index 0000000..19f083b --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/response/OrderAllResponse.java @@ -0,0 +1,96 @@ +package com.sqx.modules.orders.response; +import com.baomidou.mybatisplus.annotation.TableField; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +public class OrderAllResponse implements Serializable { + + @ApiModelProperty("订单id") + private Long ordersId; + @ApiModelProperty("订单编号") + private String ordersNo; + @ApiModelProperty("接单id") + private Long orderTakingId; + @ApiModelProperty("支付金额") + private BigDecimal payMoney; + @ApiModelProperty("订单状态0待支付1进行中2已完成3已退款") + private Long state; + @ApiModelProperty("创建时间") + private String createTime; + @ApiModelProperty("订单种类1接单2会员") + private Long ordersType; + @ApiModelProperty("备注") + private String remarks; + @ApiModelProperty("订单数量") + private Long orderNumber; + @ApiModelProperty("会员类型id") + private Long vipDetailsId; + @TableField(exist = false) + private String userName; + @TableField(exist = false) + private String avatar; + @ApiModelProperty("评分") + private Double orderScore; + private Long userId; + private BigDecimal memberMoney; + private BigDecimal money; + private BigDecimal oldMoney; + private Integer classify; + private String unit; + @ApiModelProperty("省") + private String province; + @ApiModelProperty("市") + private String city; + @ApiModelProperty("区") + private String district; + @ApiModelProperty("详细地址") + private String detailsAddress; + @ApiModelProperty("姓名") + private String name; + @ApiModelProperty("电话") + private String phone; + @ApiModelProperty("上门时间") + private String startTime; + private String myLevel; + private String ordersUserName; + /** + *是否已修改桶数量 0未修改 1已修改 + */ + private Integer isUpdateBucket; + private BigDecimal rate; + private BigDecimal zhiRate; + private Long zhiUserId; + private BigDecimal feiRate; + private Long feiUserId; + private BigDecimal pingRate; + + private String zhiUserName; + private String feiUserName; + @ApiModelProperty("站长id") + private Long laundryUserId; + private String code; + private String carNo; + private String carType; + private String carColor; + private String carName; + private String carPhone; + private String startImg; + private String endImg; + private Integer isShopping; + private Long skuId; + private String detailJson; + private Integer isTransfer; + private Long couponId; + private BigDecimal couponMoney; + private String serviceName; + private Long laundryId; + private BigDecimal laundryMoney; + private String laundryName; + /** + * 无需验证码 完成订单的图片 + */ + private String noCodeFinishImg; +} diff --git a/src/main/java/com/sqx/modules/orders/service/OrdersService.java b/src/main/java/com/sqx/modules/orders/service/OrdersService.java new file mode 100644 index 0000000..973003b --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/service/OrdersService.java @@ -0,0 +1,148 @@ +package com.sqx.modules.orders.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.utils.excel.ExcelData; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.List; + + +public interface OrdersService extends IService { + + int selectMyOrdersCount(Long userId, String time); + + Result selectMyOrdersCount(Long userId); + + int selectTakeOrdersCount( Long userId, String time); + + /** + * 生成订单 + * + * @param userId + * @param id + * @param type + * @param orderNumber + * @param remarks + * @param userType + * @param isNeedBucket + * @return + */ + Result generateOrder(String province, String district, String name, String phone, Long userId, Long id, Long type, String city, String detailsAddres, String latitude, String longitude, Integer orderNumber, String remarks, Long addressId, String startTime, String startImg, Integer isShopping, Long skuId, String detailJson, Long couponId, Long laundryId, Integer userType); + + Result updateOrdersAddress(Long ordersId,Long addressId); + + Result updateShoppingNum(Long id,Integer type); + + /** + * 查看我的订单 + * + * @param userId + * @return + */ + Result selectMyOrder(Long userId, IPage iPage, String status,Integer isShopping); + + Result payShopping(List ordersList); + + Result selectOrderListByOrdersIds(String ids); + + Result selectOrderList(Long page, Long limit,String createTime,String distance,String longitude,String latitude,Long laundryId); + + Result insertMyOrders(Long ordersId,Long userId,String startImg); + + /** + * 生成充值订单 + * + * @param userId + * @param money + * @return + */ + Result investOrder(Long userId, Double money, Integer classify); + + + Result giveOrdersUser(UserEntity user, Long ordersId); + + /** + * 取消订单 + * + * @param id + * @param status + * @param noCodeFinishImg + * @return + */ + Result cancelOrder(Long id, String status, String code, String endImg, String startImg, String noCodeFinishImg); + + /** + * 删除订单 + * + * @param id + * @param + * @return + */ + Result deleteOrder(Long id); + + /** + * \ + * 查询订单详情 + * + * @param id + * @return + */ + Result queryOrders(Long id); + + /** + * 查看所有订单 + */ + Result queryOrdersAll(Long page, Long limit,Long type, String name, Long status,Long userId,String ordersNo,String startTime,String endTime,Long laundryId,Long orderTakingUserId); + + ExcelData ordersListExcel(Long type, String name, Long status, Long userId, String ordersNo,String startTime,String endTime,Long laundryId); + + Result selectMyTakeOrders(Integer page,Integer limit,Long userId,Integer status); + + Result selectNowDayOrders(Integer page,Integer limit, Long userId); + + Result payMoney(Long ordersId); + + PageUtils incomeAnalysisOrders(Integer page, Integer limit, String time, Integer flag); + + Integer getOrdersRemind(Long userId); + + int updateOrdersIsRemind(Long userId); + + Result selectTeamOrdersList(Integer page, Integer limit, Long userId,Integer type, Integer status); + + Result selectTeamUserList(Integer page, Integer limit, String invitationCode,Integer type,Long userId); + + Double selectOrdersMoneyCountByUserId(Long userId,Integer type,String time); + + Integer selectUserCountByInvitationCode(String invitationCode,Integer type); + + Result selectNewestOrders(); + + Result selectOrdersCountAndMoney(Long userId); + + Result selectStaffUserMoney(Long userId); + + Result ticketPayMoney(List ordersList); + + Result startDelivery(Long ordersId, Long userId); + + Result selectLaundryMoneyStatistics(Integer page,Integer limit,String laundryName); + + BigDecimal selectLaundryMoneyByLaundryId(Long laundryId); + + Integer selectOrdersCount(Integer status,Integer ordersType,Integer flag,String time); + + Integer selectOrdersNumber(Integer status, Integer ordersType, Integer flag, String time); + + + Double selectOrdersMoney(Integer status,Integer ordersType,Integer flag,String time); + List> getUserBucket(Integer flag, String date); + + Integer getUserBucketCount(Long userId); +} diff --git a/src/main/java/com/sqx/modules/orders/service/PayOrderService.java b/src/main/java/com/sqx/modules/orders/service/PayOrderService.java new file mode 100644 index 0000000..7bb2557 --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/service/PayOrderService.java @@ -0,0 +1,16 @@ +package com.sqx.modules.orders.service; + +import com.sqx.common.utils.Result; +import org.springframework.web.bind.annotation.RequestAttribute; + +import java.math.BigDecimal; + +public interface PayOrderService { + /** + * 生成充值订单 + * @param userId + * @param money + * @return + */ + Result insertOrder( Long userId, BigDecimal money); +} diff --git a/src/main/java/com/sqx/modules/orders/service/impl/OrdersServiceImpl.java b/src/main/java/com/sqx/modules/orders/service/impl/OrdersServiceImpl.java new file mode 100644 index 0000000..745bdcc --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/service/impl/OrdersServiceImpl.java @@ -0,0 +1,1457 @@ +package com.sqx.modules.orders.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserDao; +import com.sqx.modules.app.dao.VipDetailsDao; +import com.sqx.modules.app.entity.*; +import com.sqx.modules.app.service.*; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.coupon.respository.SelfCouponUserJpaRepository; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.response.OrderAllResponse; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.pay.controller.app.AliPayController; +import com.sqx.modules.pay.dao.CashOutDao; +import com.sqx.modules.pay.dao.PayDetailsDao; +import com.sqx.modules.pay.entity.PayDetails; +import com.sqx.modules.pay.service.WxService; +import com.sqx.modules.taking.dao.OrderTakingDao; +import com.sqx.modules.taking.entity.GoodsSku; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.GoodsSkuService; +import com.sqx.modules.taking.service.OrderTakingService; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.tickets.service.TicketsService; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import com.sqx.modules.ticketsUserRole.service.TicketsUserRoleService; +import com.sqx.modules.utils.AliPayOrderUtil; +import com.sqx.modules.utils.LonLatUtil; +import com.sqx.modules.utils.SenInfoCheckUtil; +import com.sqx.modules.utils.excel.ExcelData; +import jodd.util.StringUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.gavaghan.geodesy.Ellipsoid; +import org.gavaghan.geodesy.GlobalCoordinates; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +@Service +@Slf4j +public class OrdersServiceImpl extends ServiceImpl implements OrdersService { + + @Autowired + private OrderTakingDao orderTakingDao; + @Autowired + private UserVipService userVipService; + @Autowired + private VipDetailsDao vipDetailsDao; + @Autowired + private PayDetailsDao payDetailsDao; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private UserDao userDao; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private MessageService messageService; + @Autowired + private TicketsService ticketsService; + @Autowired + private UserService userService; + @Autowired + private OrderTakingService orderTakingService; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private TicketsUserRoleService userRoleService; + @Autowired + private AddressService addressService; + @Autowired + private WxService wxService; + @Autowired + private AliPayController aliPayController; + @Autowired + private GoodsSkuService goodsSkuService; + @Autowired + private CashOutDao cashOutDao; + @Autowired + private UserCertificationService certificationService; + @Autowired + private TbCouponUserService couponUserService; + @Autowired + private SelfCouponUserJpaRepository selfCouponUserJpaRepository; + @Autowired + private LaundryRepository laundryRepository; + private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true); + + @Override + public int selectMyOrdersCount(Long userId, String time) { + return baseMapper.selectMyOrdersCount(userId, time); + } + + @Override + public Result selectMyOrdersCount(Long userId) { + //0待支付1待服务2已完成3已退款4进行中 + int count0 = baseMapper.selectCount(new QueryWrapper().eq("user_id", userId).eq("orders_type", 1).eq("state", 0)); + int count1 = baseMapper.selectCount(new QueryWrapper().eq("user_id", userId).eq("orders_type", 1).eq("state", 1)); + int count2 = baseMapper.selectCount(new QueryWrapper().eq("user_id", userId).eq("orders_type", 1).eq("state", 2)); + int count4 = baseMapper.selectCount(new QueryWrapper().eq("user_id", userId).eq("orders_type", 1).eq("state", 4)); + int count5 = baseMapper.selectCount(new QueryWrapper().eq("user_id", userId).eq("orders_type", 1).eq("state", 5)); + Map result = new HashMap<>(); + result.put("count0", count0); + result.put("count1", count1); + result.put("count2", count2); + result.put("count4", count4); + result.put("count5", count5); + return Result.success().put("data", result); + } + + @Override + public int selectTakeOrdersCount(Long userId, String time) { + return baseMapper.selectTakeOrdersCount(userId, time); + } + + @Override + public Result updateOrdersAddress(Long ordersId, Long addressId) { + Orders orders = baseMapper.selectById(ordersId); + if ("0".equals(orders.getState())) { + Address byId = addressService.getById(addressId); + orders.setProvince(byId.getProvince()); + orders.setCity(byId.getCity()); + orders.setDistrict(byId.getDistrict()); + orders.setDetailsAddress(byId.getDetailsAddress()); + orders.setName(byId.getName()); + orders.setPhone(byId.getPhone()); + orders.setLatitude(byId.getLatitude()); + orders.setLongitude(byId.getLongitude()); + baseMapper.updateById(orders); + return Result.success(); + } + return Result.error("当前订单状态不允许修改地址!"); + } + + /** + * 生成订单 + * + * @param userId + * @param id + * @param userType + * @return + */ + @Override + public Result generateOrder(String province, String district, String name, String phone, Long userId, Long id, Long orderType, String city, String detailsAddres, String longitude, String latitude, Integer orderNumber, String remarks, Long addressId, String startTime, String startImg, Integer isShopping, Long skuId, String detailJson, Long couponId, Long laundryId, Integer userType) { + if (isShopping != null && isShopping == 1) { + Orders selectOne = baseMapper.selectOne(new QueryWrapper().eq("user_id", userId).eq("order_taking_id", id).eq("isdelete", 0).notIn("state", 1, 2, 3, 4).eq("is_shopping", 1).eq("sku_id", skuId)); + if (selectOne != null) { + return updateShoppingNum(selectOne.getOrdersId(), 1); + } + } + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //判断订单类型 + if (orderType != null) { + //创建订单模板 + Orders orders = new Orders(); + //查看会员信息 + UserVip userVip = userVipService.selectUserVipByUserId(userId); + //接单 + if (orderType == 1) { + OrderTaking orderTaking = orderTakingDao.selectById(id); + //接单的订单是否存在 + if (orderTaking == null || orderTaking.getIsdelete() == 1) { + return Result.error("商品不存在,请刷新页面后重试!"); + } + //接单的订单 + if (orderTaking.getIsNeedBucket() != null && orderTaking.getIsNeedBucket() == 1) { + UserEntity userEntity = userService.getById(userId); + if (userEntity.getBucket() < orderNumber) { + return Result.error("您的压桶数量不足"); + } + } + if (laundryId != null) { + Laundry laundry = laundryRepository.findById(laundryId).orElse(null); + if (laundry != null) { + if (laundry.getIsOpen() != null && laundry.getIsOpen() == 1) { + return Result.error("站点打烊了,请更换其他站点!"); + } + orders.setLaundryName(laundry.getLaundryName()); + GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(latitude), Double.parseDouble(longitude)); + GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(laundry.getLatitude()), Double.parseDouble(laundry.getLongitude())); + int distances = (int) LonLatUtil.getDistanceMeter(source, target, Ellipsoid.Sphere); + if (distances > laundry.getMaxScope()) { + return Result.error("当前地址超出站点最大配送范围!"); + } + + } + } + GoodsSku goodsSku = goodsSkuService.getById(skuId); + if (goodsSku == null || goodsSku.getStock() == null || goodsSku.getStock() <= 0 || goodsSku.getStock() < orderNumber) { + return Result.error("商品数量不足!"); + } + orders.setProvince(province); + orders.setDistrict(district); + orders.setName(name); + orders.setPhone(phone); + //设置订单编号 + orders.setOrdersNo(AliPayOrderUtil.createOrderId()); + //设置用户id + orders.setUserId(userId); + orders.setStartTime(startTime); + //设置接单id + orders.setOrderTakingId(id); + //设置订单状态 + orders.setState("0"); + //设置创建时间 + orders.setCreateTime(df.format(new Date())); + //设置更新时间 + orders.setUpdateTime(df.format(new Date())); + //设置订单种类 + orders.setOrdersType(orderType); + //用户类型 + orders.setType((long) 1); + //地址 + orders.setStartImg(startImg); + orders.setCity(city); + orders.setDetailsAddress(detailsAddres); + orders.setLatitude(latitude); + orders.setLongitude(longitude); + orders.setIsShopping(isShopping); + orders.setSkuId(skuId); + orders.setDetailJson(detailJson); + if (userType != null && userType == 2) { + UserEntity riderUser = userService.getById(userId); + if (riderUser != null) { + if (riderUser.getIsAuthentication() != null && riderUser.getIsAuthentication() == 1) { + orders.setUserType(2); + orders.setOrderTakingUserId(userId); + } else { + return Result.error("师傅未认证"); + } + if (riderUser.getIsSafetyMoney() == null || riderUser.getIsSafetyMoney() != 1) { + return Result.error("请先加纳保证金"); + } + } else { + return Result.error("下单异常,请重新登录!"); + } + } else { + orders.setUserType(1); + } + + //订单数量 + if (orderNumber != null) { + try { + if (userVip != null && df.parse(userVip.getEndTime()).getTime() > System.currentTimeMillis() && userVip.getIsVip() == 1) { + orders.setType((long) 1); + BigDecimal money = goodsSku.getSkuMemberPrice(); + orders.setMoney(money); + BigDecimal moneys = money.multiply(BigDecimal.valueOf(orderNumber)); + //设置支付金额 + orders.setPayMoney(moneys); + + } else { + orders.setType((long) 2); + BigDecimal money = goodsSku.getSkuPrice(); + orders.setMoney(money); + BigDecimal nmoney = money.multiply(BigDecimal.valueOf(orderNumber)); + //设置支付金额 + orders.setPayMoney(nmoney); + } + } catch (ParseException e) { + e.printStackTrace(); + log.error("生成订单会员价格出异常:" + e.getMessage(), e); + orders.setType((long) 2); + BigDecimal money = goodsSku.getSkuPrice(); + orders.setMoney(money); + BigDecimal nmoney = money.multiply(BigDecimal.valueOf(orderNumber)); + //设置支付金额 + orders.setPayMoney(nmoney); + } + if (laundryId != null) { + Laundry laundry = laundryRepository.findById(laundryId).orElse(null); + if (laundry.getRate() != null && laundry.getRate().doubleValue() > 0) { + BigDecimal laundryMoney = orders.getPayMoney().multiply(laundry.getRate()); + orders.setLaundryMoney(laundryMoney); + } + + } + + //设置订单数量 + orders.setOrderNumber(orderNumber); + //设置备注 + orders.setRemarks(remarks); + //设置假射出状态 + orders.setIsdelete((long) 0); + int code = (int) ((Math.random() * 9 + 1) * 1000); + orders.setCode(String.valueOf(code)); + //生成订单 + //优惠券代码逻辑 + if (couponId != null) { + TbCouponUser tbCouponUser = couponUserService.getById(couponId); + if (tbCouponUser == null) { + return Result.error("你未持有当前优惠券"); + } + if (tbCouponUser.getStatus() == 1) { + return Result.error("当前优惠券已使用"); + } + if (tbCouponUser.getStatus() == 2) { + return Result.error("当前优惠券已失效"); + } + //如果订单金额大于优惠券最小订单金额 + if (orders.getPayMoney().compareTo(tbCouponUser.getMinMoney()) >= 0) { + //写入使用了优惠券之后的订单金额 + orders.setPayMoney(orders.getPayMoney().subtract(tbCouponUser.getMoney())); + tbCouponUser.setStatus(1); + tbCouponUser.setEmployTime(new Date()); + couponUserService.updateById(tbCouponUser); + } else { + return Result.error("订单金额不满足最低满减金额"); + } + } + orders.setCouponId(couponId); + orders.setLaundryId(laundryId); + //获取 站点id + if (laundryId != null) { + Laundry laundry = laundryRepository.findById(laundryId).orElse(null); + if (laundry != null) { + if (laundry.getRate() != null) { + orders.setLaundryRate(laundry.getRate().toString()); + } + orders.setLaundryName(laundry.getLaundryName()); + orders.setLaundryId(laundryId); + } + } + if (orders.getPayMoney().compareTo(BigDecimal.ZERO) <= 0) { + orders.setPayMoney(new BigDecimal("0.01")); + } + baseMapper.insert(orders); + return Result.success().put("data", orders); + } else { + return Result.error("订单数量为空!订单生成失败"); + } + + } else { + //会员 + //设置订单编号 + orders.setOrdersNo(AliPayOrderUtil.createOrderId()); + //设置用户id + orders.setUserId(userId); + //设置要开通的会员类型id + orders.setVipDetailsId(id); + //查询会员支付价钱 + VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper().eq("id", id)); + //设置订单金额 + orders.setPayMoney(vipDetails.getMoney()); + //设置订单状态 待支付 + orders.setState("0"); + //设置创建时间 + orders.setCreateTime(df.format(new Date())); + //设置更新时间 + orders.setUpdateTime(df.format(new Date())); + orders.setIsdelete((long) 0); + //设置订单种类 + orders.setOrdersType(orderType); + baseMapper.insert(orders); + return Result.success().put("data", orders); + } + } else { + return Result.error("订单类型异常,请刷新页面后重试!"); + } + } + + @Override + public Result updateShoppingNum(Long id, Integer type) { + reentrantReadWriteLock.writeLock().lock(); + try { + Orders orders = baseMapper.selectById(id); + if (!"0".equals(orders.getState())) { + return Result.error("商品已经支付或取消,请刷新后重试!"); + } + if (orders.getIsShopping() == null || orders.getIsShopping() != 1) { + return Result.error("非购物车商品,请刷新后重试!"); + } + if (type == 1) { + orders.setOrderNumber(orders.getOrderNumber() + 1); + } else { + if (orders.getOrderNumber() == 1) { + return Result.error("商品数量为1,不可再减!"); + } + orders.setOrderNumber(orders.getOrderNumber() - 1); + } + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + BigDecimal multiply = goodsSku.getSkuPrice().multiply(BigDecimal.valueOf(orders.getOrderNumber())); + orders.setPayMoney(multiply); + baseMapper.updateById(orders); + return Result.success().put("data", multiply); + } catch (Exception e) { + e.printStackTrace(); + log.error("加入购物车异常:" + e.getMessage(), e); + } finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + @Override + public Result payShopping(List ordersList) { + List ordersLists = new ArrayList<>(); + BigDecimal price = BigDecimal.ZERO; + for (Orders orders : ordersList) { + Laundry laundry = laundryRepository.findById(orders.getLaundryId()).orElse(null); + Orders oldOrders = baseMapper.selectById(orders.getOrdersId()); + if (laundry == null) { + return Result.error("站点参数异常,请重新选择站点"); + } + if (laundry.getRate() != null && laundry.getRate().doubleValue() > 0) { + BigDecimal laundryMoney = oldOrders.getPayMoney().multiply(laundry.getRate()); + oldOrders.setLaundryMoney(laundryMoney); + } + oldOrders.setLaundryId(laundry.getLaundryId()); + oldOrders.setLaundryName(laundry.getLaundryName()); + oldOrders.setRemarks(orders.getRemarks()); + oldOrders.setStartTime(orders.getStartTime()); + oldOrders.setProvince(orders.getProvince()); + oldOrders.setCity(orders.getCity()); + oldOrders.setDistrict(orders.getDistrict()); + oldOrders.setDetailsAddress(orders.getDetailsAddress()); + oldOrders.setName(orders.getName()); + oldOrders.setPhone(orders.getPhone()); + oldOrders.setIsShopping(2); + GoodsSku goodsSku = goodsSkuService.getById(oldOrders.getSkuId()); + if (goodsSku.getStock() < oldOrders.getOrderNumber()) { + OrderTaking orderTaking = orderTakingDao.selectById(oldOrders.getOrderTakingId()); + return Result.error(orderTaking.getServiceName() + " 剩余库存不足!"); + } + if (orders.getCouponId() != null) { + TbCouponUser tbCouponUser = couponUserService.getById(orders.getCouponId()); + if (tbCouponUser == null) { + return Result.error("你未持有当前优惠券"); + } + if (tbCouponUser.getStatus() == 1) { + return Result.error("当前优惠券已使用"); + } + if (tbCouponUser.getStatus() == 2) { + return Result.error("当前优惠券已失效"); + } + //如果订单金额大于优惠券最小订单金额 + if (oldOrders.getPayMoney().compareTo(tbCouponUser.getMinMoney()) < 0) { + return Result.error("订单金额不满足最低满减金额"); + } else { + oldOrders.setPayMoney(oldOrders.getPayMoney().subtract(tbCouponUser.getMoney())); + oldOrders.setCouponId(orders.getCouponId()); + } + if (oldOrders.getPayMoney().compareTo(BigDecimal.ZERO) <= 0) { + oldOrders.setPayMoney(new BigDecimal("0.01")); + } + } + price = price.add(oldOrders.getPayMoney()); + ordersLists.add(oldOrders); + } + Orders orders1 = ordersLists.get(0); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders1.getUserId()); + if (userMoney.getMoney().doubleValue() < price.doubleValue()) { + return Result.error("余额不足,请充值!"); + } + + for (Orders orders : ordersLists) { + if (orders.getCouponId() != null) { + TbCouponUser tbCouponUser = couponUserService.getById(orders.getCouponId()); + tbCouponUser.setStatus(1); + tbCouponUser.setEmployTime(new Date()); + couponUserService.updateById(tbCouponUser); + } + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + goodsSku.setStock(goodsSku.getStock() - orders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + UserEntity userEntity = userService.selectUserById(orders.getUserId()); + userMoneyService.updateMoney(2, orders.getUserId(), orders.getPayMoney()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(orders.getPayMoney()); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setContent("支付订单:" + orders.getOrdersNo()); + userMoneyDetails.setTitle("下单成功"); + userMoneyDetails.setType(2); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单下单成功:" + orders.getOrdersNo()); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + orders.setState("4"); + orders.setIsRemind(0); + orders.setPayWay(1); + baseMapper.updateById(orders); + } + return Result.success(); + } + + @Override + public Result selectOrderListByOrdersIds(String ids) { + List list = new ArrayList<>(); + for (String id : ids.split(",")) { + Orders orders = baseMapper.selectById(Long.parseLong(id)); + OrderTaking orderTaking = orderTakingDao.queryTakingDetails(orders.getOrderTakingId(), null, null); + orders.setOrderTaking(orderTaking); + orders.setIsNeedBucket(orderTaking.getIsNeedBucket()); + list.add(orders); + } + return Result.success().put("data", list); + } + + @Override + public Result selectMyOrder(Long userId, IPage iPage, String status, Integer isShopping) { + + return Result.success().put("data", new PageUtils(baseMapper.selectMyOrder(iPage, userId, status, isShopping))); + } + + @Override + public Result selectOrderList(Long page, Long limit, String createTime, String distance, String longitude, String latitude, Long laundryId) { + if (laundryId == null) { + return Result.success().put("data", null); + } + return Result.success().put("data", new PageUtils(baseMapper.selectOrderList(new Page(page, limit), createTime, distance, longitude, latitude, laundryId))); + } + + @Override + public Result insertMyOrders(Long ordersId, Long userId, String startImg) { + reentrantReadWriteLock.writeLock().lock(); + CommonInfo commonInfo = commonInfoService.findOne(329); + try { + Orders orders = baseMapper.selectById(ordersId); + if ("4".equals(orders.getState())) { + UserEntity userEntity = userService.getById(userId); + if ("是".equals(commonInfo.getValue())) { + UserCertification certification = certificationService.getOne(new QueryWrapper().eq("user_id", userEntity.getUserId())); + + if (certification == null || certification.getStatus() != 1 || userEntity.getIsAuthentication() == null) { + return Result.error("您还未实名认证,请实名认证后进行接单!"); + } + if (userEntity.getIsSafetyMoney() == null || userEntity.getIsSafetyMoney() != 1) { + return Result.error("您还未缴纳保证金,请缴纳后进行接单!"); + } + } + orders.setOrderTakingUserId(userId); + orders.setState("5"); + orders.setStartImg(startImg); + baseMapper.updateById(orders); + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + if (orderTaking == null) { + return Result.error("订单商品不存在"); + } + String value = commonInfoService.findOne(278).getValue(); + List msgList = new ArrayList<>(); + String title = orderTaking.getMyLevel(); + if (title.length() > 15) { + title = title.substring(0, 15) + "..."; + } + msgList.add(title); + msgList.add("已接单"); + msgList.add(DateUtils.format(new Date())); + UserEntity ordersUser = userService.getById(orders.getUserId()); + if (StringUtils.isNotEmpty(ordersUser.getOpenId())) { + SenInfoCheckUtil.sendMsg(ordersUser.getOpenId(), value, null, msgList, 1); + } + return Result.success(); + } else { + return Result.error("订单已经被抢走了!"); + } + } catch (Exception e) { + e.printStackTrace(); + log.error("抢单异常,订单id:" + ordersId, e); + } finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + + @Override + public Result investOrder(Long userId, Double money, Integer classify) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + PayDetails payDetails = new PayDetails(); + //分类( 1app微信 2微信公众号 3微信小程序 4支付宝) + payDetails.setClassify(classify); + //订单编号 + payDetails.setOrderId(AliPayOrderUtil.createOrderId()); + //金额 + payDetails.setMoney(money); + //用户id + payDetails.setUserId(userId); + //状态0待支付 1支付成功 2失败 + payDetails.setState(0); + //创建时间 + payDetails.setCreateTime(simpleDateFormat.format(new Date())); + payDetailsDao.insert(payDetails); + return Result.success(); + } + + @Override + public Result giveOrdersUser(UserEntity user, Long ordersId) { + if (user == null) { + return Result.error("用户不存在!"); + } + if (user.getIsAuthentication() == null) { + return Result.error("该用户尚未实名认证,请实名认证后进行接单!"); + } + if (user.getIsSafetyMoney() == null || user.getIsSafetyMoney() != 1) { + return Result.error("该用户尚未缴纳保证金,请缴纳后进行接单!"); + } + Orders orders = baseMapper.selectById(ordersId); + if ("2".equals(orders.getState()) || "3".equals(orders.getState())) { + return Result.error("订单当前状态不允许转接!"); + } + orders.setOrderTakingUserId(user.getUserId()); + orders.setIsTransfer(1); + orders.setState("5"); + baseMapper.updateById(orders); + + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + if (orderTaking != null) { + UserEntity ordersUser = userService.selectUserById(orders.getUserId()); + + String title = orderTaking.getServiceName(); + if (title.length() > 15) { + title = title.substring(0, 15) + "..."; + } + + if (ordersUser != null) { + String value = commonInfoService.findOne(278).getValue(); + List msgList = new ArrayList<>(); + + msgList.add(title); + msgList.add("已接单"); + msgList.add(DateUtils.format(new Date())); + + if (StringUtils.isNotEmpty(ordersUser.getOpenId())) { + SenInfoCheckUtil.sendMsg(ordersUser.getOpenId(), value, null, msgList, 1); + } + } + + //商家通知 + String shopValue = commonInfoService.findOne(321).getValue(); + List shopMsgList = new ArrayList<>(); + shopMsgList.add(orders.getOrdersNo()); + shopMsgList.add(title); + shopMsgList.add(orders.getPhone()); + shopMsgList.add("请尽快与对方联系"); + if (StringUtils.isNotEmpty(user.getShopOpenId())) { + SenInfoCheckUtil.sendShopMsg(user.getShopOpenId(), shopValue, null, shopMsgList, 3); + } + + + } + return Result.success(); + } + + + @Override + public Result cancelOrder(Long id, String status, String code, String endImg, String startImg, String noCodeFinishImg) { + reentrantReadWriteLock.writeLock().lock(); + try { + return cancelOrders(id, status, code, endImg, startImg, noCodeFinishImg); + } catch (Exception e) { + e.printStackTrace(); + log.error("修改订单异常:" + e.getMessage(), e); + } finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + @Transactional + public Result cancelOrders(Long id, String status, String code, String endImg, String startImg, String noCodeFinishImg) { + Orders orders = baseMapper.selectById(id); + + if (orders != null) { + if ("3".equals(status) && "0".equals(orders.getState())) { + if (orders.getCouponId() != null) { + TbCouponUser tbCouponUser = new TbCouponUser(); + tbCouponUser.setId(orders.getCouponId()); + tbCouponUser.setStatus(0); + couponUserService.updateById(tbCouponUser); + } + } + if ("1".equals(orders.getState()) || "4".equals(orders.getState()) || "5".equals(orders.getState())) { + if ("2".equals(status) || "5".equals(status)) { + if ("2".equals(status) && !code.equals(orders.getCode())) { + return Result.error("确认码不正确!"); + } + if ("5".equals(status) && StringUtils.isBlank(noCodeFinishImg)) { + return Result.error("请上传商品位置图片"); + } + orders.setNoCodeFinishImg(noCodeFinishImg); + orders.setEndImg(endImg); + //完成订单 + OrderTaking orderTaking = orderTakingDao.selectById(orders.getOrderTakingId()); + Integer ordersCount = baseMapper.selectCount(new QueryWrapper().eq("order_taking_id", orders.getOrderTakingId()).eq("state", 2).eq("orders_type", 1)); + ordersCount += baseMapper.selectCount(new QueryWrapper().eq("order_taking_id", orders.getOrderTakingId()).eq("state", 1).eq("orders_type", 1)); + orderTaking.setCount(ordersCount); + orderTaking.setId(orders.getOrderTakingId()); + orderTaking.setSalesNum((orderTaking.getSalesNum() == null ? 0 : orderTaking.getSalesNum()) + orders.getOrderNumber()); + orderTakingService.updateById(orderTaking); + BigDecimal payMoney = orders.getPayMoney(); + String time = DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN); + + + //判断是否开启分销 + String value = commonInfoService.findOne(209).getValue(); + if ("是".equals(value)) { + //分销 + UserEntity userEntity = userService.selectUserById(orders.getOrderTakingUserId()); + //陪玩官 + BigDecimal peiMoney = new BigDecimal("0.00"); + if (userEntity.getRate().doubleValue() == 0 || userEntity.getRate().doubleValue() < 0) { + peiMoney = payMoney; + } else { + peiMoney = payMoney.multiply(userEntity.getRate()); + } + + peiMoney = peiMoney.setScale(2, BigDecimal.ROUND_HALF_DOWN); + BigDecimal pingRate = payMoney.subtract(peiMoney); + orders.setRate(peiMoney); + userMoneyService.updateMoney(1, orders.getOrderTakingUserId(), peiMoney); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(orders.getOrderTakingUserId()); + userMoneyDetails.setTitle("订单完成:" + orders.getOrdersNo()); + if (orders.getCouponId() != null) { + TbCouponUser couponUser = couponUserService.getById(orders.getCouponId()); + userMoneyDetails.setContent("订单完成,订单金额:" + payMoney + ",优惠金额" + couponUser.getMoney() + "元,平台服务费:" + pingRate + ",实际到账金额:" + peiMoney); + + } else { + userMoneyDetails.setContent("订单完成,订单金额:" + payMoney + ",平台服务费:" + pingRate + ",实际到账金额:" + peiMoney); + + } + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(peiMoney); + userMoneyDetails.setCreateTime(time); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + userMoneyDetailsService.save(userMoneyDetails); + userEntity = userService.selectUserById(orders.getUserId()); + //推广员 + UserEntity zhiUser = userService.queryByInvitationCode(userEntity.getInviterCode()); + if (zhiUser != null && zhiUser.getIsPromotion() != null && zhiUser.getIsPromotion() == 1) { + if (zhiUser.getZhiRate().doubleValue() != 0 && zhiUser.getZhiRate().doubleValue() > 0) { + peiMoney = payMoney.multiply(zhiUser.getZhiRate()); + peiMoney = peiMoney.setScale(2, BigDecimal.ROUND_HALF_DOWN); + orders.setZhiRate(peiMoney); + orders.setZhiUserId(zhiUser.getUserId()); + userMoneyService.updateMoney(1, zhiUser.getUserId(), peiMoney); + userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(zhiUser.getUserId()); + userMoneyDetails.setTitle("推广佣金订单完成:" + orders.getOrdersNo()); + userMoneyDetails.setContent("推广佣金订单完成,到账金额:" + peiMoney); + userMoneyDetails.setType(1); + userMoneyDetails.setClassify(10); + userMoneyDetails.setMoney(peiMoney); + userMoneyDetails.setCreateTime(time); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + userMoneyDetailsService.save(userMoneyDetails); + } + } + + //代理商 + UserEntity feiUser = userService.queryAgentUser(orders.getProvince(), orders.getCity(), orders.getDistrict()); + if (feiUser == null) { + feiUser = userService.queryAgentUser(orders.getProvince(), orders.getCity(), null); + if (feiUser == null) { + feiUser = userService.queryAgentUser(orders.getProvince(), null, null); + } + } + if (feiUser != null) { + if (feiUser.getFeiRate().doubleValue() != 0 && feiUser.getFeiRate().doubleValue() > 0) { + peiMoney = payMoney.multiply(feiUser.getFeiRate()); + peiMoney = peiMoney.setScale(2, BigDecimal.ROUND_HALF_DOWN); + orders.setFeiRate(peiMoney); + orders.setFeiUserId(feiUser.getUserId()); + userMoneyService.updateMoney(1, feiUser.getUserId(), peiMoney); + userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(feiUser.getUserId()); + userMoneyDetails.setTitle("代理商佣金订单完成:" + orders.getOrdersNo()); + userMoneyDetails.setContent("代理商佣金订单完成,到账金额:" + peiMoney); + userMoneyDetails.setType(1); + userMoneyDetails.setClassify(20); + userMoneyDetails.setMoney(peiMoney); + userMoneyDetails.setCreateTime(time); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + userMoneyDetailsService.save(userMoneyDetails); + } + } + } else { + orders.setRate(payMoney); + userMoneyService.updateMoney(1, orders.getOrderTakingUserId(), payMoney); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(orders.getOrderTakingUserId()); + userMoneyDetails.setTitle("订单完成:" + orders.getOrdersNo()); + userMoneyDetails.setContent("订单完成,到账金额:" + payMoney); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(payMoney); + userMoneyDetails.setCreateTime(time); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + userMoneyDetailsService.save(userMoneyDetails); + } + BigDecimal pingRate = orders.getPayMoney().subtract(orders.getRate()); + if (orders.getZhiRate() != null) { + pingRate = pingRate.subtract(orders.getZhiRate()); + } + if (orders.getFeiRate() != null) { + pingRate = pingRate.subtract(orders.getFeiRate()); + } + orders.setPingRate(pingRate); + + orders.setEndTime(DateUtils.format(new Date())); + String values = commonInfoService.findOne(278).getValue(); + List msgList = new ArrayList<>(); + String title = orderTaking.getMyLevel(); + if (title.length() > 15) { + title = title.substring(0, 15) + "..."; + } + msgList.add(title); + msgList.add("已完成"); + msgList.add(DateUtils.format(new Date())); + UserEntity ordersUser = userService.selectUserById(orders.getUserId()); + if (StringUtils.isNotEmpty(ordersUser.getOpenId())) { + SenInfoCheckUtil.sendMsg(ordersUser.getOpenId(), values, null, msgList, 1); + } + + } else if ("3".equals(status)) { + + TbCouponUser tbCouponUser = new TbCouponUser(); + tbCouponUser.setId(orders.getCouponId()); + tbCouponUser.setStatus(0); + couponUserService.updateById(tbCouponUser); + + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + goodsSku.setStock(goodsSku.getStock() + orders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + + if (orders.getPayWay() == null || orders.getPayWay() == 1) { + //退款 + userMoneyService.updateMoney(1, orders.getUserId(), orders.getPayMoney()); + } else if (orders.getPayWay() == 2) { + //微信 + boolean refund = wxService.refund(orders.getOrdersNo()); + if (!refund) { + return Result.error("退款失败,请联系客服处理!"); + } + } else if (orders.getPayWay() == 3) { + //支付宝 + String data = aliPayController.alipayRefund(orders.getOrdersNo()); + if (StringUtils.isNotBlank(data)) { + log.error(data); + JSONObject jsonObject = JSON.parseObject(data); + JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response"); + String code1 = alipay_trade_refund_response.getString("code"); + if (!"10000".equals(code1)) { + return Result.error("退款失败!" + alipay_trade_refund_response.getString("sub_msg")); + } + } else { + return Result.error("退款失败!"); + } + //水票支付 + } else if (orders.getPayWay() == 4) { + TicketsUserRole userRole = userRoleService.getById(orders.getRoleId()); + Tickets tickets = ticketsService.getById(userRole.getTicketsId()); + UserEntity userEntity = userService.getById(userRole.getUserId()); + userRole.setNum(userRole.getNum() - orders.getOrderNumber()); + userRoleService.updateById(userRole); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单号" + orders.getOrdersNo() + "取消,水票返还【" + tickets.getTitle() + "】共" + orders.getOrderNumber() + "张"); + messageInfo.setTitle("订单水票返还"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(new SimpleDateFormat().format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + } + if (orders.getPayWay() != 4) { + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setTitle("订单退款:" + orders.getOrdersNo()); + userMoneyDetails.setContent("订单已原路退款:" + orders.getPayMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + userMoneyDetails.setMoney(orders.getPayMoney()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + } + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + String values = commonInfoService.findOne(278).getValue(); + List msgList = new ArrayList<>(); + String title = orderTaking.getMyLevel(); + if (title.length() > 15) { + title = title.substring(0, 15) + "..."; + } + msgList.add(title); + msgList.add("已退款"); + msgList.add(DateUtils.format(new Date())); + UserEntity ordersUser = userService.selectUserById(orders.getUserId()); + if (StringUtils.isNotEmpty(ordersUser.getOpenId())) { + SenInfoCheckUtil.sendMsg(ordersUser.getOpenId(), values, null, msgList, 1); + } + + } else if ("1".equals(status)) { + orders.setStartImg(startImg); + } + if ("5".equals(status) || "2".equals(status)) { + orders.setState("2"); + } else { + orders.setState(status); + } + baseMapper.updateById(orders); + } else if ("0".equals(orders.getState())) { + orders.setState("3"); + } + baseMapper.updateById(orders); + return Result.success(); + + } else { + return Result.error("订单不存在!"); + } + } + + + @Override + public Result deleteOrder(Long id) { + Orders orders = baseMapper.selectById(id); + if (orders != null) { + orders.setIsdelete((long) 1); + baseMapper.update(orders, new QueryWrapper().eq("orders_id", id)); + return Result.success(); + } else { + return Result.error("订单不存在!"); + } + } + + @Override + public Result queryOrders(Long id) { + Orders orders = baseMapper.selectById(id); + OrderTaking orderTaking = orderTakingDao.selectById(orders.getOrderTakingId()); + if (orderTaking != null) { + //orders.setGame(gameDao.selectById(orderTaking.getGameId())); + orders.setOrderTaking(orderTaking); + + } + if (orders.getOrderTakingUserId() != null) { + UserEntity userEntity = userDao.selectById(orders.getOrderTakingUserId()); + orders.setUser(userEntity); + } + if (orders.getCouponId() != null) { + TbCouponUser couponUser = couponUserService.getById(orders.getCouponId()); + orders.setCouponUser(couponUser); + } + if (orders.getLaundryId() != null) { + Laundry laundry = laundryRepository.findById(orders.getLaundryId()).orElse(null); + if (laundry != null) { + orders.setLaundryPhone(laundry.getLaundryPhone()); + } + } + return Result.success().put("data", orders); + } + + @Override + public Result queryOrdersAll(Long page, Long limit, Long type, String name, Long status, Long userId, + String ordersNo, String startTime, String endTime, Long laundryId, Long orderTakingUserId) { + IPage iPage = new Page<>(page, limit); + String str = null; + if (name != null && !(name.equals(""))) { + str = "%" + name + "%"; + } + return Result.success().put("data", new PageUtils(baseMapper.queryOrdersAll(iPage, type, str, status, userId, ordersNo, startTime, endTime, laundryId, orderTakingUserId))); + } + + @Override + public ExcelData ordersListExcel(Long type, String name, Long status, Long userId, String ordersNo, String startTime, String endTime, Long laundryId) { + if (StringUtils.isNotEmpty(name)) { + name = "%" + name + "%"; + } + List orderAllResponses = baseMapper.ordersListExcel(type, name, status, userId, ordersNo, startTime, endTime, laundryId); + ExcelData data = new ExcelData(); + data.setName("订单列表"); + List titles = new ArrayList(); + titles.add("编号"); + titles.add("接单用户"); + titles.add("下单用户"); + titles.add("订单编号"); + titles.add("订单类型"); + titles.add("标题"); + titles.add("发布价格"); + titles.add("普通用户价格"); + titles.add("会员价格"); + titles.add("商家佣金"); + titles.add("一级佣金"); + titles.add("二级佣金"); + titles.add("平台金额"); + titles.add("时长"); + titles.add("单位"); + titles.add("支付金额"); + titles.add("上门时间"); + titles.add("备注"); + titles.add("收货码"); + titles.add("订单状态"); + titles.add("创建时间"); + titles.add("是否为转单"); + data.setTitles(titles); + List> rows = new ArrayList(); + for (OrderAllResponse orderAllResponse : orderAllResponses) { + List row = new ArrayList(); + row.add(orderAllResponse.getOrdersId()); + row.add(orderAllResponse.getUserName()); + row.add(orderAllResponse.getOrdersUserName()); + row.add(orderAllResponse.getOrdersNo()); + if (orderAllResponse.getOrdersType() == 1) { + row.add("服务订单"); + } else { + row.add("会员订单"); + } + row.add(orderAllResponse.getMyLevel() == null ? "" : orderAllResponse.getMyLevel()); + row.add(orderAllResponse.getOldMoney() == null ? "" : orderAllResponse.getOldMoney()); + row.add(orderAllResponse.getMoney() == null ? "" : orderAllResponse.getMoney()); + row.add(orderAllResponse.getMemberMoney() == null ? "" : orderAllResponse.getMemberMoney()); + row.add(orderAllResponse.getRate() == null ? 0 : orderAllResponse.getRate()); + row.add(orderAllResponse.getZhiRate() == null ? 0 : orderAllResponse.getZhiRate()); + row.add(orderAllResponse.getFeiRate() == null ? 0 : orderAllResponse.getFeiRate()); + row.add(orderAllResponse.getPingRate() == null ? 0 : orderAllResponse.getPingRate()); + row.add(orderAllResponse.getOrderNumber() == null ? "" : orderAllResponse.getOrderNumber()); + row.add(orderAllResponse.getUnit() == null ? "" : orderAllResponse.getUnit()); + row.add(orderAllResponse.getPayMoney() == null ? "" : orderAllResponse.getPayMoney()); + row.add(orderAllResponse.getStartTime() == null ? "" : orderAllResponse.getStartTime()); + row.add(orderAllResponse.getRemarks() == null ? "" : orderAllResponse.getRemarks()); + row.add(orderAllResponse.getCode() == null ? "" : orderAllResponse.getCode()); + if (orderAllResponse.getState() == 0) { + row.add("待支付"); + } else if (orderAllResponse.getState() == 1) { + row.add("进行中"); + } else if (orderAllResponse.getState() == 2) { + row.add("已完成"); + } else if (orderAllResponse.getState() == 3) { + row.add("已退款"); + } else { + row.add("未知"); + } + row.add(orderAllResponse.getCreateTime() == null ? "" : orderAllResponse.getCreateTime()); + if (orderAllResponse.getIsTransfer() != null && orderAllResponse.getIsTransfer() == 1) { + row.add("是"); + } else { + row.add("否"); + } + rows.add(row); + } + data.setRows(rows); + return data; + } + + + @Override + public Result selectMyTakeOrders(Integer page, Integer limit, Long userId, Integer status) { + Page> pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + + return Result.success().put("data", baseMapper.selectMyTakeOrders(pages, userId, status)); + } + + @Override + public Result selectNowDayOrders(Integer page, Integer limit, Long userId) { + Page> pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + + return Result.success().put("data", baseMapper.selectNowDayOrders(pages, userId)); + } + + + @Override + public Result payMoney(Long ordersId) { + Orders orders = baseMapper.selectById(ordersId); + + if (orders != null) { + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId()); + if (userMoney.getMoney().doubleValue() >= orders.getPayMoney().doubleValue()) { + + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + if (goodsSku.getStock() < orders.getOrderNumber()) { + return Result.error(orderTaking.getServiceName() + " 剩余库存不足!"); + } + goodsSku.setStock(goodsSku.getStock() - orders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + + UserEntity userEntity = userService.selectUserById(orders.getUserId()); + userMoneyService.updateMoney(2, orders.getUserId(), orders.getPayMoney()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(orders.getPayMoney()); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setContent("零钱支付订单"); + userMoneyDetails.setTitle("下单成功,订单号:" + orders.getOrdersNo()); + userMoneyDetails.setType(2); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单下单成功:" + orders.getOrdersNo()); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + String userName = userEntity.getUserName(); + orders.setState("4"); + if (orders.getOrderTakingUserId() != null) { + orders.setState("5"); + } + orders.setIsRemind(0); + orders.setPayWay(1); + OrderTaking byId = orderTakingService.getById(orders.getOrderTakingId()); + + baseMapper.updateById(orders); + + + return Result.success(); + } else { + return Result.error("账户不足,请充值!"); + } + } else { + return Result.error("订单不存在,请刷新后重试!"); + } + } + + @Override + public PageUtils incomeAnalysisOrders(Integer page, Integer limit, String time, Integer flag) { + Page> pages = new Page<>(page, limit); + return new PageUtils(baseMapper.incomeAnalysisOrders(pages, time, flag)); + } + + @Override + public Integer getOrdersRemind(Long userId) { + return baseMapper.getOrdersRemind(userId); + } + + @Override + public int updateOrdersIsRemind(Long userId) { + return baseMapper.updateOrdersIsRemind(userId); + } + + @Override + public Result selectTeamOrdersList(Integer page, Integer limit, Long userId, Integer type, Integer status) { + return Result.success().put("data", new PageUtils(baseMapper.selectTeamOrdersList(new Page<>(page, limit), userId, type, status))); + } + + @Override + public Result selectTeamUserList(Integer page, Integer limit, String invitationCode, Integer type, Long userId) { + if (type == 1) { + return Result.success().put("data", new PageUtils(baseMapper.selectTeamUserList(new Page<>(page, limit), invitationCode, type, userId))); + } else { + return Result.success().put("data", new PageUtils(baseMapper.selectTeamUserList2(new Page<>(page, limit), type, userId))); + } + } + + @Override + public Double selectOrdersMoneyCountByUserId(Long userId, Integer type, String time) { + return baseMapper.selectOrdersMoneyCountByUserId(userId, type, time); + } + + @Override + public Integer selectUserCountByInvitationCode(String invitationCode, Integer type) { + return baseMapper.selectUserCountByInvitationCode(invitationCode, type); + } + + @Override + public Result selectNewestOrders() { + //下单信息 + List> maps = baseMapper.selectNewestOrders(); + return Result.success().put("data", maps); + } + + @Override + public Result selectOrdersCountAndMoney(Long userId) { + return Result.success().put("data", baseMapper.selectOrdersCountAndMoney(userId)); + } + + @Override + public Result selectStaffUserMoney(Long userId) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dayTime = sdf.format(new Date()); + //累计收益 今日收益 本月预估收益 本月预估提现 + BigDecimal sumMoney = baseMapper.selectSumMoney(userId, null, null); + BigDecimal dayMoney = baseMapper.selectEstimationSumMoneyBy(userId, dayTime, 1); + BigDecimal monthMoney = baseMapper.selectEstimationSumMoneyBy(userId, dayTime, 2); + BigDecimal cashMoney = cashOutDao.sumMoneyByUserId(userId, dayTime, 2); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + Map result = new HashMap<>(); + result.put("sumMoney", sumMoney); + result.put("dayMoney", dayMoney); + result.put("monthMoney", monthMoney); + result.put("cashMoney", cashMoney); + result.put("money", userMoney.getMoney()); + return Result.success().put("data", result); + } + + @Override + public Result ticketPayMoney(List ordersList) { + for (Orders orders : ordersList) { + Orders oldOrders = baseMapper.selectById(orders.getOrdersId()); + if (oldOrders != null) { + if (!"0".equals(oldOrders.getState())) { + return Result.error("该订单已支付"); + } + OrderTaking orderTaking = orderTakingService.getById(oldOrders.getOrderTakingId()); + GoodsSku goodsSku = goodsSkuService.getById(oldOrders.getSkuId()); + if (goodsSku.getStock() < oldOrders.getOrderNumber()) { + return Result.error(orderTaking.getServiceName() + " 剩余库存不足!"); + } + + UserEntity userEntity = userService.selectUserById(oldOrders.getUserId()); + TicketsUserRole ticketsUserRole = userRoleService.getById(orders.getRoleId()); + if (oldOrders.getOrderNumber() > (ticketsUserRole.getStock() - ticketsUserRole.getNum())) { + return Result.error(orderTaking.getServiceName() + "的水票数量不足"); + } + Tickets tickets = ticketsService.getOne(new QueryWrapper().eq("tickets_id", ticketsUserRole.getTicketsId()).like("relation_id", oldOrders.getOrderTakingId())); + if (tickets == null) { + return Result.error("你选择的水票不能购买当前商品"); + } + ticketsUserRole.setNum(ticketsUserRole.getNum() + oldOrders.getOrderNumber()); + userRoleService.updateById(ticketsUserRole); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单下单成功:" + oldOrders.getOrdersNo()); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + + + oldOrders.setRemarks(orders.getRemarks()); + oldOrders.setStartTime(orders.getStartTime()); + oldOrders.setName(orders.getName()); + oldOrders.setPhone(orders.getPhone()); + oldOrders.setIsShopping(2); + oldOrders.setState("4"); + oldOrders.setIsRemind(0); + oldOrders.setPayWay(4); + oldOrders.setRoleId(orders.getRoleId()); + + baseMapper.updateById(oldOrders); + + goodsSku.setStock(goodsSku.getStock() - oldOrders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + UserMoneyDetails details = new UserMoneyDetails(); + details.setUserId(userEntity.getUserId()); + details.setClassify(9); + details.setPayType(4); + details.setMoney(oldOrders.getPayMoney()); + details.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + details.setType(2); + details.setTitle("水票支付订单:" + oldOrders.getOrdersNo()); + details.setContent("花费" + oldOrders.getOrderNumber() + "张水票购买商品【" + orderTaking.getServiceName() + "】" + oldOrders.getOrderNumber() + "个"); + userMoneyDetailsService.save(details); + + + } else { + return Result.error("订单不存在"); + } + + } + return Result.success(); + } + + @Override + public Result startDelivery(Long ordersId, Long userId) { + Orders orders = new Orders(); + orders.setOrdersId(ordersId); + orders.setState("1"); + return Result.upStatus(baseMapper.updateById(orders)); + } + + @Override + public Result selectLaundryMoneyStatistics(Integer page, Integer limit, String laundryName) { + Page> pages = new Page<>(page, limit); + return Result.success().put("data", new PageUtils(baseMapper.selectLaundryMoneyStatistics(pages, laundryName))); + } + + @Override + public BigDecimal selectLaundryMoneyByLaundryId(Long laundryId) { + return baseMapper.selectLaundryMoneyByLaundryId(laundryId); + } + + + @Scheduled(fixedDelay = 60 * 1000) + public void cleanOrdersByTime() { + String minute = commonInfoService.findOne(322).getValue(); + baseMapper.updateOrdersStateByCreateTime(minute); + + String value = commonInfoService.findOne(318).getValue(); + List ordersList = baseMapper.cleanOrdersByTime(value); + for (Orders orders : ordersList) { + try { + TbCouponUser tbCouponUser = new TbCouponUser(); + tbCouponUser.setId(orders.getCouponId()); + tbCouponUser.setStatus(0); + couponUserService.updateById(tbCouponUser); + + + if (orders.getPayWay() == null || orders.getPayWay() == 1) { + //退款 + userMoneyService.updateMoney(1, orders.getUserId(), orders.getPayMoney()); + } else if (orders.getPayWay() == 2) { + //微信 + boolean refund = wxService.refund(orders.getOrdersNo()); + if (!refund) { + continue; + } + } else if (orders.getPayWay() == 3) { + //支付宝 + String data = aliPayController.alipayRefund(orders.getOrdersNo()); + if (StringUtils.isNotBlank(data)) { + log.error(data); + JSONObject jsonObject = JSON.parseObject(data); + JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response"); + String code1 = alipay_trade_refund_response.getString("code"); + if (!"10000".equals(code1)) { + continue; + } + } else { + continue; + } + //水票支付 + } else if (orders.getPayWay() == 4) { + TicketsUserRole userRole = userRoleService.getById(orders.getRoleId()); + Tickets tickets = ticketsService.getById(userRole.getTicketsId()); + UserEntity userEntity = userService.getById(userRole.getUserId()); + userRole.setNum(userRole.getNum() - orders.getOrderNumber()); + userRoleService.updateById(userRole); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单号" + orders.getOrdersNo() + "取消,水票返还【" + tickets.getTitle() + "】共" + orders.getOrderNumber() + "张"); + messageInfo.setTitle("订单水票返还"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(new SimpleDateFormat().format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + } + if (orders.getPayWay() != 4) { + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setTitle("订单退款:" + orders.getOrdersNo()); + userMoneyDetails.setContent("订单已原路退款:" + orders.getPayMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + userMoneyDetails.setMoney(orders.getPayMoney()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + } + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + String values = commonInfoService.findOne(278).getValue(); + List msgList = new ArrayList<>(); + String title = orderTaking.getMyLevel(); + if (title.length() > 15) { + title = title.substring(0, 15) + "..."; + } + msgList.add(title); + msgList.add("已退款"); + msgList.add(DateUtils.format(new Date())); + UserEntity ordersUser = userService.selectUserById(orders.getUserId()); + if (StringUtils.isNotEmpty(ordersUser.getOpenId())) { + SenInfoCheckUtil.sendMsg(ordersUser.getOpenId(), values, null, msgList, 1); + } + } catch (Exception e) { + e.printStackTrace(); + log.error("自动取消订单异常:" + orders.getOrdersId(), e); + } + } + } + + + @Override + public Integer selectOrdersCount(Integer status, Integer ordersType, Integer flag, String time) { + return baseMapper.selectOrdersCount(status, ordersType, flag, time); + } + + @Override + public Integer selectOrdersNumber(Integer status, Integer ordersType, Integer flag, String time) { + return baseMapper.selectOrdersNumber(status, ordersType, flag, time); + } + + @Override + public Double selectOrdersMoney(Integer status, Integer ordersType, Integer flag, String time) { + return baseMapper.selectOrdersMoney(status, ordersType, flag, time); + } + + @Override + public List> getUserBucket(Integer flag, String date) { + + return baseMapper.getUserBucket(flag, date); + + } + + @Override + public Integer getUserBucketCount(Long userId) { + + + return baseMapper.getUserBucketCount(userId); + + + } +} diff --git a/src/main/java/com/sqx/modules/orders/service/impl/PayOrderServiceImpl.java b/src/main/java/com/sqx/modules/orders/service/impl/PayOrderServiceImpl.java new file mode 100644 index 0000000..e4eeaf9 --- /dev/null +++ b/src/main/java/com/sqx/modules/orders/service/impl/PayOrderServiceImpl.java @@ -0,0 +1,56 @@ +package com.sqx.modules.orders.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.orders.dao.PayOrderDao; +import com.sqx.modules.orders.entity.PayOrder; +import com.sqx.modules.orders.service.PayOrderService; +import com.sqx.modules.utils.AliPayOrderUtil; +import lombok.AllArgsConstructor; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; + +@Service +@AllArgsConstructor +public class PayOrderServiceImpl extends ServiceImpl implements PayOrderService { + private CommonInfoService commonInfoService; + + @Override + public Result insertOrder(Long userId, BigDecimal money) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + int i = money.compareTo(BigDecimal.ZERO); + if (i == 1) { + //创建订单模板 + PayOrder order = new PayOrder(); + //订单编号 + order.setOrdersNo(AliPayOrderUtil.createOrderId()); + //设置充值金额 + order.setPayMoney(money); + //查询金币比例 + String scale = commonInfoService.findOne(154).getValue(); + Integer scel = Integer.parseInt(scale); + //计算 + BigDecimal nmoeny = money.multiply(BigDecimal.valueOf(scel)); + //设置金币金额 + order.setMoney(nmoeny); + //状态 + order.setState(0); + //用户id + order.setUserId(userId); + //设置创建时间 + order.setCreateTime(simpleDateFormat.format(new Date())); + //插入到表中 + baseMapper.insert(order); + + return Result.success().put("data", order); + } else { + return Result.error("充值的金额不合法!"); + } + } +} diff --git a/src/main/java/com/sqx/modules/oss/cloud/AliyunCloudStorageService.java b/src/main/java/com/sqx/modules/oss/cloud/AliyunCloudStorageService.java new file mode 100644 index 0000000..060ac84 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/cloud/AliyunCloudStorageService.java @@ -0,0 +1,53 @@ +package com.sqx.modules.oss.cloud; + +import com.aliyun.oss.OSSClient; +import com.sqx.common.exception.SqxException; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +/** + * 阿里云存储 + * + */ +public class AliyunCloudStorageService extends CloudStorageService { + private OSSClient client; + + public AliyunCloudStorageService(CloudStorageConfig config){ + this.config = config; + + //初始化 + init(); + } + + private void init(){ + client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(), + config.getAliyunAccessKeySecret()); + } + + @Override + public String upload(byte[] data, String path) { + return upload(new ByteArrayInputStream(data), path); + } + + @Override + public String upload(InputStream inputStream, String path) { + try { + client.putObject(config.getAliyunBucketName(), path, inputStream); + } catch (Exception e){ + throw new SqxException("上传文件失败,请检查配置信息", e); + } + + return config.getAliyunDomain() + "/" + path; + } + + @Override + public String uploadSuffix(byte[] data, String suffix) { + return upload(data, getPath(config.getAliyunPrefix(), suffix)); + } + + @Override + public String uploadSuffix(InputStream inputStream, String suffix) { + return upload(inputStream, getPath(config.getAliyunPrefix(), suffix)); + } +} diff --git a/src/main/java/com/sqx/modules/oss/cloud/CloudStorageConfig.java b/src/main/java/com/sqx/modules/oss/cloud/CloudStorageConfig.java new file mode 100644 index 0000000..3786865 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/cloud/CloudStorageConfig.java @@ -0,0 +1,85 @@ +package com.sqx.modules.oss.cloud; + + +import com.sqx.common.validator.group.AliyunGroup; +import com.sqx.common.validator.group.QcloudGroup; +import com.sqx.common.validator.group.QiniuGroup; +import lombok.Data; +import org.hibernate.validator.constraints.Range; +import org.hibernate.validator.constraints.URL; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * 云存储配置信息 + * + */ +@Data +public class CloudStorageConfig implements Serializable { + private static final long serialVersionUID = 1L; + + //类型 1:七牛 2:阿里云 3:腾讯云 + @Range(min=1, max=3, message = "类型错误") + private Integer type; + + //七牛绑定的域名 + @NotBlank(message="七牛绑定的域名不能为空", groups = QiniuGroup.class) + @URL(message = "七牛绑定的域名格式不正确", groups = QiniuGroup.class) + private String qiniuDomain; + //七牛路径前缀 + private String qiniuPrefix; + //七牛ACCESS_KEY + @NotBlank(message="七牛AccessKey不能为空", groups = QiniuGroup.class) + private String qiniuAccessKey; + //七牛SECRET_KEY + @NotBlank(message="七牛SecretKey不能为空", groups = QiniuGroup.class) + private String qiniuSecretKey; + //七牛存储空间名 + @NotBlank(message="七牛空间名不能为空", groups = QiniuGroup.class) + private String qiniuBucketName; + + //阿里云绑定的域名 + @NotBlank(message="阿里云绑定的域名不能为空", groups = AliyunGroup.class) + @URL(message = "阿里云绑定的域名格式不正确", groups = AliyunGroup.class) + private String aliyunDomain; + //阿里云路径前缀 + private String aliyunPrefix; + //阿里云EndPoint + @NotBlank(message="阿里云EndPoint不能为空", groups = AliyunGroup.class) + private String aliyunEndPoint; + //阿里云AccessKeyId + @NotBlank(message="阿里云AccessKeyId不能为空", groups = AliyunGroup.class) + private String aliyunAccessKeyId; + //阿里云AccessKeySecret + @NotBlank(message="阿里云AccessKeySecret不能为空", groups = AliyunGroup.class) + private String aliyunAccessKeySecret; + //阿里云BucketName + @NotBlank(message="阿里云BucketName不能为空", groups = AliyunGroup.class) + private String aliyunBucketName; + + //腾讯云绑定的域名 + @NotBlank(message="腾讯云绑定的域名不能为空", groups = QcloudGroup.class) + @URL(message = "腾讯云绑定的域名格式不正确", groups = QcloudGroup.class) + private String qcloudDomain; + //腾讯云路径前缀 + private String qcloudPrefix; + //腾讯云AppId + @NotNull(message="腾讯云AppId不能为空", groups = QcloudGroup.class) + private Integer qcloudAppId; + //腾讯云SecretId + @NotBlank(message="腾讯云SecretId不能为空", groups = QcloudGroup.class) + private String qcloudSecretId; + //腾讯云SecretKey + @NotBlank(message="腾讯云SecretKey不能为空", groups = QcloudGroup.class) + private String qcloudSecretKey; + //腾讯云BucketName + @NotBlank(message="腾讯云BucketName不能为空", groups = QcloudGroup.class) + private String qcloudBucketName; + //腾讯云COS所属地区 + @NotBlank(message="所属地区不能为空", groups = QcloudGroup.class) + private String qcloudRegion; + + +} diff --git a/src/main/java/com/sqx/modules/oss/cloud/CloudStorageService.java b/src/main/java/com/sqx/modules/oss/cloud/CloudStorageService.java new file mode 100644 index 0000000..f5ef33d --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/cloud/CloudStorageService.java @@ -0,0 +1,69 @@ +package com.sqx.modules.oss.cloud; + +import com.sqx.common.utils.DateUtils; +import org.apache.commons.lang.StringUtils; + +import java.io.InputStream; +import java.util.Date; +import java.util.UUID; + +/** + * 云存储(支持七牛、阿里云、腾讯云、又拍云) + * + */ + public abstract class CloudStorageService { + /** 云存储配置信息 */ + CloudStorageConfig config; + + /** + * 文件路径 + * @param prefix 前缀 + * @param suffix 后缀 + * @return 返回上传路径 + */ + public String getPath(String prefix, String suffix) { + //生成uuid + String uuid = UUID.randomUUID().toString().replaceAll("-", ""); + //文件路径 + String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + uuid; + + if(StringUtils.isNotBlank(prefix)){ + path = prefix + "/" + path; + } + + return path + suffix; + } + + /** + * 文件上传 + * @param data 文件字节数组 + * @param path 文件路径,包含文件名 + * @return 返回http地址 + */ + public abstract String upload(byte[] data, String path); + + /** + * 文件上传 + * @param data 文件字节数组 + * @param suffix 后缀 + * @return 返回http地址 + */ + public abstract String uploadSuffix(byte[] data, String suffix); + + /** + * 文件上传 + * @param inputStream 字节流 + * @param path 文件路径,包含文件名 + * @return 返回http地址 + */ + public abstract String upload(InputStream inputStream, String path); + + /** + * 文件上传 + * @param inputStream 字节流 + * @param suffix 后缀 + * @return 返回http地址 + */ + public abstract String uploadSuffix(InputStream inputStream, String suffix); + +} diff --git a/src/main/java/com/sqx/modules/oss/cloud/OSSFactory.java b/src/main/java/com/sqx/modules/oss/cloud/OSSFactory.java new file mode 100644 index 0000000..0301447 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/cloud/OSSFactory.java @@ -0,0 +1,35 @@ +package com.sqx.modules.oss.cloud; + + +import com.sqx.common.utils.ConfigConstant; +import com.sqx.common.utils.Constant; +import com.sqx.common.utils.SpringContextUtils; +import com.sqx.modules.sys.service.SysConfigService; + +/** + * 文件上传Factory + * + */ +public final class OSSFactory { + private static SysConfigService sysConfigService; + + static { + OSSFactory.sysConfigService = (SysConfigService) SpringContextUtils.getBean("sysConfigService"); + } + + public static CloudStorageService build(){ + //获取云存储配置信息 + CloudStorageConfig config = sysConfigService.getConfigObject(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY, CloudStorageConfig.class); + + if(config.getType() == Constant.CloudService.QINIU.getValue()){ + return new QiniuCloudStorageService(config); + }else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){ + return new AliyunCloudStorageService(config); + }else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){ + return new QcloudCloudStorageService(config); + } + + return null; + } + +} diff --git a/src/main/java/com/sqx/modules/oss/cloud/QcloudCloudStorageService.java b/src/main/java/com/sqx/modules/oss/cloud/QcloudCloudStorageService.java new file mode 100644 index 0000000..97a01e1 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/cloud/QcloudCloudStorageService.java @@ -0,0 +1,79 @@ +package com.sqx.modules.oss.cloud; + + +import com.alibaba.fastjson.JSONObject; +import com.qcloud.cos.COSClient; +import com.qcloud.cos.ClientConfig; +import com.qcloud.cos.request.UploadFileRequest; +import com.qcloud.cos.sign.Credentials; +import com.sqx.common.exception.SqxException; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * 腾讯云存储 + * + */ +public class QcloudCloudStorageService extends CloudStorageService { + private COSClient client; + + public QcloudCloudStorageService(CloudStorageConfig config){ + this.config = config; + + //初始化 + init(); + } + + private void init(){ + Credentials credentials = new Credentials(config.getQcloudAppId(), config.getQcloudSecretId(), + config.getQcloudSecretKey()); + + //初始化客户端配置 + ClientConfig clientConfig = new ClientConfig(); + //设置bucket所在的区域,华南:gz 华北:tj 华东:sh + clientConfig.setRegion(config.getQcloudRegion()); + + client = new COSClient(clientConfig, credentials); + } + + @Override + public String upload(byte[] data, String path) { + //腾讯云必需要以"/"开头 + if(!path.startsWith("/")) { + path = "/" + path; + } + + //上传到腾讯云 + UploadFileRequest request = new UploadFileRequest(config.getQcloudBucketName(), path, data); + String response = client.uploadFile(request); + + JSONObject jsonObject = JSONObject.parseObject(response); + if(jsonObject.getInteger("code") != 0) { + throw new SqxException("文件上传失败," + jsonObject.getString("message")); + } + + return config.getQcloudDomain() + path; + } + + @Override + public String upload(InputStream inputStream, String path) { + try { + byte[] data = IOUtils.toByteArray(inputStream); + return this.upload(data, path); + } catch (IOException e) { + throw new SqxException("上传文件失败", e); + } + } + + @Override + public String uploadSuffix(byte[] data, String suffix) { + return upload(data, getPath(config.getQcloudPrefix(), suffix)); + } + + @Override + public String uploadSuffix(InputStream inputStream, String suffix) { + return upload(inputStream, getPath(config.getQcloudPrefix(), suffix)); + } +} diff --git a/src/main/java/com/sqx/modules/oss/cloud/QiniuCloudStorageService.java b/src/main/java/com/sqx/modules/oss/cloud/QiniuCloudStorageService.java new file mode 100644 index 0000000..02c459e --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/cloud/QiniuCloudStorageService.java @@ -0,0 +1,68 @@ +package com.sqx.modules.oss.cloud; + +import com.qiniu.common.Zone; +import com.qiniu.http.Response; +import com.qiniu.storage.Configuration; +import com.qiniu.storage.UploadManager; +import com.qiniu.util.Auth; +import com.sqx.common.exception.SqxException; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * 七牛云存储 + * + */ +public class QiniuCloudStorageService extends CloudStorageService { + private UploadManager uploadManager; + private String token; + + public QiniuCloudStorageService(CloudStorageConfig config){ + this.config = config; + + //初始化 + init(); + } + + private void init(){ + uploadManager = new UploadManager(new Configuration(Zone.autoZone())); + token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()). + uploadToken(config.getQiniuBucketName()); + } + + @Override + public String upload(byte[] data, String path) { + try { + Response res = uploadManager.put(data, path, token); + if (!res.isOK()) { + throw new RuntimeException("上传七牛出错:" + res.toString()); + } + } catch (Exception e) { + throw new SqxException("上传文件失败,请核对七牛配置信息", e); + } + + return config.getQiniuDomain() + "/" + path; + } + + @Override + public String upload(InputStream inputStream, String path) { + try { + byte[] data = IOUtils.toByteArray(inputStream); + return this.upload(data, path); + } catch (IOException e) { + throw new SqxException("上传文件失败", e); + } + } + + @Override + public String uploadSuffix(byte[] data, String suffix) { + return upload(data, getPath(config.getQiniuPrefix(), suffix)); + } + + @Override + public String uploadSuffix(InputStream inputStream, String suffix) { + return upload(inputStream, getPath(config.getQiniuPrefix(), suffix)); + } +} diff --git a/src/main/java/com/sqx/modules/oss/controller/SysOssController.java b/src/main/java/com/sqx/modules/oss/controller/SysOssController.java new file mode 100644 index 0000000..ca13462 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/controller/SysOssController.java @@ -0,0 +1,126 @@ +package com.sqx.modules.oss.controller; + +import com.google.gson.Gson; +import com.sqx.common.exception.SqxException; +import com.sqx.common.utils.ConfigConstant; +import com.sqx.common.utils.Constant; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.common.validator.ValidatorUtils; +import com.sqx.common.validator.group.AliyunGroup; +import com.sqx.common.validator.group.QcloudGroup; +import com.sqx.common.validator.group.QiniuGroup; +import com.sqx.modules.oss.cloud.CloudStorageConfig; +import com.sqx.modules.oss.cloud.OSSFactory; +import com.sqx.modules.oss.entity.SysOssEntity; +import com.sqx.modules.oss.service.SysOssService; +import com.sqx.modules.sys.service.SysConfigService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.Arrays; +import java.util.Date; +import java.util.Map; + +/** + * 文件上传 + * + */ +@RestController +@RequestMapping("sys/oss") +public class SysOssController { + @Autowired + private SysOssService sysOssService; + @Autowired + private SysConfigService sysConfigService; + + private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY; + + /** + * 列表 + */ + @GetMapping("/list") + @RequiresPermissions("sys:oss:all") + public Result list(@RequestParam Map params){ + PageUtils page = sysOssService.queryPage(params); + + return Result.success().put("page", page); + } + + + /** + * 云存储配置信息 + */ + @GetMapping("/config") + @RequiresPermissions("sys:oss:all") + public Result config(){ + CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class); + + return Result.success().put("config", config); + } + + + /** + * 保存云存储配置信息 + */ + @PostMapping("/saveConfig") + @RequiresPermissions("sys:oss:all") + public Result saveConfig(@RequestBody CloudStorageConfig config){ + //校验类型 + ValidatorUtils.validateEntity(config); + + if(config.getType() == Constant.CloudService.QINIU.getValue()){ + //校验七牛数据 + ValidatorUtils.validateEntity(config, QiniuGroup.class); + }else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){ + //校验阿里云数据 + ValidatorUtils.validateEntity(config, AliyunGroup.class); + }else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){ + //校验腾讯云数据 + ValidatorUtils.validateEntity(config, QcloudGroup.class); + } + + sysConfigService.updateValueByKey(KEY, new Gson().toJson(config)); + + return Result.success(); + } + + + /** + * 上传文件 + */ + @PostMapping("/upload") + @RequiresPermissions("sys:oss:all") + public Result upload(@RequestParam("file") MultipartFile file) throws Exception { + if (file.isEmpty()) { + throw new SqxException("上传文件不能为空"); + } + + //上传文件 + String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); + String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix); + + //保存文件信息 + SysOssEntity ossEntity = new SysOssEntity(); + ossEntity.setUrl(url); + ossEntity.setCreateDate(new Date()); + sysOssService.save(ossEntity); + + return Result.success().put("url", url); + } + + + /** + * 删除 + */ + @PostMapping("/delete") + @RequiresPermissions("sys:oss:all") + public Result delete(@RequestBody Long[] ids){ + sysOssService.removeByIds(Arrays.asList(ids)); + + return Result.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/oss/dao/SysOssDao.java b/src/main/java/com/sqx/modules/oss/dao/SysOssDao.java new file mode 100644 index 0000000..0112e15 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/dao/SysOssDao.java @@ -0,0 +1,14 @@ +package com.sqx.modules.oss.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.oss.entity.SysOssEntity; +import org.apache.ibatis.annotations.Mapper; + +/** + * 文件上传 + * + */ +@Mapper +public interface SysOssDao extends BaseMapper { + +} diff --git a/src/main/java/com/sqx/modules/oss/entity/SysOssEntity.java b/src/main/java/com/sqx/modules/oss/entity/SysOssEntity.java new file mode 100644 index 0000000..e869384 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/entity/SysOssEntity.java @@ -0,0 +1,27 @@ +package com.sqx.modules.oss.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + + +/** + * 文件上传 + * + */ +@Data +@TableName("sys_oss") +public class SysOssEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @TableId + private Long id; + //URL地址 + private String url; + //创建时间 + private Date createDate; + +} diff --git a/src/main/java/com/sqx/modules/oss/service/SysOssService.java b/src/main/java/com/sqx/modules/oss/service/SysOssService.java new file mode 100644 index 0000000..11c999e --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/service/SysOssService.java @@ -0,0 +1,16 @@ +package com.sqx.modules.oss.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.oss.entity.SysOssEntity; + +import java.util.Map; + +/** + * 文件上传 + * + */ +public interface SysOssService extends IService { + + PageUtils queryPage(Map params); +} diff --git a/src/main/java/com/sqx/modules/oss/service/impl/SysOssServiceImpl.java b/src/main/java/com/sqx/modules/oss/service/impl/SysOssServiceImpl.java new file mode 100644 index 0000000..0d6bf83 --- /dev/null +++ b/src/main/java/com/sqx/modules/oss/service/impl/SysOssServiceImpl.java @@ -0,0 +1,27 @@ +package com.sqx.modules.oss.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.modules.oss.dao.SysOssDao; +import com.sqx.modules.oss.entity.SysOssEntity; +import com.sqx.modules.oss.service.SysOssService; +import org.springframework.stereotype.Service; + +import java.util.Map; + + +@Service("sysOssService") +public class SysOssServiceImpl extends ServiceImpl implements SysOssService { + + @Override + public PageUtils queryPage(Map params) { + IPage page = this.page( + new Query().getPage(params) + ); + + return new PageUtils(page); + } + +} diff --git a/src/main/java/com/sqx/modules/pay/config/AliPayConstants.java b/src/main/java/com/sqx/modules/pay/config/AliPayConstants.java new file mode 100644 index 0000000..0d074cb --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/config/AliPayConstants.java @@ -0,0 +1,44 @@ +package com.sqx.modules.pay.config; + +/** + * @author WALKMAN + * @Description: 支付宝支付参数 + **/ +public class AliPayConstants { + + /** + * 支付宝环境 + */ + public static final String REQUEST_URL = "https://openapi.alipay.com/gateway.do"; + + /** + * 编码格式 + */ + public static String CHARSET = "UTF-8"; + + /** + * 参数格式 + */ + public static String FORMAT = "json"; + + /** + * 加密方式 + */ + public static String SIGNTYPE = "RSA2"; + + /** + * 支付类型-提现(固定) + */ + public static String PAY_TYPE = "ALIPAY_LOGONID"; + + /** + * 平台和支付宝签约属性-固定值 + */ + public static String PRODUCT_CODE = "QUICK_WAP_WAY"; + + /** + * 支付宝提现成功状态 + */ + public static String SUCCESS_CODE = "10000"; + +} diff --git a/src/main/java/com/sqx/modules/pay/config/WXConfig.java b/src/main/java/com/sqx/modules/pay/config/WXConfig.java new file mode 100644 index 0000000..1d4fd85 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/config/WXConfig.java @@ -0,0 +1,89 @@ +package com.sqx.modules.pay.config; + +import com.github.wxpay.sdk.WXPayConfig; +import lombok.Data; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +/** + * @author fang + * @date 2020/2/26 + */ +@Data +public class WXConfig implements WXPayConfig { + private byte[] certData; + + public String appId; + public String key; + public String mchId; + + /*public WXConfigUtil() throws Exception { + String certPath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/weixin/apiclient_cert.p12";//从微信商户平台下载的安全证书存放的路径 + File file = new File(certPath); + InputStream certStream = new FileInputStream(file); + this.certData = new byte[(int) file.length()]; + certStream.read(this.certData); + certStream.close(); + }*/ + + public byte[] getCertData() { + return certData; + } + + public void setCertData(byte[] certData) { + this.certData = certData; + } + + public String getAppId() { + return appId; + } + + public void setAppId(String appId) { + this.appId = appId; + } + + public void setKey(String key) { + this.key = key; + } + + public String getMchId() { + return mchId; + } + + public void setMchId(String mchId) { + this.mchId = mchId; + } + + @Override + public String getAppID() { + return this.appId; + } + + //parnerid,商户号 + @Override + public String getMchID() { + return this.mchId; + } + + @Override + public String getKey() { + return this.key; + } + + @Override + public InputStream getCertStream() { + ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData); + return certBis; + } + + @Override + public int getHttpConnectTimeoutMs() { + return 8000; + } + + @Override + public int getHttpReadTimeoutMs() { + return 10000; + } +} diff --git a/src/main/java/com/sqx/modules/pay/controller/CashController.java b/src/main/java/com/sqx/modules/pay/controller/CashController.java new file mode 100644 index 0000000..4db2839 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/controller/CashController.java @@ -0,0 +1,543 @@ +package com.sqx.modules.pay.controller; + + +import cn.hutool.core.bean.BeanUtil; +import com.alibaba.fastjson.JSON; +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.CertAlipayRequest; +import com.alipay.api.DefaultAlipayClient; +import com.alipay.api.request.AlipayFundTransToaccountTransferRequest; +import com.alipay.api.request.AlipayFundTransUniTransferRequest; +import com.alipay.api.response.AlipayFundTransToaccountTransferResponse; +import com.alipay.api.response.AlipayFundTransUniTransferResponse; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.pay.config.AliPayConstants; +import com.sqx.modules.pay.entity.AliPayWithdrawModel; +import com.sqx.modules.pay.entity.CashOut; +import com.sqx.modules.pay.service.CashOutService; +import com.sqx.modules.pay.service.PayDetailsService; +import com.sqx.modules.utils.AmountCalUtils; +import com.sqx.modules.utils.EasyPoi.ExcelUtils; +import com.sqx.modules.utils.wx.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import lombok.val; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * @author fang + * @date 2020/5/15 + */ +@Slf4j +@RestController +@Api(value = "管理平台", tags = {"管理平台"}) +@RequestMapping(value = "/cash") +public class CashController { + + /** + * 充值记录 + */ + @Autowired + private PayDetailsService payDetailsService; + /** + * 提现记录 + */ + @Autowired + private CashOutService cashOutService; + /** + * app用户 + */ + @Autowired + private UserService userService; + /** + * 通用配置 + */ + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private MessageService messageService; + @Autowired + private UserMoneyService userMoneyService; + private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true); + + @RequestMapping(value = "/sendMsgByUserId", method = RequestMethod.GET) + @ApiOperation("管理平台主动推送消息(指定用户)") + @ResponseBody + public Result sendMsgByUserId(String title, String content, Long userId) { + UserEntity user = userService.queryByUserId(userId); + send(user, title, content); + return Result.success(); + } + + + @RequestMapping(value = "/sendMsg", method = RequestMethod.GET) + @ApiOperation("管理平台主动推送消息") + @ResponseBody + public Result sendMsg(String title, String content, String phone, Integer flag) { + if (flag == 1) { + //根据手机号推送 + UserEntity userByPhone = userService.queryByPhone(phone); + if (null == userByPhone) { + return Result.error(-100, "手机号不存在!"); + } + send(userByPhone, title, content); + } else { + //所有人推送 + List userInfos = userService.list(); + //用户数量较大 使用多线程推送 根据用户数量进行拆分 同时按照3个线程进行推送 + int count = userInfos.size() / 3; + new Thread(() -> { + for (int i = 0; i < count; i++) { + send(userInfos.get(i), title, content); + } + }).start(); + new Thread(() -> { + for (int i = count; i < count * 2; i++) { + send(userInfos.get(i), title, content); + } + }).start(); + new Thread(() -> { + for (int i = count * 2; i < userInfos.size(); i++) { + send(userInfos.get(i), title, content); + } + }).start(); + /* for(UserInfo userByPhone:userInfos){ + + }*/ + } + return Result.success(); + } + + private void send(UserEntity userByPhone, String title, String content) { + if (userByPhone.getClientid() != null) { + userService.pushToSingle(title, content, userByPhone.getClientid()); + } + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent(content); + messageInfo.setTitle(title); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userByPhone.getUserName()); + messageInfo.setUserId(String.valueOf(userByPhone.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + } + + + @RequestMapping(value = "/selectCashOut", method = RequestMethod.GET) + @ApiOperation("获取最新的提现信息") + @ResponseBody + public Result selectCashOut() { + return Result.success().put("data", cashOutService.selectCashOutLimit3()); + } + + @RequestMapping(value = "/selectSumPay", method = RequestMethod.GET) + @ApiOperation("查询用户充值金额") + @ResponseBody + public Result selectSumPay(String createTime, String endTime, Long userId) { + return Result.success().put("data", payDetailsService.selectSumPay(createTime, endTime, userId)); + } + + @RequestMapping(value = "/selectUserRecharge", method = RequestMethod.GET) + @ApiOperation("查询所有用户充值信息列表") + @ResponseBody + public Result selectUserRecharge(int page, int limit, String startTime, String endTime, Integer state,Integer type) { + return Result.success().put("data", payDetailsService.selectPayDetails(page, limit, startTime, endTime, null, state,type)); + } + + @RequestMapping(value = "/selectUserRechargeByUserId", method = RequestMethod.GET) + @ApiOperation("查询某个用户充值信息列表") + @ResponseBody + public Result selectUserRechargeByUserId(int page, int limit, String startTime, String endTime, Long userId, Integer state) { + return Result.success().put("data", payDetailsService.selectPayDetails(page, limit, startTime, endTime, userId, state, null)); + } + + @RequestMapping(value = "/selectUserRechargeByUserIdApp", method = RequestMethod.GET) + @ApiOperation("查询某个用户充值信息列表") + @ResponseBody + public Result selectUserRechargeByUserIdApp(int page, int limit, String startTime, String endTime, Long userId) { + return Result.success().put("data", payDetailsService.selectPayDetails(page, limit, startTime, endTime, userId, 1, null)); + } + + @RequestMapping(value = "/selectAdminHelpProfit", method = RequestMethod.GET) + @ApiOperation("管理员查询提现记录列表") + @ResponseBody + public Result selectAdminHelpProfit(Integer page, Integer limit, String startTime, String endTime, CashOut cashOut) { + return Result.success().put("data", cashOutService.selectAdminHelpProfit(page, limit, startTime, endTime, cashOut)); + } + + + @ApiOperation("财务提现统计") + @GetMapping("/statisticsCashMoney") + public Result statisticsMoney(String time, Integer flag) { + return Result.success().put("data", cashOutService.statisticsMoney(time, flag)); + } + + + @ApiOperation("充值统计") + @GetMapping("/payMember") + public Result payMember(String time, Integer flag) { + return Result.success().put("data", cashOutService.payMember(time, flag)); + } + + @RequestMapping(value = "/selectPayDetails", method = RequestMethod.GET) + @ApiOperation("查询提现记录列表") + @ResponseBody + public Result selectHelpProfit(int page, int limit, Long userId) { + Map map = new HashMap<>(); + map.put("page", page); + map.put("limit", limit); + map.put("userId", userId); + PageUtils pageUtils = cashOutService.selectCashOutList(map); + return Result.success().put("data", pageUtils); + } + + @GetMapping("/exportExcel") + public void cashListExcel(CashOut cashOut, String startTime, String endTime, HttpServletResponse response) throws IOException { + List list = cashOutService.selectAdminHelpProfit(null, null, startTime, endTime, cashOut).getRecords(); + ExcelUtils.exportExcel(list, "提现统计表", "提现统计Sheet", CashOut.class, "提现统计表", response); + } +/* + @ApiOperation("收入统计") + @GetMapping("/statisticsIncomeMoney") + public Result statisticsIncomeMoney(String time, Integer flag){ + Double sumMoney = ordersService.statisticsIncomeMoney(time, flag, null); + Double courseMoney = ordersService.statisticsIncomeMoney(time, flag, 1); + Double vipMoney = ordersService.statisticsIncomeMoney(time, flag, 2); + Map map=new HashMap<>(); + map.put("sumMoney",sumMoney==null?0.00:sumMoney); + map.put("courseMoney",courseMoney==null?0.00:courseMoney); + map.put("vipMoney",vipMoney==null?0.00:vipMoney); + return Result.success().put("data",map); + } +*/ + + + @RequestMapping(value = "/alipay/{cashId}", method = RequestMethod.POST) + @ApiOperation("管理平台确认提现") + @ResponseBody + public Result alipayPay(@PathVariable Long cashId) { + reentrantReadWriteLock.writeLock().lock(); + try { + CashOut one = cashOutService.selectById(cashId); + if (one.getClassify() == null || one.getClassify() == 1) { + return cashAliPay(one); + } else { + return cashWxPay(one); + } + } catch (Exception e) { + e.printStackTrace(); + log.error("转账异常" + e.getMessage()); + } finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + + public Result cashAliPay(CashOut one) { + //提现订单 + log.error("进来了!!!"); + //订单记录不为空 + if (one == null) { + return Result.error("提现记录不存在!"); + } + //订单状态不是待转帐 + if (one.getState() != 0) { + return Result.error(9999, one.getZhifubaoName() + "转账失败!原因是用户已转账"); + } + //订单编号为空 + if (StringUtils.isEmpty(one.getOrderNumber())) { + one.setOrderNumber(String.valueOf(System.currentTimeMillis())); + } + //配置文件对象 + CommonInfo commonInfo = commonInfoService.findOne(98); + + CommonInfo name = commonInfoService.findOne(12); + if (commonInfo.getValue() != null && commonInfo.getValue().equals("1")) { + + try { + CertAlipayRequest certAlipayRequest = new CertAlipayRequest(); + certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do"); //gateway:支付宝网关(固定)https://openapi.alipay.com/gateway.do + certAlipayRequest.setAppId(commonInfoService.findOne(63).getValue()); //APPID 即创建应用后生成,详情见创建应用并获取 APPID + certAlipayRequest.setPrivateKey(commonInfoService.findOne(65).getValue()); //开发者应用私钥,由开发者自己生成 + certAlipayRequest.setFormat("json"); //参数返回格式,只支持 json 格式 + certAlipayRequest.setCharset(AliPayConstants.CHARSET); //请求和签名使用的字符编码格式,支持 GBK和 UTF-8 + certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE); //商户生成签名字符串所使用的签名算法类型,目前支持 RSA2 和 RSA,推荐商家使用 RSA2。 + CommonInfo url = commonInfoService.findOne(200); + certAlipayRequest.setCertPath(url.getValue() + "/appCertPublicKey.crt"); //应用公钥证书路径(app_cert_path 文件绝对路径) + certAlipayRequest.setAlipayPublicCertPath(url.getValue() + "/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径(alipay_cert_path 文件绝对路径) + certAlipayRequest.setRootCertPath(url.getValue() + "/alipayRootCert.crt"); //支付宝CA根证书文件路径(alipay_root_cert_path 文件绝对路径) + AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest); + AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest(); + request.setBizContent("{" + + "\"out_biz_no\":\"" + one.getOrderNumber() + "\"," + //订单编号 + "\"trans_amount\":" + new BigDecimal(one.getMoney()) + "," + //转账金额 + "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," + + "\"biz_scene\":\"DIRECT_TRANSFER\"," + + "\"order_title\":\"" + name.getValue() + "佣金结算" + "\"," + + "\"payee_info\":{" + + "\"identity\":\"" + one.getZhifubao() + "\"," + //支付宝账号 + "\"identity_type\":\"ALIPAY_LOGON_ID\"," + + "\"name\":\"" + one.getZhifubaoName() + "\"," + //支付宝名称 + "}," + + "\"remark\":\"" + name.getValue() + "佣金结算" + "\"" + + "}"); + AlipayFundTransUniTransferResponse response = null; + response = alipayClient.certificateExecute(request); + log.error("支付宝转账返回值:" + response.getBody()); + //如果转账成功 + if (AliPayConstants.SUCCESS_CODE.equalsIgnoreCase(response.getCode())) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //修改状态为转账成功 + one.setState(1); + //设置转账时间 + one.setOutAt(sdf.format(new Date())); + //更新转账订单 + cashOutService.update(one); + //查询用户 + UserEntity userInfo = userService.queryByUserId(one.getUserId()); + cashOutService.cashOutSuccess(userInfo, one.getOutAt(), one.getMoney(), one.getZhifubao(), commonInfoService.findOne(19).getValue()); + + return Result.success(one.getZhifubaoName() + "转账成功"); + } else { + return Result.error(9999, one.getZhifubaoName() + "转账失败!" + response.getSubMsg()); + } + } catch (AlipayApiException e) { + log.error("零钱提现异常原因:" + e.getMessage()); + e.printStackTrace(); + return Result.error(9999, one.getZhifubaoName() + "转账失败!" + e.getMessage()); + } + } else if (commonInfo.getValue() != null && commonInfo.getValue().equals("2")) { + AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.REQUEST_URL, + commonInfoService.findOne(63).getValue(), commonInfoService.findOne(65).getValue(), AliPayConstants.FORMAT, + AliPayConstants.CHARSET, commonInfoService.findOne(64).getValue(), AliPayConstants.SIGNTYPE); + val aliPayWithdrawModel = AliPayWithdrawModel.builder() + .out_biz_no(one.getOrderNumber()) + .amount(new BigDecimal(one.getMoney())) + .payee_account(one.getZhifubao()) + .payee_real_name(one.getZhifubaoName()) + .payee_type(AliPayConstants.PAY_TYPE) + .remark(name.getValue()) + .build(); + String json = JSON.toJSONString(aliPayWithdrawModel); + //实例化连接对象 + AlipayFundTransToaccountTransferRequest withdrawRequest = new AlipayFundTransToaccountTransferRequest(); + withdrawRequest.setBizContent(json); + try { + AlipayFundTransToaccountTransferResponse response = alipayClient.execute(withdrawRequest); + if (AliPayConstants.SUCCESS_CODE.equalsIgnoreCase(response.getCode())) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //修改状态为转账成功 + one.setState(1); + //设置转账时间 + one.setOutAt(sdf.format(new Date())); + //更新转账订单 + cashOutService.update(one); + //查询用户 + UserEntity userInfo = userService.queryByUserId(one.getUserId()); + cashOutService.cashOutSuccess(userInfo, one.getOutAt(), one.getMoney(), one.getZhifubao(), commonInfoService.findOne(19).getValue()); + return Result.success(one.getZhifubaoName() + "转账成功"); + } else { + return Result.error(9999, one.getZhifubaoName() + "转账失败!" + response.getSubMsg()); + } + } catch (AlipayApiException e) { + log.error("零钱提现异常原因:" + e.getMessage()); + e.printStackTrace(); + return Result.error(9999, one.getZhifubaoName() + "转账失败!" + e.getMessage()); + + } + } else { + //人工转账后改变状态的 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + one.setState(1); + one.setOutAt(sdf.format(now)); + cashOutService.update(one); + UserEntity userInfo = userService.queryByUserId(one.getUserId()); + cashOutService.cashOutSuccess(userInfo, one.getOutAt(), one.getMoney(), one.getZhifubao(), commonInfoService.findOne(19).getValue()); + return Result.success(one.getZhifubaoName() + "转账成功"); + } + } + + + private Result cashWxPay(CashOut one) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + UserEntity userEntity = userService.getById(one.getUserId()); + if (StringUtils.isEmpty(one.getOrderNumber())) { + one.setOrderNumber(String.valueOf(System.currentTimeMillis())); + } + String value = commonInfoService.findOne(244).getValue(); + if ("1".equals(value)) { + WxPay wxPay = new WxPay(); + CommonInfo mchId = commonInfoService.findOne(76); + CommonInfo key = commonInfoService.findOne(75); + //小程序或公众号appid + if (one.getClassify() == 2) { + CommonInfo mchAppId = commonInfoService.findOne(45); + wxPay.setMch_appid(mchAppId.getValue()); + wxPay.setOpenid(userEntity.getOpenId()); + } else if (one.getClassify() == 3) { + CommonInfo mchAppId = commonInfoService.findOne(5); + wxPay.setMch_appid(mchAppId.getValue()); + wxPay.setOpenid(userEntity.getWxOpenId()); + } +// else{ +// CommonInfo mchAppId = commonInfoService.findOne(74); +// wxPay.setMch_appid(mchAppId.getValue()); +// wxPay.setOpenid(userEntity.get()); +// } + //商户号id + wxPay.setMchid(mchId.getValue()); + //随机字符 + wxPay.setNonce_str(WxPayUtils.generateNonceStr()); + //商户订单号 需保持唯一 + wxPay.setPartner_trade_no(one.getOrderNumber()); + //用户openId + + //NO_CHECK:不校验真实姓名 + //FORCE_CHECK:强校验真实姓名 + wxPay.setCheck_name("NO_CHECK"); + //转账金额 微信为分 + double v = Double.parseDouble(one.getMoney()); + Double mul = AmountCalUtils.mul(v, 100); + Integer amount = mul.intValue(); + wxPay.setAmount(amount); + //备注 + CommonInfo one1 = commonInfoService.findOne(12); + wxPay.setDesc(one1.getValue() + "提现金额到账"); + wxPay.setSign(WxPayUtils.createSign(BeanUtil.beanToMap(wxPay), key.getValue())); + + + String xmlParam = XmlUtil.beanToXml(wxPay, WxPay.class); + WeChatPayRequest weChatPayRequest = new WeChatPayRequest(); + + String returnXml = null; + try { + CommonInfo zsUlr = commonInfoService.findOne(201); + returnXml = weChatPayRequest.request(zsUlr.getValue(), WxPayUtils.WX_COM_DO_TRANS_URL, xmlParam, true, mchId.getValue()); + WxResult wxResult = XmlUtil.xmlToBean(returnXml, WxResult.class); + if (wxResult.getReturn_code().equals("SUCCESS")) { + if (one.getOrderNumber().equals(wxResult.getPartner_trade_no())) { + //修改状态为转账成功 + one.setState(1); + //设置转账时间 + one.setOutAt(sdf.format(new Date())); + //更新转账订单 + cashOutService.update(one); + if (userEntity != null && userEntity.getOpenId() != null) { + //提现通知消息 + cashOutService.cashOutSuccess(userEntity, one.getOutAt(), one.getMoney(), one.getZhifubao(), commonInfoService.findOne(19).getValue()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent(one.getMoney() + "提现已到账"); + messageInfo.setTitle("提现到账"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + messageService.saveBody(messageInfo); + return Result.success(one.getZhifubaoName() + "转账成功"); + } else { + return Result.error("转账失败!原因:" + wxResult.getErr_code_des()); + } + } else { + return Result.error("转账失败!状态码:" + wxResult.getErr_code_des()); + } + } catch (Exception e) { + log.error("转账异常:" + e.getMessage(), e); + log.error("postWxTransfers 微信处理异常 ==>{}", ExceptionUtils.getStackTrace(e)); + } + } else { + Date now = new Date(); + one.setState(1); + one.setOutAt(sdf.format(now)); + cashOutService.update(one); + UserEntity userInfo = userService.queryByUserId(one.getUserId()); + cashOutService.cashOutSuccess(userInfo, one.getOutAt(), one.getMoney(), one.getZhifubao(), commonInfoService.findOne(19).getValue()); + return Result.success(one.getZhifubaoName() + "转账成功"); + } + return Result.error("转账失败!"); + } + + + @RequestMapping(value = "/refund/{cashId}/{content}", method = RequestMethod.POST) + @ApiOperation("管理平台退款") + @ResponseBody + public Result refund(@PathVariable("cashId") Long cashId, @PathVariable("content") String content) { + CashOut one = cashOutService.selectById(cashId); + if (one == null) { + return Result.error("提现信息不存在"); + } + //将状态为待提现的退款 + if (one.getState() != 0) { + return Result.error(-100, "状态错误,已经转账或退款!"); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + //修改提现订单状态 + one.setState(-1); + one.setRefund(content); + one.setOutAt(sdf.format(now)); + cashOutService.update(one); + Long userId = one.getUserId(); + UserEntity userInfo = userService.queryByUserId(userId); + if (userInfo != null) { + //将金额退还 + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(userInfo.getUserId()); + userMoneyDetails.setTitle("[退款提醒]退款:" + one.getRate()); + userMoneyDetails.setContent("退款原因:" + content); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(BigDecimal.valueOf(one.getRate())); + userMoneyDetails.setCreateTime(sdf.format(now)); + userMoneyDetailsService.save(userMoneyDetails); + userMoneyService.updateMoney(1, userId, BigDecimal.valueOf(one.getRate())); + + cashOutService.refundSuccess(userInfo, one.getOutAt(), one.getMoney(), commonInfoService.findOne(19).getValue(), content); + } + return Result.success(); + } + + @GetMapping(value = "/cashMoney") + @ApiOperation("发起提现") + public Result cashMoney(Long userId, Double money, Integer classify) { + return cashOutService.cashMoney(userId, money, classify); + } + + @GetMapping(value = "/getBucketBuyList") + @ApiOperation("获取用户压桶购买记录") + public Result getBucketBuyList(Integer page, Integer limit, Long userId, Integer type, String phone, String userName, String tradeNo) { + return Result.success().put("data", payDetailsService.getBucketBuyList(page, limit, userId, type, phone, userName, tradeNo)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/pay/controller/app/AliPayController.java b/src/main/java/com/sqx/modules/pay/controller/app/AliPayController.java new file mode 100644 index 0000000..d90897b --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/controller/app/AliPayController.java @@ -0,0 +1,851 @@ +package com.sqx.modules.pay.controller.app; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.CertAlipayRequest; +import com.alipay.api.DefaultAlipayClient; +import com.alipay.api.domain.AlipayTradeAppPayModel; +import com.alipay.api.domain.AlipayTradeRefundModel; +import com.alipay.api.internal.util.AlipaySignature; +import com.alipay.api.request.AlipayTradeAppPayRequest; +import com.alipay.api.request.AlipayTradeRefundRequest; +import com.alipay.api.request.AlipayTradeWapPayRequest; +import com.alipay.api.response.AlipayTradeAppPayResponse; +import com.alipay.api.response.AlipayTradeRefundResponse; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.dao.UserMoneyDao; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.coupon.entity.SelfCouponUser; +import com.sqx.modules.coupon.respository.SelfCouponUserJpaRepository; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.orders.dao.PayOrderDao; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.entity.PayOrder; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.pay.config.AliPayConstants; +import com.sqx.modules.pay.dao.PayDetailsDao; +import com.sqx.modules.pay.entity.PayDetails; +import com.sqx.modules.taking.dao.OrderTakingDao; +import com.sqx.modules.taking.entity.GoodsSku; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.GoodsSkuService; +import com.sqx.modules.taking.service.OrderTakingService; +import com.sqx.modules.task.dao.HelpOrderDao; +import com.sqx.modules.task.entity.HelpOrder; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.tickets.service.TicketsService; +import com.sqx.modules.utils.AmountCalUtils; +import com.sqx.modules.utils.SenInfoCheckUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import jodd.util.StringUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 支付宝支付处理--暂不做同步处理、回调方式使用异步 + */ +@Slf4j +@RestController +@Api(value = "支付宝支付", tags = {"支付宝支付"}) +@RequestMapping("/app/aliPay") +public class AliPayController { + + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private OrdersDao ordersDao; + @Autowired + private TbCouponService couponService; + @Autowired + private TbCouponUserService couponUserService; + @Autowired + private PayOrderDao payOrderDao; + @Autowired + private OrdersService ordersService; + @Autowired + private UserMoneyDao userMoneyDao; + @Autowired + private PayDetailsDao payDetailsDao; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private UserService userService; + @Autowired + private MessageService messageService; + @Autowired + private OrderTakingService orderTakingService; + @Autowired + private HelpOrderDao helpOrderDao; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private TicketsService ticketsService; + @Autowired + private SelfCouponUserJpaRepository selfCouponUserJpaRepository; + @Autowired + private LaundryRepository laundryRepository; + @Autowired + private GoodsSkuService goodsSkuService; + + + @RequestMapping(value = "/notifyApp", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public void notifyApp(HttpServletRequest request, HttpServletResponse response) { + //获取支付宝POST过来反馈信息 + Map params = new HashMap(); + Map requestParams = request.getParameterMap(); + for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) { + String name = (String) iter.next(); + String[] values = (String[]) requestParams.get(name); + String valueStr = ""; + for (int i = 0; i < values.length; i++) { + valueStr = (i == values.length - 1) ? valueStr + values[i] + : valueStr + values[i] + ","; + } + //乱码解决,这段代码在出现乱码时使用。 + //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); + params.put(name, valueStr); + } + try { + log.info("回调成功!!!"); + boolean flag = AlipaySignature.rsaCheckV1(params, commonInfoService.findOne(64).getValue(), AliPayConstants.CHARSET, "RSA2"); + log.info(flag + "回调验证信息"); + if (flag) { + String tradeStatus = params.get("trade_status"); + if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) { + + //支付宝返回的订单编号 + String outTradeNo = params.get("out_trade_no"); + log.error("支付宝订单号:" + outTradeNo); + //支付宝支付单号 + String tradeNo = params.get("trade_no"); + PayDetails payDetails = payDetailsDao.selectOne(new QueryWrapper().eq("order_id", outTradeNo)); + if (payDetails.getState() == 0) { + payDetails.setState(1); + payDetails.setPayTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); + payDetails.setTradeNo(tradeNo); + payDetailsDao.updateById(payDetails); + if (payDetails.getType() == 1) { + //设置查询条件 + QueryWrapper queryWrapper = new QueryWrapper<>(); + //根据订单编号去查询订单 + queryWrapper.eq("orders_no", outTradeNo); + //去订单表中查询到该订单 + PayOrder orders = payOrderDao.selectOne(queryWrapper); + + + //改变订单状态 + orders.setState(1); + orders.setPayWay(4); + //设置订单更新时间 + orders.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payOrderDao.updateById(orders); + //调用处理接口 + userMoneyDao.updateMayMoney(1, orders.getUserId(), orders.getMoney()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setTitle("支付宝充值"); + userMoneyDetails.setContent("支付宝充值:" + orders.getPayMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(orders.getMoney()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + } else if (payDetails.getType() == 2) { + Orders orders = ordersDao.selectOne(new QueryWrapper().eq("orders_no", payDetails.getOrderId())); + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + goodsSku.setStock(goodsSku.getStock() - orders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + UserEntity userEntity = userService.selectUserById(orders.getUserId()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(orders.getPayMoney()); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setContent("支付宝支付订单"); + userMoneyDetails.setTitle("下单成功,订单号:" + orders.getOrdersNo()); + userMoneyDetails.setType(2); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单下单成功:" + orders.getOrdersNo()); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + String userName = userEntity.getUserName(); + orders.setState("4"); + orders.setIsRemind(0); + orders.setPayWay(3); + + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + ordersDao.updateById(orders); + + + + } else if (payDetails.getType() == 3) { + HelpOrder helpOrder = JSONObject.parseObject(payDetails.getRemark(), HelpOrder.class); + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(new Date()); + helpOrder.setStatus(2); + helpOrder.setCreateTime(date); + helpOrder.setMoney(helpOrder.getCommission()); + CommonInfo one = commonInfoService.findOne(120); + String value = one.getValue(); + Double mul = AmountCalUtils.mul(helpOrder.getCommission().doubleValue(), Double.parseDouble(value)); + BigDecimal sub = AmountCalUtils.sub(helpOrder.getMoney(), BigDecimal.valueOf(mul)); + helpOrder.setCommission(sub); + helpOrder.setPayWay(3); + helpOrderDao.insert(helpOrder); + + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(helpOrder.getUserId()); + userMoneyDetails.setTitle("万能任务"); + userMoneyDetails.setContent("万能任务支付宝支付扣款:" + helpOrder.getMoney()); + userMoneyDetails.setType(2); + userMoneyDetails.setMoney(helpOrder.getMoney()); + userMoneyDetails.setCreateTime(date); + userMoneyDetailsService.save(userMoneyDetails); + if (userEntity.getClientid() != null) { + userService.pushToSingle("派发订单", "您的订单已经派发成功!", userEntity.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的订单已经派发成功!"); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageService.saveBody(messageInfo); + } else if (payDetails.getType() == 4) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + BigDecimal money = BigDecimal.valueOf(payDetails.getMoney()); + userMoneyDao.updateSafetyMoney(1, payDetails.getUserId(), money); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setClassify(4); + userMoneyDetails.setUserId(payDetails.getUserId()); + userMoneyDetails.setTitle("[保证金]缴纳保证金"); + userMoneyDetails.setContent("缴纳保证金,保证金增加:" + money); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(money); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(payDetails.getUserId()); + userMoneyService.updateSafetyMoneyWay(userMoney.getId(), 2, payDetails.getOrderId()); + UserEntity userEntity = userService.selectUserById(payDetails.getUserId()); + userEntity.setIsSafetyMoney(1); + userService.updateById(userEntity); + } else if (payDetails.getType() == 5) { + List ordersList = JSONObject.parseArray(payDetails.getRemark(), Orders.class); + for (Orders orders : ordersList) { + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + goodsSku.setStock(goodsSku.getStock() - orders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + UserEntity userEntity = userService.selectUserById(orders.getUserId()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(orders.getPayMoney()); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setContent("微信支付订单"); + userMoneyDetails.setTitle("下单成功,订单号:" + orders.getOrdersNo()); + userMoneyDetails.setType(2); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单下单成功:" + orders.getOrdersNo()); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + orders.setState("4"); + orders.setIsRemind(0); + orders.setPayWay(2); + + ordersDao.updateById(orders); + + + + } + //购买水票 + } else if (payDetails.getType() == 6) { + ticketsService.businessCallback(3, payDetails.getUserId(), BigDecimal.valueOf(payDetails.getMoney()), payDetails.getRelationId(), payDetails.getBuyNum(), payDetails.getTradeNo()); + //购买优惠券 + } else if (payDetails.getType() == 7) { + couponUserService.businessCallback(3, payDetails.getUserId(), payDetails.getRelationId(), payDetails.getBuyNum(), BigDecimal.valueOf(payDetails.getMoney())); + //购买桶 + } else if (payDetails.getType() == 8) { + userService.bucketCallback(payDetails.getUserId(), payDetails.getBuyNum(), BigDecimal.valueOf(payDetails.getMoney()), payDetails.getClassify()); + } + } + } + + } + } catch (AlipayApiException e) { + e.printStackTrace(); + log.info("回调验证失败!!!"); + } + } + + @Login + @ApiOperation("支付宝购物车订单") + @RequestMapping(value = "/payShoppingOrders/{type}", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result payShoppingOrders(@RequestBody List ordersList, @PathVariable Integer type) { + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + List ordersLists = new ArrayList<>(); + BigDecimal price = BigDecimal.ZERO; + for (Orders orders : ordersList) { + Laundry laundry = laundryRepository.findById(orders.getLaundryId()).orElse(null); + Orders oldOrders = ordersDao.selectById(orders.getOrdersId()); + if (laundry.getRate() != null && laundry.getRate().doubleValue() > 0) { + BigDecimal laundryMoney = oldOrders.getPayMoney().multiply(laundry.getRate()); + oldOrders.setLaundryMoney(laundryMoney); + } + oldOrders.setLaundryId(laundry.getLaundryId()); + oldOrders.setLaundryName(laundry.getLaundryName()); + + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + GoodsSku goodsSku = goodsSkuService.getById(oldOrders.getSkuId()); + if (goodsSku.getStock() < oldOrders.getOrderNumber()) { + return Result.error(orderTaking.getServiceName() + " 剩余库存不足!"); + } + if (orders.getCouponId() != null) { + TbCouponUser tbCouponUser = couponUserService.getById(orders.getCouponId()); + if (tbCouponUser == null) { + return Result.error("你未持有当前优惠券"); + } + if (tbCouponUser.getStatus() == 1) { + return Result.error("当前优惠券已使用"); + } + if (tbCouponUser.getStatus() == 2) { + return Result.error("当前优惠券已失效"); + } + //如果订单金额大于优惠券最小订单金额 + if (oldOrders.getPayMoney().compareTo(tbCouponUser.getMinMoney()) >= 0) { + //写入使用了优惠券之后的订单金额 + oldOrders.setPayMoney(oldOrders.getPayMoney().subtract(tbCouponUser.getMoney())); + tbCouponUser.setStatus(1); + tbCouponUser.setEmployTime(new Date()); + oldOrders.setCouponId(orders.getCouponId()); + couponUserService.updateById(tbCouponUser); + + } else { + return Result.error("订单金额不满足最低满减金额"); + } + } + + price = price.add(oldOrders.getPayMoney()); + oldOrders.setRemarks(orders.getRemarks()); + oldOrders.setStartTime(orders.getStartTime()); + oldOrders.setProvince(orders.getProvince()); + oldOrders.setCity(orders.getCity()); + oldOrders.setDistrict(orders.getDistrict()); + oldOrders.setDetailsAddress(orders.getDetailsAddress()); + oldOrders.setName(orders.getName()); + oldOrders.setPhone(orders.getPhone()); + oldOrders.setIsShopping(2); + ordersLists.add(oldOrders); + ordersDao.updateById(oldOrders); + } + Orders orders1 = ordersLists.get(0); + + PayDetails payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setUserId(orders1.getUserId()); + payDetails.setMoney(price.doubleValue()); + payDetails.setClassify(3); + payDetails.setType(5); + payDetails.setRemark(JSONObject.toJSONString(ordersLists)); + payDetailsDao.insert(payDetails); + + if (type == 1) { + return payApp(name, payDetails.getOrderId(), price.doubleValue()); + } + return payH5(name, payDetails.getOrderId(), price.doubleValue(), returnUrl); + } + + + @Login + @ApiOperation("支付宝支付充值订单") + @RequestMapping(value = "/payMoneyOrder", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result payMoneyOrder(Long orderId, Integer classify) { + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + PayOrder orders = payOrderDao.selectById(orderId); + PayDetails payDetails = payDetailsDao.selectByOrderId(orders.getOrdersNo()); + if (payDetails == null) { + payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setOrderId(orders.getOrdersNo()); + payDetails.setUserId(orders.getUserId()); + payDetails.setMoney(orders.getPayMoney().doubleValue()); + payDetails.setClassify(4); + payDetails.setType(1); + payDetailsDao.insert(payDetails); + } + if (classify == 1) { + return payApp(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue()); + } + return payH5(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue(), returnUrl); + } + + @Login + @ApiOperation("支付宝支付家政订单") + @RequestMapping(value = "/payOrder", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result payOrder(Long orderId, Integer classify) { + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + Orders orders = ordersDao.selectById(orderId); + if (orders == null) { + return Result.error("订单生成失败,请重新下单!"); + } + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + if (goodsSku.getStock() < orders.getOrderNumber()) { + return Result.error(orderTaking.getServiceName() + " 剩余库存不足!"); + } + PayDetails payDetails = payDetailsDao.selectByOrderId(orders.getOrdersNo()); + if (payDetails == null) { + payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setOrderId(orders.getOrdersNo()); + payDetails.setUserId(orders.getUserId()); + payDetails.setMoney(orders.getPayMoney().doubleValue()); + payDetails.setClassify(4); + payDetails.setType(2); + payDetailsDao.insert(payDetails); + } + if (classify == 1) { + return payApp(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue()); + } + return payH5(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue(), returnUrl); + } + + @Login + @ApiOperation("买桶") + @RequestMapping(value = "/buyBucket", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result buyBucket(Integer num, @RequestAttribute("userId") Long userId, Integer classify) { + CommonInfo bucket = commonInfoService.findOne(326); + BigDecimal money = new BigDecimal(num).multiply(new BigDecimal(bucket.getValue())); + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + PayDetails payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setBuyNum(num); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setUserId(userId); + payDetails.setMoney(money.doubleValue()); + payDetails.setClassify(4); + payDetails.setType(8); + payDetailsDao.insert(payDetails); + if (classify == 1) { + return payApp(name, payDetails.getOrderId(), payDetails.getMoney()); + } + return payH5(name, payDetails.getOrderId(), payDetails.getMoney(), returnUrl); + } + + + @Login + @ApiOperation("支付宝支付万能订单") + @RequestMapping(value = "/payHelpOrder", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result payHelpOrder(@RequestBody HelpOrder helpOrder, @RequestAttribute Long userId) { + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + Integer classify = helpOrder.getClassify(); + helpOrder.setUserId(userId); + if (helpOrder.getCommission().doubleValue() <= 0) { + return Result.error("金额必须大于0"); + } + helpOrder.setOrderNo(getGeneralOrder()); + PayDetails payDetails = payDetailsDao.selectByOrderId(helpOrder.getOrderNo()); + if (payDetails == null) { + payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setOrderId(helpOrder.getOrderNo()); + payDetails.setUserId(helpOrder.getUserId()); + payDetails.setMoney(helpOrder.getCommission().doubleValue()); + payDetails.setClassify(4); + payDetails.setType(3); + payDetails.setRemark(JSON.toJSONString(helpOrder)); + payDetailsDao.insert(payDetails); + } + if (classify == 1) { + return payApp(name, helpOrder.getOrderNo(), helpOrder.getCommission().doubleValue()); + } + return payH5(name, helpOrder.getOrderNo(), helpOrder.getCommission().doubleValue(), returnUrl); + } + + @Login + @ApiOperation("缴纳保证金") + @RequestMapping(value = "/paySafetyMoney", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result wxPaySafetyMoney(@RequestAttribute Long userId, Integer classify) { + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + UserEntity userEntity = userService.selectUserById(userId); + if (userEntity.getIsSafetyMoney() != null && userEntity.getIsSafetyMoney() == 1) { + return Result.error("当前账号已经缴纳过保证金了!"); + } + String value = commonInfoService.findOne(271).getValue(); + BigDecimal money = new BigDecimal(value); + String outTradeNo = getGeneralOrder(); + PayDetails payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setOrderId(outTradeNo); + payDetails.setUserId(userId); + payDetails.setMoney(money.doubleValue()); + payDetails.setClassify(4); + payDetails.setType(4); + payDetailsDao.insert(payDetails); + if (classify == 1) { + return payApp(name, outTradeNo, money.doubleValue()); + } + return payH5(name, outTradeNo, money.doubleValue(), returnUrl); + } + + @Login + @ApiOperation("支付宝购买水票") + @RequestMapping(value = "/payTicketOrder", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result payTicketOrder(@RequestAttribute("userId") Long userId, Long ticketsId, Integer buyNum, Integer payType) { + Tickets tickets = ticketsService.getById(ticketsId); + if (tickets == null) { + return Result.error("选择的水票不存在"); + } + if (tickets.getIsEnable() != 1) { + return Result.error("当前水票已暂停购买"); + } + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + PayDetails payDetails = new PayDetails(); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setState(0); + payDetails.setBuyNum(buyNum); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setUserId(userId); + payDetails.setMoney(tickets.getBuyMoney().multiply(new BigDecimal(buyNum)).doubleValue()); + payDetails.setClassify(4); + payDetails.setType(6); + payDetails.setRelationId(ticketsId); + payDetailsDao.insert(payDetails); + if (payType == 1) { + return payApp(name, payDetails.getOrderId(), payDetails.getMoney()); + } + return payH5(name, payDetails.getOrderId(), payDetails.getMoney(), returnUrl); + } + + + @Login + @ApiOperation("支付宝购买优惠券") + @RequestMapping(value = "/payCoupon", method = RequestMethod.POST) + @Transactional(rollbackFor = Exception.class) + public Result payCoupon(@RequestAttribute("userId") Long userId, Long couponId, Integer buyNum, Integer payType) { + TbCoupon tbCoupon = couponService.getById(couponId); + if (tbCoupon == null || tbCoupon.getIsEnable() == 0 || tbCoupon.getDeleteFlag() == 1) { + return Result.error("优惠券暂未出售或不存在"); + } + if (tbCoupon.getCouponType() != 2) { + return Result.error("当前优惠券不支持购买"); + } + //查看当前用户已购买或领取数量 + Integer num = couponUserService.count(new QueryWrapper().eq("user_id", userId).eq("coupon_id", couponId)); + if (tbCoupon.getMaxReceive() != 0) { + if ((tbCoupon.getMaxReceive() - num) <= buyNum) { + return Result.error("当前可购买或领取的数量已到达上限"); + } + } + BigDecimal totalPrice = tbCoupon.getBuyMoney().multiply(new BigDecimal(buyNum)); + PayDetails payDetails = new PayDetails(); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setState(0); + payDetails.setBuyNum(buyNum); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setUserId(userId); + payDetails.setMoney(totalPrice.doubleValue()); + payDetails.setClassify(4); + payDetails.setType(7); + payDetails.setRelationId(couponId); + payDetailsDao.insert(payDetails); + + //通知页面地址 + CommonInfo one = commonInfoService.findOne(19); + String returnUrl = one.getValue(); + CommonInfo one3 = commonInfoService.findOne(12); + String name = one3 == null ? "陪玩接单" : one3.getValue(); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + log.info("回调地址:" + url); + + if (payType == 1) { + return payApp(name, payDetails.getOrderId(), payDetails.getMoney()); + } + return payH5(name, payDetails.getOrderId(), payDetails.getMoney(), returnUrl); + } + + + public Result payApp(String name, String generalOrder, Double money) { + CommonInfo one = commonInfoService.findOne(19); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + String result = ""; + CommonInfo payWay = commonInfoService.findOne(258); + try { + if ("1".equals(payWay.getValue())) { + //构造client + CertAlipayRequest certAlipayRequest = new CertAlipayRequest(); + //设置网关地址 + certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do"); + //设置应用Id + certAlipayRequest.setAppId(commonInfoService.findOne(63).getValue()); + //设置应用私钥 + certAlipayRequest.setPrivateKey(commonInfoService.findOne(65).getValue()); + //设置请求格式,固定值json + certAlipayRequest.setFormat("json"); + //设置字符集 + certAlipayRequest.setCharset(AliPayConstants.CHARSET); + //设置签名类型 + certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE); + CommonInfo urls = commonInfoService.findOne(259); + certAlipayRequest.setCertPath(urls.getValue() + "/appCertPublicKey.crt"); //应用公钥证书路径(app_cert_path 文件绝对路径) + certAlipayRequest.setAlipayPublicCertPath(urls.getValue() + "/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径(alipay_cert_path 文件绝对路径) + certAlipayRequest.setRootCertPath(urls.getValue() + "/alipayRootCert.crt"); //支付宝CA根证书文件路径(alipay_root_cert_path 文件绝对路径) + //构造client + AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest); + + //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay + AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); + //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 + AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); + model.setBody(name); + model.setSubject(name); + model.setOutTradeNo(generalOrder); + model.setTimeoutExpress("30m"); + model.setTotalAmount(money + ""); + model.setProductCode("QUICK_MSECURITY_PAY"); + request.setBizModel(model); + request.setNotifyUrl(url); + //这里和普通的接口调用不同,使用的是sdkExecute + AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request); + if (response.isSuccess()) { + result = response.getBody(); + } else { + return Result.error("获取订单失败!"); + } + return Result.success().put("data", result); + } else { + //实例化客户端 + AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonInfoService.findOne(63).getValue(), commonInfoService.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonInfoService.findOne(64).getValue(), "RSA2"); + //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay + AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); + //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 + AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); + model.setBody(name); + model.setSubject(name); + model.setOutTradeNo(generalOrder); + model.setTimeoutExpress("30m"); + model.setTotalAmount(String.valueOf(money)); + model.setProductCode("QUICK_MSECURITY_PAY"); + request.setBizModel(model); + request.setNotifyUrl(url); + AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request); + if (response.isSuccess()) { + result = response.getBody(); + } else { + return Result.error("获取订单失败!"); + } + return Result.success().put("data", result); + } + } catch (AlipayApiException e) { + e.printStackTrace(); + } + return Result.error(-100, "获取订单失败!"); + } + + public Result payH5(String name, String generalOrder, Double money, String returnUrl) { + CommonInfo payWay = commonInfoService.findOne(258); + CommonInfo one = commonInfoService.findOne(19); + String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp"; + try { + if ("1".equals(payWay.getValue())) { + //构造client + CertAlipayRequest certAlipayRequest = new CertAlipayRequest(); + //设置网关地址 + certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do"); + //设置应用Id + certAlipayRequest.setAppId(commonInfoService.findOne(63).getValue()); + //设置应用私钥 + certAlipayRequest.setPrivateKey(commonInfoService.findOne(65).getValue()); + //设置请求格式,固定值json + certAlipayRequest.setFormat("json"); + //设置字符集 + certAlipayRequest.setCharset(AliPayConstants.CHARSET); + //设置签名类型 + certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE); + CommonInfo urls = commonInfoService.findOne(259); + certAlipayRequest.setCertPath(urls.getValue() + "/appCertPublicKey.crt"); //应用公钥证书路径(app_cert_path 文件绝对路径) + certAlipayRequest.setAlipayPublicCertPath(urls.getValue() + "/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径(alipay_cert_path 文件绝对路径) + certAlipayRequest.setRootCertPath(urls.getValue() + "/alipayRootCert.crt"); //支付宝CA根证书文件路径(alipay_root_cert_path 文件绝对路径) + //构造client + AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest); + AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); + JSONObject order = new JSONObject(); + order.put("out_trade_no", generalOrder); //订单号 + order.put("subject", name); //商品标题 + order.put("product_code", "QUICK_WAP_WAY"); + order.put("body", name);//商品名称 + order.put("total_amount", money + ""); //金额 + alipayRequest.setBizContent(order.toString()); + alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址 + alipayRequest.setReturnUrl(returnUrl); //线上通知页面地址 + String result = alipayClient.pageExecute(alipayRequest).getBody(); + return Result.success().put("data", result); + } else { + AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonInfoService.findOne(63).getValue(), commonInfoService.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonInfoService.findOne(64).getValue(), "RSA2"); + AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); + JSONObject order = new JSONObject(); + order.put("out_trade_no", generalOrder); //订单号 + order.put("subject", name); //商品标题 + order.put("product_code", "QUICK_WAP_WAY"); + order.put("body", name);//商品名称 + order.put("total_amount", money); //金额 + alipayRequest.setBizContent(order.toString()); + //在公共参数中设置回跳和通知地址 + alipayRequest.setNotifyUrl(url); + //通知页面地址 + alipayRequest.setReturnUrl(returnUrl); + String form = alipayClient.pageExecute(alipayRequest).getBody(); + return Result.success().put("data", form); + } + } catch (AlipayApiException e) { + log.error("CreatPayOrderForH5", e); + } + return Result.error("获取订单信息错误!"); + } + + + public String getGeneralOrder() { + Date date = new Date(); + String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000)); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + String format = sdf.format(date); + return format + newString; + } + + + /** + * 说明: 支付宝订单退款 + * + * @return 公共返回参数 code,msg, 响应参数实例: https://docs.open.alipay.com/api_1/alipay.trade.refund + */ + public String alipayRefund(String ordersNo) { + PayDetails payDetails = payDetailsDao.selectByOrderId(ordersNo); + AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonInfoService.findOne(63).getValue(), commonInfoService.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonInfoService.findOne(64).getValue(), "RSA2"); + AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest(); + AlipayTradeRefundModel model = new AlipayTradeRefundModel(); + model.setOutTradeNo(payDetails.getOrderId());//订单编号 + model.setTradeNo(payDetails.getTradeNo());//支付宝订单交易号 + model.setRefundAmount(payDetails.getMoney().toString());//退款金额 不得大于订单金额 + model.setRefundReason("服务退款");//退款说明 + model.setOutRequestNo(payDetails.getOrderId());//标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传。 + alipay_request.setBizModel(model); + try { + AlipayTradeRefundResponse alipay_response = alipayClient.execute(alipay_request); + String alipayRefundStr = alipay_response.getBody(); + log.info(alipayRefundStr); + return alipayRefundStr; + } catch (AlipayApiException e) { + e.printStackTrace(); + } + return null; + } + + +} diff --git a/src/main/java/com/sqx/modules/pay/controller/app/ApiWeiXinPayController.java b/src/main/java/com/sqx/modules/pay/controller/app/ApiWeiXinPayController.java new file mode 100644 index 0000000..f3f4b97 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/controller/app/ApiWeiXinPayController.java @@ -0,0 +1,257 @@ +package com.sqx.modules.pay.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.pay.dao.PayDetailsDao; +import com.sqx.modules.pay.entity.PayDetails; +import com.sqx.modules.pay.service.WxService; +import com.sqx.modules.task.entity.HelpOrder; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; + +/** + * @author fang + * @date 2020/2/26 + */ +@RestController +@Api(value = "微信支付", tags = {"微信支付"}) +@RequestMapping("/app/wxPay") +@Slf4j +public class ApiWeiXinPayController { + + @Autowired + private WxService wxService; + @Autowired + private PayDetailsDao payDetailsDao; + @Login + @ApiOperation("微信app支付充值订单") + @PostMapping("/payAppOrder") + public Result payAppOrder(Long id,HttpServletRequest request) throws Exception { + return wxService.payOrder(id,1,request); + } + + + @Login + @ApiOperation("微信jsapi支付充值订单") + @PostMapping("/wxPayJsApiOrder") + public Result wxPayJsApiOrder(Long orderId,HttpServletRequest request) throws Exception { + return wxService.payOrder(orderId,3,request); + } + + + @Login + @ApiOperation("微信公众号支付充值订单") + @PostMapping("/wxPayMpOrder") + public Result wxPayMpOrder(Long orderId,HttpServletRequest request) throws Exception { + return wxService.payOrder(orderId,2,request); + } + + @Login + @ApiOperation("微信h5支付充值订单") + @PostMapping("/wxPayH5Order") + public Result wxPayH5Order(Long orderId,HttpServletRequest request) throws Exception { + return wxService.payOrder(orderId,4,request); + } + + @Login + @ApiOperation("微信购买桶") + @PostMapping("/buyBucket") + public Result buyBucket(Integer num, @RequestAttribute("userId") Long userId, Integer classify,HttpServletRequest request) throws Exception { + return wxService.buyBucket(num,userId,classify,request); + } + + @Login + @ApiOperation("支付家政订单") + @PostMapping("/wxPayOrder") + public Result wxPayOrder(Long orderId,Integer classify,HttpServletRequest request) throws Exception { + return wxService.wxPayOrder(orderId,classify,request); + } + + @Login + @ApiOperation("微信支付订单") + @PostMapping("/wxPayShoppingOrders/{type}") + public Result wxPayShoppingOrders(@RequestBody List ordersList, @PathVariable Integer type,HttpServletRequest request) throws Exception { + return wxService.wxPayShoppingOrders(ordersList,type,request); + } + + @Login + @ApiOperation("微信支付缴纳保证金") + @PostMapping("/paySafetyMoney") + public Result wxPaySafetyMoney(@RequestAttribute Long userId,Integer classify,HttpServletRequest request) throws Exception { + return wxService.wxPaySafetyMoney(userId,classify,request); + } + @Login + @ApiOperation("微信购买水票") + @PostMapping("/wxTicketOrder") + public Result wxTicketOrder(@RequestAttribute("userId") Long userId, Long ticketsId, Integer buyNum, Integer payType,HttpServletRequest request) throws Exception { + return wxService.wxTicketOrder(userId,ticketsId,buyNum,payType,request); + } + + @Login + @ApiOperation("微信购买优惠券") + @PostMapping("/payCoupon") + public Result payCoupon(@RequestAttribute("userId") Long userId, Long couponId, Integer buyNum, Integer payType,HttpServletRequest request) throws Exception { + return wxService.payCoupon(userId,couponId,buyNum,payType,request); + } + + @PostMapping("/notify") + @ApiOperation("微信回调") + public String wxPayNotify(HttpServletRequest request) { + String resXml = ""; + try { + InputStream inputStream = request.getInputStream(); + //将InputStream转换成xmlString + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder sb = new StringBuilder(); + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); + } + } catch (IOException e) { + log.info(e.getMessage()); + } finally { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + resXml = sb.toString(); + String result = wxService.payBack(resXml,1); + log.info("成功"); + log.info(result); + + return result; + } catch (Exception e) { + log.info("微信手机支付失败:" + e.getMessage()); + String result = "" + "" + "" + " "; + log.info("失败"); + log.info(result); + return result; + } + } + + @PostMapping("/notifyJsApi") + @ApiOperation("微信回调") + public String notifyJsApi(HttpServletRequest request) { + String resXml = ""; + try { + InputStream inputStream = request.getInputStream(); + //将InputStream转换成xmlString + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder sb = new StringBuilder(); + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); + } + } catch (IOException e) { + log.info(e.getMessage()); + } finally { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + resXml = sb.toString(); + String result = wxService.payBack(resXml,3); + log.info("成功"); + log.info(result); + return result; + } catch (Exception e) { + log.info("微信手机支付失败:" + e.getMessage(),e); + String result = "" + "" + "" + " "; + log.info("失败"); + log.info(result); + return result; + } + } + + @PostMapping("/notifyJsApiShop") + @ApiOperation("微信回调") + public String notifyJsApiShop(HttpServletRequest request) { + String resXml = ""; + try { + InputStream inputStream = request.getInputStream(); + //将InputStream转换成xmlString + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder sb = new StringBuilder(); + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); + } + } catch (IOException e) { + log.info(e.getMessage()); + } finally { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + resXml = sb.toString(); + String result = wxService.payBack(resXml,4); + log.info("成功"); + log.info(result); + return result; + } catch (Exception e) { + log.info("微信手机支付失败:" + e.getMessage(),e); + String result = "" + "" + "" + " "; + log.info("失败"); + log.info(result); + return result; + } + } + + @PostMapping("/notifyMp") + @ApiOperation("微信回调") + public String notifyMp(HttpServletRequest request) { + String resXml = ""; + try { + InputStream inputStream = request.getInputStream(); + //将InputStream转换成xmlString + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder sb = new StringBuilder(); + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); + } + } catch (IOException e) { + log.info(e.getMessage()); + } finally { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + resXml = sb.toString(); + String result = wxService.payBack(resXml,2); + log.info("成功"); + log.info(result); + return result; + } catch (Exception e) { + log.info("微信手机支付失败:" + e.getMessage(),e); + String result = "" + "" + "" + " "; + log.info("失败"); + log.info(result); + return result; + } + } + +} diff --git a/src/main/java/com/sqx/modules/pay/controller/app/AppCashController.java b/src/main/java/com/sqx/modules/pay/controller/app/AppCashController.java new file mode 100644 index 0000000..f0ff3cd --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/controller/app/AppCashController.java @@ -0,0 +1,82 @@ +package com.sqx.modules.pay.controller.app; + + +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.pay.service.CashOutService; +import com.sqx.modules.pay.service.PayDetailsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author fang + * @date 2020/5/15 + */ +@Slf4j +@RestController +@Api(value = "提现", tags = {"提现"}) +@RequestMapping(value = "/app/cash") +public class AppCashController { + + /** + * 提现记录 + */ + @Autowired + private CashOutService cashOutService; + @Autowired + private PayDetailsService payDetailsService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + + + @Login + @GetMapping(value = "/cashMoney") + @ApiOperation("发起提现") + public Result cashMoney(@RequestAttribute("userId") Long userId, Double money, Integer classify) { + return cashOutService.cashMoney(userId, money, classify); + } + + @Login + @RequestMapping(value = "/selectUserRechargeByUserId", method = RequestMethod.GET) + @ApiOperation("查询某个用户充值信息列表") + @ResponseBody + public Result selectUserRechargeByUserId(int page, int limit, String startTime, String endTime, @RequestAttribute("userId") Long userId, Integer state) { + return Result.success().put("data", payDetailsService.selectPayDetails(page, limit, startTime, endTime, userId, state, null)); + } + + @Login + @RequestMapping(value = "/selectPayDetails", method = RequestMethod.GET) + @ApiOperation("查询提现记录列表") + @ResponseBody + public Result selectHelpProfit(int page, int limit, @RequestAttribute("userId") Long userId) { + Map map = new HashMap<>(); + map.put("page", page); + map.put("limit", limit); + map.put("userId", userId); + PageUtils pageUtils = cashOutService.selectCashOutList(map); + return Result.success().put("data", pageUtils); + } + + @Login + @ApiOperation("钱包明细") + @GetMapping("/queryUserMoneyDetails") + public Result queryUserMoneyDetails(Integer page, Integer limit, @RequestAttribute("userId") Long userId, Integer classify, Integer type, String phone, String ordersNo, String userName) { + return userMoneyDetailsService.queryUserMoneyDetails(page, limit, userId, classify, type, phone, ordersNo, userName); + } + + @Login + @GetMapping(value = "/getBucketBuyList") + @ApiOperation("获取用户压桶购买记录") + public Result getBucketBuyList(Integer page, Integer limit, @RequestAttribute("userId") Long userId, Integer type, String phone, String userName, String tradeNo) { + return Result.success().put("data", payDetailsService.getBucketBuyList(page, limit, userId, type, phone, userName, tradeNo)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/pay/dao/CashOutDao.java b/src/main/java/com/sqx/modules/pay/dao/CashOutDao.java new file mode 100644 index 0000000..98563a6 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/dao/CashOutDao.java @@ -0,0 +1,45 @@ +package com.sqx.modules.pay.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.pay.entity.CashOut; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; + +/** + * @author fang + * @date 2020/7/8 + */ +@Mapper +public interface CashOutDao extends BaseMapper { + + List selectCashOutLimit3(); + + Double selectCashOutSum(@Param("userId") Long userId, @Param("startTime") Date startTime, @Param("endTime") Date endTime); + + Double sumMoney(@Param("time") String time, @Param("flag") Integer flag); + + Integer countMoney(@Param("time") String time, @Param("flag") Integer flag); + + Integer stayMoney(@Param("time") String time, @Param("flag") Integer flag); + + void updateMayMoney(@Param("type") Integer type,@Param("userId")Long userId,@Param("money") Double money); + + Double selectMayMoney(@Param("userId") Long userId); + + BigDecimal sumMoneyByUserId(@Param("userId") Long userId, @Param("time") String time, @Param("flag") Integer flag); + + BigDecimal getRechargeWay(String time, Integer flag, Integer classify); + + BigDecimal sumCashMoney(String time, Integer flag, Integer state,Integer classify); + + BigDecimal sumCashMoneyCount(String time, Integer flag, Integer state,Integer classify); + + IPage selectAdminHelpProfit(@Param("pages") Page pages, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("cashOut") CashOut cashOut); + +} diff --git a/src/main/java/com/sqx/modules/pay/dao/PayDetailsDao.java b/src/main/java/com/sqx/modules/pay/dao/PayDetailsDao.java new file mode 100644 index 0000000..7803ae0 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/dao/PayDetailsDao.java @@ -0,0 +1,50 @@ +package com.sqx.modules.pay.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.pay.entity.PayDetails; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * @author fang + * @date 2020/7/1 + */ +@Mapper +public interface PayDetailsDao extends BaseMapper { + + PayDetails selectById(@Param("id") Long id); + + PayDetails selectByRemark(@Param("remark") String remark); + + PayDetails selectByOrderId(@Param("orderId") String orderId); + + int updateState(@Param("id") Long id, @Param("state") Integer state, @Param("time") String time, @Param("tradeNo") String tradeNo); + + IPage> selectPayDetails(Page> page, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("userId") Long userId, @Param("state") Integer state, Integer type); + + Double selectSumPay(@Param("createTime") String createTime, @Param("endTime") String endTime, @Param("userId") Long userId); + + Double selectSumMember(@Param("time") String time, @Param("flag") Integer flag); + + IPage> payMemberAnalysis(Page> page, @Param("time") String time, @Param("flag") Integer flag); + + Double selectSumPayByState(@Param("time") String time, @Param("flag") Integer flag, @Param("state") Integer state); + + Double selectSumPayByClassify(@Param("time") String time, @Param("flag") Integer flag, @Param("classify") Integer classify,@Param("payClassify") Integer payClassify); + + IPage> selectUserMemberList(Page> page, @Param("phone") String phone); + + int selectPayCount(Long userId); + + Double instantselectSumPay(@Param("date") String date, @Param("userId") Long userId); + + + IPage getBucketBuyList(Page pages, Long userId, Integer type, String phone, String userName, String tradeNo); + + BigDecimal sumTypeMoney(String time, Integer flag, Integer type); +} diff --git a/src/main/java/com/sqx/modules/pay/entity/AliPayParamModel.java b/src/main/java/com/sqx/modules/pay/entity/AliPayParamModel.java new file mode 100644 index 0000000..bd8efae --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/entity/AliPayParamModel.java @@ -0,0 +1,33 @@ +package com.sqx.modules.pay.entity; + +import lombok.Data; + +/** + * @author WALKMAN + * @Description 支付宝订单参数 + **/ +@Data +public class AliPayParamModel { + + /** + * 系统交易订单号 + */ + private String out_trade_no; + + /** + * 订单金额 + */ + private String total_amount; + + /** + * 标题 + */ + private String subject; + + /** + * 商品标签-固定值 + */ + private String product_code; + + +} diff --git a/src/main/java/com/sqx/modules/pay/entity/AliPayWithdrawModel.java b/src/main/java/com/sqx/modules/pay/entity/AliPayWithdrawModel.java new file mode 100644 index 0000000..4a91221 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/entity/AliPayWithdrawModel.java @@ -0,0 +1,51 @@ +package com.sqx.modules.pay.entity; + +import lombok.Builder; +import lombok.Data; + +import java.math.BigDecimal; + +/** + * @author WALKMAN + * @Description:支付宝提现表单 + **/ +@Data +@Builder +public class AliPayWithdrawModel { + + /** + * 平台交易订单号 + */ + private String out_biz_no; + + /** + * 交易方式 + */ + private String payee_type = "ALIPAY_LOGONID"; + + /** + * 提现金额 + */ + private BigDecimal amount; + + /** + * 提现账户 + */ + private String payee_account; + + /** + * 支付宝账户昵称 + */ + private String payer_show_name; + + /** + * 支付宝真实名称 + */ + private String payee_real_name; + + /** + * 交易备注 + */ + private String remark; + +} diff --git a/src/main/java/com/sqx/modules/pay/entity/CashOut.java b/src/main/java/com/sqx/modules/pay/entity/CashOut.java new file mode 100644 index 0000000..0ebabe2 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/entity/CashOut.java @@ -0,0 +1,125 @@ +package com.sqx.modules.pay.entity; + +import cn.afterturn.easypoi.excel.annotation.Excel; +import cn.afterturn.easypoi.excel.annotation.ExcelIgnore; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * 提现申请 + * @author fang + * @date 2020/7/8 + */ +@Data +@TableName("cash_out") +public class CashOut implements Serializable { + + private static final long serialVersionUID = 1L; + + + /** + * 申请提现id + */ + @Excel(name = "编号") + @TableId(type = IdType.INPUT) + private Long id; + + /** + * 申请时间 + */ + @Excel(name = "申请时间",width = 35) + private String createAt; + + /** + * 转账时间 + */ + @Excel(name = "转账/拒绝时间",width = 35) + private String outAt; + + /** + * 提现金额 + */ + @Excel(name = "提现金额") + private String money; + + /** + * 是否转账 + */ + //表示不导出当前字段 + @ExcelIgnore + @Excel(name = "是否转账") + private Boolean isOut; + + /** + * 会员编号 + */ + //表示不导出当前字段 + @ExcelIgnore + @Excel(name = "会员编号") + private String relationId; + + /** + * 用户id + */ + @ExcelIgnore + @Excel(name = "用户id") + private Long userId; + + /** + * 支付宝账号 + */ + @Excel(name = "支付宝账号", width = 15) + private String zhifubao; + + /** + * 支付宝姓名 + */ + @Excel(name = "支付宝姓名", width = 15) + private String zhifubaoName; + + /** + * 订单编号 + */ + @Excel(name = "转账订单号",width = 30) + private String orderNumber; + + /** + * 状态 0待转账 1成功 -1退款 + */ + @Excel(name = "状态", replace = {"待转账_0", "已转账_1", "已拒绝_-1"}) + private Integer state; + + /** + * 原因 + */ + @Excel(name = "拒绝原因") + private String refund; + + /** + * 手续费 + */ + @ExcelIgnore + @Excel(name = "手续费") + private Double rate; + + /** + * 提现方式 1支付宝 2微信小程序 3微信公众号 + */ + @Excel(name = "提现方式", replace = {"_null", "支付宝_1", "微信小程序_2", "微信公众号_3"}) + private Integer classify; + /** + * 微信手动图片 + */ + //表示不导出当前字段 + @Excel(name = "收款二维码") + private String wxImg; + @TableField(exist = false) + @Excel(name = "提现用户手机号", width = 30) + private String phone; + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/pay/entity/PayDetails.java b/src/main/java/com/sqx/modules/pay/entity/PayDetails.java new file mode 100644 index 0000000..8071fb0 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/entity/PayDetails.java @@ -0,0 +1,93 @@ +package com.sqx.modules.pay.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * 充值记录 + * + * @author fang 2020-05-14 + */ +@Data +@TableName("pay_details") +public class PayDetails implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 充值记录id + */ + @TableId(type = IdType.INPUT) + private Long id; + + /** + * 分类(1微信 1app微信 2微信公众号 3微信小程序 4支付宝) + */ + private Integer classify; + + /** + * 订单id + */ + private String orderId; + + /** + * 支付宝交易订单号 + */ + private String tradeNo; + + /** + * 充值金额 + */ + private Double money; + + /** + * 用户id + */ + private Long userId; + + /** + * 0待支付 1支付成功 2失败 + */ + private Integer state; + + /** + * 创建时间 + */ + private String createTime; + + /** + * 支付时间 + */ + private String payTime; + + /** + * 支付类型 1 订单 2会员 + */ + private Integer type; + /** + * 购买数量 + */ + private Integer buyNum; + /** + * 关联id + */ + private Long relationId; + + private String remark; + @TableField(exist = false) + private String userName; + @TableField(exist = false) + private String phone; + + @TableField(exist = false) + private String refundContent; + + @TableField(exist = false) + private String outRequestNo; + +} diff --git a/src/main/java/com/sqx/modules/pay/service/CashOutService.java b/src/main/java/com/sqx/modules/pay/service/CashOutService.java new file mode 100644 index 0000000..aadbb84 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/service/CashOutService.java @@ -0,0 +1,49 @@ +package com.sqx.modules.pay.service; + + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.pay.entity.CashOut; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public interface CashOutService extends IService { + + PageUtils selectCashOutList(Map params); + + int saveBody(CashOut cashOut); + + int update(CashOut cashOut); + + CashOut selectById(Long id); + + void cashOutSuccess(UserEntity userByWxId, String date, String money, String payWay, String url); + + List selectCashOutLimit3(); + + void refundSuccess(UserEntity userByWxId, String date, String money, String url, String content); + + Double selectCashOutSum(Long userId, Date startTime, Date endTime); + + Double sumMoney(String time, Integer flag); + + Integer countMoney(String time, Integer flag); + + Integer stayMoney(String time, Integer flag); + + void updateMayMoney(int i, Long userId, Double money); + + Result cashMoney(Long userId, Double money,Integer classify); + + HashMap payMember(String time, Integer flag); + + HashMap statisticsMoney(String time, Integer flag); + + IPage selectAdminHelpProfit(Integer page, Integer limit, String startTime, String endTime, CashOut cashOut); +} diff --git a/src/main/java/com/sqx/modules/pay/service/PayDetailsService.java b/src/main/java/com/sqx/modules/pay/service/PayDetailsService.java new file mode 100644 index 0000000..c174905 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/service/PayDetailsService.java @@ -0,0 +1,30 @@ +package com.sqx.modules.pay.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.pay.entity.PayDetails; + +import java.math.BigDecimal; + +public interface PayDetailsService { + + PageUtils selectPayDetails(int page, int limit, String startTime, String endTime, Long userId, Integer state, Integer type); + + Double selectSumPay(String createTime, String endTime, Long userId); + + PageUtils payMemberAnalysis(int page, int limit, String time, Integer flag); + + PageUtils selectUserMemberList(int page, int limit, String phone); + + Double selectSumMember(String time, Integer flag); + + Double selectSumPayByState(String time, Integer flag, Integer state); + + Double selectSumPayByClassify(String time, Integer flag, Integer classify,Integer payClassify); + + Double instantselectSumPay(String date, Long userId); + + IPage getBucketBuyList(Integer page, Integer limit, Long userId, Integer type, String phone, String userName, String tradeNo); + + BigDecimal sumTypeMoney(String time, Integer flag, Integer type); +} diff --git a/src/main/java/com/sqx/modules/pay/service/WxService.java b/src/main/java/com/sqx/modules/pay/service/WxService.java new file mode 100644 index 0000000..e955748 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/service/WxService.java @@ -0,0 +1,36 @@ +package com.sqx.modules.pay.service; + +import com.sqx.common.utils.Result; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.task.entity.HelpOrder; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + + +/** + * @author fang + * @date 2020/2/26 + */ +public interface WxService { + + Result payOrder(Long id, Integer classify, HttpServletRequest request) throws Exception; + + Result wxPayOrder(Long id, Integer classify,HttpServletRequest request) throws Exception; + + Result wxPayHelpOrder(HelpOrder helpOrder, Integer classify,HttpServletRequest request) throws Exception; + + Result wxPaySafetyMoney(Long userId, Integer type,HttpServletRequest request) throws Exception; + + Result wxPayShoppingOrders(List ordersList, Integer type, HttpServletRequest request) throws Exception; + + String payBack(String resXml,Integer type); + + boolean refund(String ordersNo); + + Result wxTicketOrder(Long userId, Long ticketsId, Integer buyNum, Integer payType,HttpServletRequest request) throws Exception; + + Result payCoupon(Long userId, Long couponId, Integer buyNum, Integer payType, HttpServletRequest request) throws Exception; + + Result buyBucket(Integer num, Long userId, Integer classify,HttpServletRequest request) throws Exception; +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/pay/service/impl/CashOutServiceImpl.java b/src/main/java/com/sqx/modules/pay/service/impl/CashOutServiceImpl.java new file mode 100644 index 0000000..498b35e --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/service/impl/CashOutServiceImpl.java @@ -0,0 +1,496 @@ +package com.sqx.modules.pay.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.invite.dao.InviteMoneyDao; +import com.sqx.modules.invite.entity.Invite; +import com.sqx.modules.invite.entity.InviteMoney; +import com.sqx.modules.message.dao.MessageInfoDao; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.pay.dao.CashOutDao; +import com.sqx.modules.pay.entity.CashOut; +import com.sqx.modules.pay.service.CashOutService; +import com.sqx.modules.pay.service.PayDetailsService; +import com.sqx.modules.utils.AmountCalUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import weixin.popular.api.MessageAPI; +import weixin.popular.bean.message.templatemessage.TemplateMessage; +import weixin.popular.bean.message.templatemessage.TemplateMessageItem; +import weixin.popular.bean.message.templatemessage.TemplateMessageResult; +import weixin.popular.support.TokenManager; + +import javax.websocket.SendResult; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 提现申请记录 + */ +@Service +public class CashOutServiceImpl extends ServiceImpl implements CashOutService { + + /** + * 提现申请记录 + */ + @Autowired + private CashOutDao cashOutDao; + /** + * 通用配置 + */ + @Autowired + private CommonInfoService commonInfoService; + /** + * app用户 + */ + @Autowired + private UserService userService; + @Autowired + private MessageInfoDao messageInfoDao; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private PayDetailsService payDetailsService; + + @Override + public PageUtils selectCashOutList(Map params) { + String zhifubaoName = (String) params.get("zhifubaoName"); + String zhifubao = (String) params.get("zhifubao"); + String userId = String.valueOf(params.get("userId")); + String classify = String.valueOf(params.get("classify")); + String state = String.valueOf(params.get("state")); + IPage page = this.page( + new Query().getPage(params), + new QueryWrapper() + .eq(StringUtils.isNotBlank(zhifubaoName), "zhifubao_name", zhifubaoName) + .eq(StringUtils.isNotBlank(zhifubao), "zhifubao", zhifubao) + .eq(StringUtils.isNotBlank(userId) && !"null".equals(userId), "user_id", userId) + .eq(StringUtils.isNotBlank(classify) && !"null".equals(classify) && "1".equals(classify), "classify", classify) + .eq(StringUtils.isNotBlank(state) && !"null".equals(state), "state", state) + .and(StringUtils.isNotBlank(classify) && !"null".equals(classify) && "2".equals(classify), wrapper -> wrapper.eq("classify", 2).or().eq("classify", 3)) + .orderByDesc("id") + ); + return new PageUtils(page); + } + + + @Override + public CashOut selectById(Long id) { + return cashOutDao.selectById(id); + } + + @Override + public int saveBody(CashOut cashOut) { + return cashOutDao.insert(cashOut); + } + + + @Override + public int update(CashOut cashOut) { + return cashOutDao.updateById(cashOut); + } + + + @Override + public void cashOutSuccess(UserEntity userByWxId, String date, String money, String payWay, String url) { + if (userByWxId != null) { + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setState(String.valueOf(5)); + messageInfo.setContent("您好,您的提现转账成功,请注意查收!提现金额【" + money + "元】!支付宝收款账号 " + payWay + "感谢您的使用!如有疑问请在公众号中发送您的问题联系客服"); + messageInfo.setTitle("提现成功通知"); + messageInfo.setUserName(userByWxId.getUserName()); + messageInfo.setUserId(String.valueOf(userByWxId.getUserId())); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + messageInfo.setCreateAt(sdf.format(now)); + messageInfo.setIsSee("0"); + messageInfoDao.insert(messageInfo); + if (userByWxId.getClientid() != null) { + userService.pushToSingle("提现成功通知", "您好,您的提现转账成功,请注意查收!提现金额【" + money + "元】!支付宝收款账号 " + payWay + "感谢您的使用!如有疑问请在公众号中发送您的问题联系客服", userByWxId.getClientid()); + } + CommonInfo three = commonInfoService.findOne(39); + String apkey = ""; + if (three != null) { + apkey = three.getValue(); + } + if (StringUtils.isNotBlank(userByWxId.getOpenId())) { + LinkedHashMap data = new LinkedHashMap<>(); + data.put("first", new TemplateMessageItem("您好,您的提现转账成功,请注意查收", "#d71345")); + data.put("keyword1", new TemplateMessageItem(money + " 元", "#d71345")); + data.put("keyword2", new TemplateMessageItem(date, "#d71345")); + data.put("remark", new TemplateMessageItem("支付宝收款账号 " + payWay + "感谢您的使用!如有疑问请在公众号中发送您的问题联系客服", null)); + sendWxMessage(apkey, data, userByWxId.getOpenId(), url); + } + } + + } + + /** + * 退款成功通知 + * + * @param + * @param date + * @param money + * @param url + */ + @Override + public void refundSuccess(UserEntity userByWxId, String date, String money, String url, String content) { + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setState(String.valueOf(5)); + messageInfo.setContent(content); + messageInfo.setTitle("提现失败提醒"); + messageInfo.setUserName(userByWxId.getUserName()); + messageInfo.setUserId(String.valueOf(userByWxId.getUserId())); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + messageInfo.setCreateAt(sdf.format(now)); + messageInfo.setIsSee("0"); + messageInfoDao.insert(messageInfo); + if (userByWxId.getClientid() != null) { + userService.pushToSingle("提现失败提醒", content, userByWxId.getClientid()); + } + CommonInfo three = commonInfoService.findOne(77); + String apkey = ""; + if (three != null) { + apkey = three.getValue(); + } + if (StringUtils.isNotBlank(userByWxId.getOpenId())) { + LinkedHashMap data = new LinkedHashMap<>(); + data.put("first", new TemplateMessageItem("您好,您发起的提现失败了", "#d71345")); + data.put("keyword1", new TemplateMessageItem(money + " 元", "#d71345")); + data.put("keyword2", new TemplateMessageItem(date, "#d71345")); + data.put("keyword3", new TemplateMessageItem(content, "#d71345")); + data.put("remark", new TemplateMessageItem("请您按照失败原因修改相关信息后,重新提现!", null)); + sendWxMessage(apkey, data, userByWxId.getOpenId(), url); + } + + } + + @Override + public Double selectCashOutSum(Long userId, Date startTime, Date endTime) { + return cashOutDao.selectCashOutSum(userId, startTime, endTime); + } + + @Override + public Double sumMoney(String time, Integer flag) { + return cashOutDao.sumMoney(time, flag); + } + + @Override + public Integer countMoney(String time, Integer flag) { + return cashOutDao.countMoney(time, flag); + } + + @Override + public Integer stayMoney(String time, Integer flag) { + return cashOutDao.stayMoney(time, flag); + } + + @Override + public void updateMayMoney(int i, Long userId, Double money) { + cashOutDao.updateMayMoney(i, userId, money); + } + + + @Override + public List selectCashOutLimit3() { + return cashOutDao.selectCashOutLimit3(); + } + + private void sendWxMessage(String templateId, LinkedHashMap data, String openid, String url) { + TemplateMessage templateMessage = new TemplateMessage(); + templateMessage.setTouser(openid); + templateMessage.setTemplate_id(templateId); + templateMessage.setData(data); + templateMessage.setUrl(url); + TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(getWxToken(), templateMessage); + if (templateMessageResult.isSuccess()) { + new SendResult(); + } else { + new SendResult(); + } + } + + private String getWxToken() { + try { + //微信appid + CommonInfo one = commonInfoService.findOne(5); + return TokenManager.getToken(one.getValue()); + } catch (Exception e) { + throw new RuntimeException("GET_ACCESS_TOKEN_FAIL"); + } + } + + + @Override + @Transactional + public Result cashMoney(Long userId, Double money, Integer classify) { + if (classify == null) { + classify = 1; + } + if (money == null || money <= 0.00) { + return Result.error("请不要输入小于0的数字,请输入正确的提现金额!"); + } + //最低提现金额 + CommonInfo one = commonInfoService.findOne(112); + if (one != null && money < Double.parseDouble(one.getValue())) { + return Result.error("输入金额不满足最低提现金额,请重新输入!"); + } + //最高提现金额 + CommonInfo one2 = commonInfoService.findOne(153); + if (one2 != null && money > Double.parseDouble(one2.getValue())) { + return Result.error(-100, "输入金额过大,不能大于" + one2.getValue() + ",请重新输入!"); + } + UserEntity userEntity = userService.selectUserById(userId); + if (classify == 2 || classify == 3) { + String value = commonInfoService.findOne(244).getValue(); + if ("2".equals(value)) { + if (StringUtils.isEmpty(userEntity.getWxImg())) { + return Result.error("请绑定微信提现收款码!"); + } + } + + } + CommonInfo one3 = commonInfoService.findOne(154); + //手续费 + CommonInfo one1 = commonInfoService.findOne(152); + + //计算提现金额所需要的手续费 小于0.01 的按0.01来算 + Double mul = AmountCalUtils.mul(money, Double.parseDouble(one1.getValue())); + if (mul < 0.01) { + mul = 0.01; + } + //查询账户的余额 + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + if (money > userMoney.getMoney().doubleValue()) { + return Result.error("金额不足,请输入正确的金额!"); + } + //提现判断金额是否足够 + Double moneySum = AmountCalUtils.add(new BigDecimal(money), new BigDecimal(mul)).doubleValue(); //金额=提现金额+手续费 + Double moneySub = AmountCalUtils.sub(new BigDecimal(money), new BigDecimal(mul)).doubleValue(); //金额=提现金额+手续费 + if ((userMoney.getMoney()).compareTo(BigDecimal.valueOf(moneySum)) > -1) { //用户金额足够 + //扣除可提现金额直接在数据库进行操作 + //增加金额操作记录 + Double moneys = AmountCalUtils.divide(money, Double.parseDouble(one3.getValue())); + userMoneyService.updateMoney(2, userId, BigDecimal.valueOf(moneySum)); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setTitle("提现:" + moneys); + + userMoneyDetails.setType(2); + userMoneyDetails.setMoney(new BigDecimal(moneySum)); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + + CashOut cashOut = new CashOut(); + cashOut.setState(0); + cashOut.setClassify(classify); + if (classify == 2 || classify == 3) { + cashOut.setWxImg(userEntity.getWxImg()); + userMoneyDetails.setContent("微信提现:" + moneys + ",扣除:" + moneySum + ",手续费:" + mul); + } else { + userMoneyDetails.setContent("支付宝提现:" + moneys + ",扣除:" + moneySum + ",手续费:" + mul); + } + cashOut.setZhifubao(userEntity.getZhiFuBao()); + cashOut.setZhifubaoName(userEntity.getZhiFuBaoName()); + cashOut.setMoney(moneys.toString()); + cashOut.setCreateAt(sdf.format(new Date())); + cashOut.setUserId(userEntity.getUserId()); + cashOut.setRate(moneySum); + cashOut.setOrderNumber(String.valueOf(System.currentTimeMillis())); + baseMapper.insert(cashOut); + userMoneyDetailsService.save(userMoneyDetails); + //扣除金额直接在数据库进行操作 + return Result.success("提现成功,将在三个工作日内到账,请耐心等待!"); + } else { + //扣除可提现金额直接在数据库进行操作 + //增加金额操作记录 + Double moneys = AmountCalUtils.divide(moneySub, Double.parseDouble(one3.getValue())); + userMoneyService.updateMoney(2, userId, BigDecimal.valueOf(money)); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setTitle("提现:" + moneys); + userMoneyDetails.setContent("支付宝提现:" + moneys + ",扣除:" + money + ",手续费:" + mul); + userMoneyDetails.setType(2); + userMoneyDetails.setMoney(new BigDecimal(money)); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + CashOut cashOut = new CashOut(); + cashOut.setState(0); + cashOut.setClassify(classify); + if (classify == 2 || classify == 3) { + cashOut.setWxImg(userEntity.getWxImg()); + userMoneyDetails.setContent("微信提现:" + moneys + ",扣除:" + moneySum + ",手续费:" + mul); + } else { + userMoneyDetails.setContent("支付宝提现:" + moneys + ",扣除:" + moneySum + ",手续费:" + mul); + } + cashOut.setZhifubao(userEntity.getZhiFuBao()); + cashOut.setZhifubaoName(userEntity.getZhiFuBaoName()); + cashOut.setMoney(moneys.toString()); + cashOut.setCreateAt(sdf.format(new Date())); + cashOut.setUserId(userEntity.getUserId()); + cashOut.setRate(money); + cashOut.setOrderNumber(String.valueOf(System.currentTimeMillis())); + baseMapper.insert(cashOut); + return Result.success("提现成功,将在三个工作日内到账,请耐心等待!"); + } + } + + @Override + public HashMap payMember(String time, Integer flag) { + HashMap hashMap = new HashMap<>(); + //微信app + BigDecimal wxApp = baseMapper.getRechargeWay(time, flag, 1); + //微信公众号 + BigDecimal wxOfficial = baseMapper.getRechargeWay(time, flag, 2); + //微信小程序 + BigDecimal wxCourse = baseMapper.getRechargeWay(time, flag, 3); + //支付宝app + BigDecimal zfbApp = baseMapper.getRechargeWay(time, flag, 4); + //支付宝H5 + BigDecimal zfbH5 = baseMapper.getRechargeWay(time, flag, 5); + + + //余额充值 + BigDecimal payBalance = payDetailsService.sumTypeMoney(time, flag, 1); + //订单支付 + BigDecimal payOrder = payDetailsService.sumTypeMoney(time, flag, 2); + //缴纳保证金 + BigDecimal payBond = payDetailsService.sumTypeMoney(time, flag, 4); + //购买水票 + BigDecimal payTicket = payDetailsService.sumTypeMoney(time, flag, 6); + //购买优惠券 + BigDecimal payCoupon = payDetailsService.sumTypeMoney(time, flag, 7); + //压桶购买 + BigDecimal payBucket = payDetailsService.sumTypeMoney(time, flag, 8); + hashMap.put("payBalance", payBalance); + hashMap.put("payOrder", payOrder); + hashMap.put("payBond", payBond); + hashMap.put("payTicket", payTicket); + hashMap.put("payCoupon", payCoupon); + hashMap.put("payBucket", payBucket); + + BigDecimal allMoney = wxApp.add(wxOfficial).add(wxCourse).add(zfbApp).add(zfbH5); + hashMap.put("wxApp", wxApp); + hashMap.put("wxOfficial", wxOfficial); + hashMap.put("wxCourse", wxCourse); + hashMap.put("zfbApp", zfbApp); + hashMap.put("zfbH5", zfbH5); + hashMap.put("allMoney", allMoney); + return hashMap; + } + + @Override + public HashMap statisticsMoney(String time, Integer flag) { + HashMap hashMap = new HashMap<>(); + //总提现金额 + BigDecimal allMoney = cashOutDao.sumCashMoney(time, flag, null, null); + //支付宝提现金额 + BigDecimal zfbAllMoney = cashOutDao.sumCashMoney(time, flag, null, 1); + //微信提现金额 + BigDecimal wxAllMoney = cashOutDao.sumCashMoney(time, flag, null, 2); + //待提现金额 + BigDecimal waitMoney = cashOutDao.sumCashMoney(time, flag, 0, null); + //支付宝待提现金额 + BigDecimal zfbWaitMoney = cashOutDao.sumCashMoney(time, flag, 0, 1); + //微信待提现金额 + BigDecimal wxWaitMoney = cashOutDao.sumCashMoney(time, flag, 0, 2); + //同意提现金额 + BigDecimal traverseMoney = cashOutDao.sumCashMoney(time, flag, 1, null); + //支付宝同意提现金额 + BigDecimal zfbTraverseMoney = cashOutDao.sumCashMoney(time, flag, 1, 1); + //微信同意提现金额 + BigDecimal wxTraverseMoney = cashOutDao.sumCashMoney(time, flag, 1, 2); + //驳回提现金额 + BigDecimal refuseMoney = cashOutDao.sumCashMoney(time, flag, -1, null); + //支付宝驳回提现金额 + BigDecimal zfbRefuseMoney = cashOutDao.sumCashMoney(time, flag, -1, 1); + //微信驳回提现金额 + BigDecimal wxRefuseMoney = cashOutDao.sumCashMoney(time, flag, -1, 2); + + //总提现次数 + BigDecimal allCount = cashOutDao.sumCashMoneyCount(time, flag, null, null); + //支付宝提现次数 + BigDecimal zfbAllCount = cashOutDao.sumCashMoneyCount(time, flag, null, 1); + //微信提现次数 + BigDecimal wxAllCount = cashOutDao.sumCashMoneyCount(time, flag, null, 2); + //待提现次数 + BigDecimal waitCount = cashOutDao.sumCashMoneyCount(time, flag, 0, null); + //支付宝待提现次数 + BigDecimal zfbWaitCount = cashOutDao.sumCashMoneyCount(time, flag, 0, 1); + //微信待提现次数 + BigDecimal wxWaitCount = cashOutDao.sumCashMoneyCount(time, flag, 0, 2); + //同意提现次数 + BigDecimal traverseCount = cashOutDao.sumCashMoneyCount(time, flag, 1, null); + //支付宝同意提现次数 + BigDecimal zfbTraverseCount = cashOutDao.sumCashMoneyCount(time, flag, 1, 1); + //微信同意提现次数 + BigDecimal wxTraverseCount = cashOutDao.sumCashMoneyCount(time, flag, 1, 2); + //驳回提现次数 + BigDecimal refuseCount = cashOutDao.sumCashMoneyCount(time, flag, -1, null); + //支付宝驳回提现次数 + BigDecimal zfbRefuseCount = cashOutDao.sumCashMoneyCount(time, flag, -1, 1); + //微信驳回提现次数 + BigDecimal wxRefuseCount = cashOutDao.sumCashMoneyCount(time, flag, -1, 2); + + + hashMap.put("allCount", allCount); + hashMap.put("zfbAllCount", zfbAllCount); + hashMap.put("wxAllCount", wxAllCount); + hashMap.put("waitCount", waitCount); + hashMap.put("zfbWaitCount", zfbWaitCount); + hashMap.put("wxWaitCount", wxWaitCount); + hashMap.put("traverseCount", traverseCount); + hashMap.put("zfbTraverseCount", zfbTraverseCount); + hashMap.put("wxTraverseCount", wxTraverseCount); + hashMap.put("refuseCount", refuseCount); + hashMap.put("zfbRefuseCount", zfbRefuseCount); + hashMap.put("wxRefuseCount", wxRefuseCount); + + + hashMap.put("allMoney", allMoney); + hashMap.put("zfbAllMoney", zfbAllMoney); + hashMap.put("wxAllMoney", wxAllMoney); + hashMap.put("waitMoney", waitMoney); + hashMap.put("zfbWaitMoney", zfbWaitMoney); + hashMap.put("wxWaitMoney", wxWaitMoney); + hashMap.put("traverseMoney", traverseMoney); + hashMap.put("zfbTraverseMoney", zfbTraverseMoney); + hashMap.put("wxTraverseMoney", wxTraverseMoney); + hashMap.put("refuseMoney", refuseMoney); + hashMap.put("zfbRefuseMoney", zfbRefuseMoney); + hashMap.put("wxRefuseMoney", wxRefuseMoney); + return hashMap; + } + + @Override + public IPage selectAdminHelpProfit(Integer page, Integer limit, String startTime, String endTime, CashOut cashOut) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + return baseMapper.selectAdminHelpProfit(pages, startTime, endTime, cashOut); + } +} diff --git a/src/main/java/com/sqx/modules/pay/service/impl/PayDetailsServiceImpl.java b/src/main/java/com/sqx/modules/pay/service/impl/PayDetailsServiceImpl.java new file mode 100644 index 0000000..c9818b6 --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/service/impl/PayDetailsServiceImpl.java @@ -0,0 +1,94 @@ +package com.sqx.modules.pay.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.pay.dao.PayDetailsDao; +import com.sqx.modules.pay.entity.PayDetails; +import com.sqx.modules.pay.service.PayDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * 充值记录 + */ +@Service +public class PayDetailsServiceImpl extends ServiceImpl implements PayDetailsService { + + /** + * 充值记录 + */ + @Autowired + private PayDetailsDao payDetailsDao; + + + @Override + public PageUtils selectPayDetails(int page, int limit, String startTime, String endTime, Long userId, Integer state, Integer type) { + Page> pages = new Page<>(page, limit); + if (state != null && state == -1) { + state = null; + } + return new PageUtils(payDetailsDao.selectPayDetails(pages, startTime, endTime, userId, state,type)); + } + + @Override + public Double selectSumPay(String createTime, String endTime, Long userId) { + if (userId == null || userId == -1) { + return payDetailsDao.selectSumPay(createTime, endTime, null); + } + return payDetailsDao.selectSumPay(createTime, endTime, userId); + } + + @Override + public PageUtils payMemberAnalysis(int page, int limit, String time, Integer flag) { + Page> pages = new Page<>(page, limit); + return new PageUtils(payDetailsDao.payMemberAnalysis(pages, time, flag)); + } + + @Override + public PageUtils selectUserMemberList(int page, int limit, String phone) { + Page> pages = new Page<>(page, limit); + return new PageUtils(payDetailsDao.selectUserMemberList(pages, phone)); + } + + @Override + public Double selectSumMember(String time, Integer flag) { + return payDetailsDao.selectSumMember(time, flag); + } + + @Override + public Double selectSumPayByState(String time, Integer flag, Integer state) { + return payDetailsDao.selectSumPayByState(time, flag, state); + } + + @Override + public Double selectSumPayByClassify(String time, Integer flag, Integer classify, Integer payClassify) { + return payDetailsDao.selectSumPayByClassify(time, flag, classify, payClassify); + } + + @Override + public Double instantselectSumPay(String date, Long userId) { + return payDetailsDao.instantselectSumPay(date, userId); + } + + @Override + public IPage getBucketBuyList(Integer page, Integer limit, Long userId, Integer type, String phone, String userName, String tradeNo) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + return payDetailsDao.getBucketBuyList(pages, userId,type,phone,userName,tradeNo); + } + + @Override + public BigDecimal sumTypeMoney(String time, Integer flag, Integer type) { + return payDetailsDao.sumTypeMoney(time,flag,type); + } +} diff --git a/src/main/java/com/sqx/modules/pay/service/impl/WxServiceImpl.java b/src/main/java/com/sqx/modules/pay/service/impl/WxServiceImpl.java new file mode 100644 index 0000000..10c334c --- /dev/null +++ b/src/main/java/com/sqx/modules/pay/service/impl/WxServiceImpl.java @@ -0,0 +1,783 @@ +package com.sqx.modules.pay.service.impl; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.github.wxpay.sdk.WXPay; +import com.github.wxpay.sdk.WXPayConstants; +import com.github.wxpay.sdk.WXPayUtil; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserMoneyDao; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.coupon.entity.SelfCouponUser; +import com.sqx.modules.coupon.respository.SelfCouponUserJpaRepository; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.orders.dao.PayOrderDao; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.entity.PayOrder; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.pay.config.WXConfig; +import com.sqx.modules.pay.dao.PayDetailsDao; +import com.sqx.modules.pay.entity.PayDetails; +import com.sqx.modules.pay.service.WxService; +import com.sqx.modules.taking.entity.GoodsSku; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.GoodsSkuService; +import com.sqx.modules.taking.service.OrderTakingService; +import com.sqx.modules.task.dao.HelpOrderDao; +import com.sqx.modules.task.entity.HelpOrder; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.tickets.service.TicketsService; +import com.sqx.modules.utils.*; +import jodd.util.StringUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * @author fang + * @date 2020/2/26 + */ +@Service +@Slf4j +public class WxServiceImpl implements WxService { + private static final String SPBILL_CREATE_IP = "127.0.0.1"; + private static final String TRADE_TYPE_APP = "APP"; + private static final String TRADE_TYPE_NATIVE = "NATIVE"; + private static final String TRADE_TYPE_JSAPI = "JSAPI"; + private static final String Wap = "MWEB"; + + + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private UserService userService; + @Autowired + private PayDetailsDao payDetailsDao; + @Autowired + private PayOrderDao payOrderDao; + @Autowired + private UserMoneyDao userMoneyDao; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private OrdersDao ordersDao; + @Autowired + private MessageService messageService; + @Autowired + private TbCouponUserService couponUserService; + @Autowired + private OrderTakingService orderTakingService; + @Autowired + private HelpOrderDao helpOrderDao; + @Autowired + private TbCouponService couponService; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private TicketsService ticketsService; + @Autowired + private SelfCouponUserJpaRepository selfCouponUserJpaRepository; + @Autowired + private LaundryRepository laundryRepository; + @Autowired + private GoodsSkuService goodsSkuService; + private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + + @Override + public Result payOrder(Long id, Integer classify, HttpServletRequest request) throws Exception { + PayOrder bean = payOrderDao.selectById(id); + if (bean == null) { + return Result.error("订单生成失败,请重新下单!"); + } + PayDetails payDetails = payDetailsDao.selectByOrderId(bean.getOrdersNo()); + if (payDetails == null) { + payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(sdf.format(new Date())); + payDetails.setOrderId(bean.getOrdersNo()); + payDetails.setUserId(bean.getUserId()); + payDetails.setMoney(bean.getPayMoney().doubleValue()); + payDetails.setClassify(classify); + payDetails.setType(1); + payDetailsDao.insert(payDetails); + } + return pay(bean.getPayMoney().doubleValue(), classify, bean.getUserId(), bean.getOrdersNo(), request, null); + } + + @Override + public Result wxPayOrder(Long id, Integer classify, HttpServletRequest request) throws Exception { + Orders bean = ordersDao.selectById(id); + if (bean == null) { + return Result.error("订单生成失败,请重新下单!"); + } + if (bean.getOrdersType() == 1) { + OrderTaking orderTaking = orderTakingService.getById(bean.getOrderTakingId()); + GoodsSku goodsSku = goodsSkuService.getById(bean.getSkuId()); + if (goodsSku.getStock() < bean.getOrderNumber()) { + return Result.error(orderTaking.getServiceName() + " 剩余库存不足!"); + } + } + PayDetails payDetails = payDetailsDao.selectByOrderId(bean.getOrdersNo()); + if (payDetails == null) { + payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(sdf.format(new Date())); + payDetails.setOrderId(bean.getOrdersNo()); + payDetails.setUserId(bean.getUserId()); + payDetails.setMoney(bean.getPayMoney().doubleValue()); + payDetails.setClassify(classify); + payDetails.setType(2); + payDetailsDao.insert(payDetails); + } + return pay(bean.getPayMoney().doubleValue(), classify, bean.getUserId(), bean.getOrdersNo(), request, null); + } + + + @Override + public Result wxPayHelpOrder(HelpOrder helpOrder, Integer classify, HttpServletRequest request) throws Exception { + if (helpOrder.getCommission().doubleValue() <= 0) { + return Result.error("金额必须大于0"); + } + helpOrder.setOrderNo(getGeneralOrder()); + PayDetails payDetails = payDetailsDao.selectByOrderId(helpOrder.getOrderNo()); + if (payDetails == null) { + payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(sdf.format(new Date())); + payDetails.setOrderId(helpOrder.getOrderNo()); + payDetails.setUserId(helpOrder.getUserId()); + payDetails.setMoney(helpOrder.getCommission().doubleValue()); + payDetails.setClassify(classify); + payDetails.setType(3); + payDetails.setRemark(JSON.toJSONString(helpOrder)); + payDetailsDao.insert(payDetails); + } + return pay(helpOrder.getCommission().doubleValue(), classify, helpOrder.getUserId(), helpOrder.getOrderNo(), request, null); + } + + + @Override + public Result wxPaySafetyMoney(Long userId, Integer type, HttpServletRequest request) throws Exception { + UserEntity userEntity = userService.selectUserById(userId); + if (userEntity.getIsSafetyMoney() != null && userEntity.getIsSafetyMoney() == 1) { + return Result.error("当前账号已经缴纳过保证金了!"); + } + String value = commonInfoService.findOne(271).getValue(); + BigDecimal money = new BigDecimal(value); + String outTradeNo = getGeneralOrder(); + PayDetails payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(sdf.format(new Date())); + payDetails.setOrderId(outTradeNo); + payDetails.setUserId(userId); + payDetails.setMoney(money.doubleValue()); + payDetails.setClassify(type); + payDetails.setType(4); + payDetailsDao.insert(payDetails); + return pay(money.doubleValue(), type, userId, outTradeNo, request, 1); + } + + @Override + public Result wxPayShoppingOrders(List ordersList, Integer type, HttpServletRequest request) throws Exception { + List ordersLists = new ArrayList<>(); + BigDecimal price = BigDecimal.ZERO; + for (Orders orders : ordersList) { + Laundry laundry = laundryRepository.findById(orders.getLaundryId()).orElse(null); + Orders oldOrders = ordersDao.selectById(orders.getOrdersId()); + if (laundry == null) { + return Result.error("站点参数错误!"); + } + if (laundry.getRate() != null && laundry.getRate().doubleValue() > 0) { + BigDecimal laundryMoney = oldOrders.getPayMoney().multiply(laundry.getRate()); + oldOrders.setLaundryMoney(laundryMoney); + } + oldOrders.setLaundryId(laundry.getLaundryId()); + oldOrders.setLaundryName(laundry.getLaundryName()); + OrderTaking orderTaking = orderTakingService.getById(oldOrders.getOrderTakingId()); + GoodsSku goodsSku = goodsSkuService.getById(oldOrders.getSkuId()); + if (goodsSku.getStock() < oldOrders.getOrderNumber()) { + return Result.error(orderTaking.getServiceName() + " 剩余库存不足!"); + } + + if (orders.getCouponId() != null) { + TbCouponUser tbCouponUser = couponUserService.getById(orders.getCouponId()); + if (tbCouponUser == null) { + return Result.error("你未持有当前优惠券"); + } + if (tbCouponUser.getStatus() == 1) { + return Result.error("当前优惠券已使用"); + } + if (tbCouponUser.getStatus() == 2) { + return Result.error("当前优惠券已失效"); + } + //如果订单金额大于优惠券最小订单金额 + if (oldOrders.getPayMoney().compareTo(tbCouponUser.getMinMoney()) >= 0) { + //写入使用了优惠券之后的订单金额 + oldOrders.setPayMoney(oldOrders.getPayMoney().subtract(tbCouponUser.getMoney())); + tbCouponUser.setStatus(1); + tbCouponUser.setEmployTime(new Date()); + oldOrders.setCouponId(orders.getCouponId()); + couponUserService.updateById(tbCouponUser); + + } else { + return Result.error("订单金额不满足最低满减金额"); + } + } + + + price = price.add(oldOrders.getPayMoney()); + oldOrders.setRemarks(orders.getRemarks()); + oldOrders.setStartTime(orders.getStartTime()); + oldOrders.setProvince(orders.getProvince()); + oldOrders.setCity(orders.getCity()); + oldOrders.setDistrict(orders.getDistrict()); + oldOrders.setDetailsAddress(orders.getDetailsAddress()); + oldOrders.setName(orders.getName()); + oldOrders.setPhone(orders.getPhone()); + oldOrders.setIsShopping(2); + ordersLists.add(oldOrders); + ordersDao.updateById(oldOrders); + } + + Orders orders1 = ordersLists.get(0); + PayDetails payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(sdf.format(new Date())); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setUserId(orders1.getUserId()); + payDetails.setMoney(price.doubleValue()); + payDetails.setClassify(type); + payDetails.setType(5); + payDetails.setRemark(JSONObject.toJSONString(ordersLists)); + payDetailsDao.insert(payDetails); + return pay(price.doubleValue(), type, orders1.getUserId(), payDetails.getOrderId(), request, null); + } + + /** + * 微信支付订单生成 + * + * @param moneys 支付金额 带小数点 + * @param classify 类型 1app 2 二维码支付 3小程序 公众号支付 + * @param userId 用户id + * @param outTradeNo 单号 + * @return + * @throws Exception + */ + private Result pay(Double moneys, Integer classify, Long userId, String outTradeNo, HttpServletRequest request, Integer shop) throws Exception { + //h5服务域名配置 + CommonInfo oneu = commonInfoService.findOne(19); + String url; + if (classify == 3) { + if (shop != null) { + url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyJsApiShop"; + } else { + url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyJsApi"; + } + + } else if (classify == 2 || classify == 4) { + url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyMp"; + } else { + url = oneu.getValue() + "/sqx_fast/app/wxPay/notify"; + } + String currentTimeMillis = (System.currentTimeMillis() / 1000) + ""; + //后台服务名称 + CommonInfo one = commonInfoService.findOne(12); + log.info("回调地址:" + url); + Double mul = AmountCalUtils.mul(moneys, 100); + String money = String.valueOf(mul.intValue()); + String generateNonceStr = WXPayUtil.generateNonceStr(); + WXConfig config = new WXConfig(); + //微信小程序APPID 微信公众号APPID + if (classify == 1) { + config.setAppId(commonInfoService.findOne(74).getValue()); + } else if (classify == 2 || classify == 4) { + config.setAppId(commonInfoService.findOne(5).getValue()); + } else { + if (shop != null) { + config.setAppId(commonInfoService.findOne(239).getValue()); + } else { + config.setAppId(commonInfoService.findOne(45).getValue()); + } + + } + //微信商户key + config.setKey(commonInfoService.findOne(75).getValue()); + //微信商户号mchId + config.setMchId(commonInfoService.findOne(76).getValue()); + WXPay wxpay = new WXPay(config); + Map data = new HashMap<>(); + data.put("appid", config.getAppID()); + data.put("mch_id", config.getMchID()); + data.put("nonce_str", generateNonceStr); + String body = one.getValue(); + data.put("body", body); + //生成商户订单号,不可重复 + data.put("out_trade_no", outTradeNo); + data.put("total_fee", money); + //自己的服务器IP地址 + data.put("spbill_create_ip", SPBILL_CREATE_IP); + //异步通知地址(请注意必须是外网) + data.put("notify_url", url); + //交易类型 + if (classify == 1) { + data.put("trade_type", TRADE_TYPE_APP); + } else if (classify == 2) { + data.put("trade_type", TRADE_TYPE_JSAPI); + } else if (classify == 3) { + data.put("trade_type", TRADE_TYPE_JSAPI); + } else { + data.put("trade_type", Wap); + data.put("spbill_create_ip", HttpClientUtil.getIpAddress(request)); + } + //附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据 + data.put("attach", ""); + data.put("sign", WXPayUtil.generateSignature(data, config.getKey(), + WXPayConstants.SignType.MD5)); + if (classify == 3 || classify == 2) { + UserEntity userEntity = userService.queryByUserId(userId); + if (classify == 3) { + if (shop != null) { + if (StringUtils.isNotBlank(userEntity.getShopOpenId())) { + data.put("openid", userEntity.getShopOpenId()); + } + } else { + if (StringUtils.isNotBlank(userEntity.getOpenId())) { + data.put("openid", userEntity.getOpenId()); + } + } + + } else { + data.put("openid", userEntity.getWxOpenId()); + } + } + //使用官方API请求预付订单 + Map response = wxpay.unifiedOrder(data); + for (String key : response.keySet()) { + log.info("微信支付订单微信返回参数:keys:" + key + " value:" + response.get(key).toString()); + } + if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数 + Map param = new HashMap<>(); + if (classify == 1) { + param.put("appid", config.getAppID()); + param.put("partnerid", response.get("mch_id")); + param.put("prepayid", response.get("prepay_id")); + param.put("package", "Sign=WXPay"); + param.put("noncestr", generateNonceStr); + param.put("timestamp", currentTimeMillis); + param.put("sign", WXPayUtil.generateSignature(param, config.getKey(), + WXPayConstants.SignType.MD5)); + param.put("outtradeno", outTradeNo); + } else if (classify == 2 || classify == 4 || classify == 3) { + param.put("appid", config.getAppID()); + param.put("partnerid", response.get("mch_id")); + param.put("prepayid", response.get("prepay_id")); + param.put("noncestr", generateNonceStr); + param.put("timestamp", currentTimeMillis); + /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(), + WXPayConstants.SignType.MD5));*/ + String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis + "" + "&key=" + config.getKey(); + String sign = MD5Util.md5Encrypt32Upper(stringSignTemp).toUpperCase(); + param.put("sign", sign); + param.put("outtradeno", outTradeNo); + param.put("package", "prepay_id=" + response.get("prepay_id"));//给前端返回的值 + param.put("mweb_url", response.get("mweb_url")); + param.put("trade_type", response.get("trade_type")); + param.put("return_msg", response.get("return_msg")); + param.put("result_code", response.get("result_code")); + param.put("signType", "MD5"); + } else { + param.put("mweb_url", response.get("mweb_url")); + } + return Result.success().put("data", param); + } + return Result.error("获取订单失败"); + } + + @Override + public String payBack(String resXml, Integer type) { + WXConfig config = null; + try { + config = new WXConfig(); + } catch (Exception e) { + e.printStackTrace(); + } + log.error("进入回调了!!!"); + if (type == 1) { + config.setAppId(commonInfoService.findOne(74).getValue()); + } else if (type == 2) { + config.setAppId(commonInfoService.findOne(5).getValue()); + } else if (type == 3) { + config.setAppId(commonInfoService.findOne(45).getValue()); + } else { + config.setAppId(commonInfoService.findOne(239).getValue()); + } + config.setKey(commonInfoService.findOne(75).getValue()); + config.setMchId(commonInfoService.findOne(76).getValue()); + WXPay wxpay = new WXPay(config); + String xmlBack = ""; + Map notifyMap = null; + try { + notifyMap = WXPayUtil.xmlToMap(resXml); // 调用官方SDK转换成map类型数据 + if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效,有效则进一步处理 + log.error("验证成功!!!"); + String return_code = notifyMap.get("return_code");//状态 + String out_trade_no = notifyMap.get("out_trade_no");//商户订单号 + if (return_code.equals("SUCCESS")) { + log.error("验证成功222!!!"); + log.error("微信支付订单号" + notifyMap.get("transaction_id")); + String transactionId = notifyMap.get("transaction_id"); + if (out_trade_no != null) { + // 注意特殊情况:订单已经退款,但收到了支付结果成功的通知,不应把商户的订单状态从退款改成支付成功 + // 注意特殊情况:微信服务端同样的通知可能会多次发送给商户系统,所以数据持久化之前需要检查是否已经处理过了,处理了直接返回成功标志 + //业务数据持久化 + log.error("订单号!!!" + out_trade_no); + PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no); + if (payDetails.getState() == 0) { + payDetails.setState(1); + payDetails.setPayTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN)); + payDetails.setTradeNo(transactionId); + payDetailsDao.updateById(payDetails); + if (payDetails.getType() == 1) { + //设置查询条件 + QueryWrapper queryWrapper = new QueryWrapper<>(); + //根据订单编号去查询订单 + queryWrapper.eq("orders_no", out_trade_no); + //去订单表中查询到该订单 + PayOrder orders = payOrderDao.selectOne(queryWrapper); + + + //改变订单状态 + orders.setState(1); + orders.setPayWay(type); + //设置订单更新时间 + orders.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payOrderDao.updateById(orders); + //调用处理接口 + userMoneyDao.updateMayMoney(1, orders.getUserId(), orders.getMoney()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setTitle("微信充值"); + userMoneyDetails.setContent("微信充值:" + orders.getPayMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(orders.getMoney()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + } else if (payDetails.getType() == 2) { + Orders orders = ordersDao.selectOne(new QueryWrapper().eq("orders_no", payDetails.getOrderId())); + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + goodsSku.setStock(goodsSku.getStock() - orders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + UserEntity userEntity = userService.selectUserById(orders.getUserId()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(orders.getPayMoney()); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setContent("微信支付订单"); + userMoneyDetails.setTitle("下单成功,订单号:" + orders.getOrdersNo()); + userMoneyDetails.setType(2); + userMoneyDetails.setOrdersNo(orders.getOrdersNo()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单下单成功:" + orders.getOrdersNo()); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + orders.setState("4"); + orders.setIsRemind(0); + orders.setPayWay(2); + + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + + ordersDao.updateById(orders); + + + } else if (payDetails.getType() == 3) { + HelpOrder helpOrder = JSONObject.parseObject(payDetails.getRemark(), HelpOrder.class); + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(new Date()); + helpOrder.setStatus(2); + helpOrder.setCreateTime(date); + helpOrder.setMoney(helpOrder.getCommission()); + CommonInfo one = commonInfoService.findOne(120); + String value = one.getValue(); + Double mul = AmountCalUtils.mul(helpOrder.getCommission().doubleValue(), Double.parseDouble(value)); + BigDecimal sub = AmountCalUtils.sub(helpOrder.getMoney(), BigDecimal.valueOf(mul)); + helpOrder.setCommission(sub); + helpOrder.setPayWay(2); + helpOrderDao.insert(helpOrder); + + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setUserId(helpOrder.getUserId()); + userMoneyDetails.setTitle("万能任务"); + userMoneyDetails.setContent("万能任务微信支付扣款:" + helpOrder.getMoney()); + userMoneyDetails.setType(2); + userMoneyDetails.setMoney(helpOrder.getMoney()); + userMoneyDetails.setCreateTime(date); + userMoneyDetailsService.save(userMoneyDetails); + if (userEntity.getClientid() != null) { + userService.pushToSingle("派发订单", "您的订单已经派发成功!", userEntity.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的订单已经派发成功!"); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageService.saveBody(messageInfo); + } else if (payDetails.getType() == 4) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + BigDecimal money = BigDecimal.valueOf(payDetails.getMoney()); + userMoneyDao.updateSafetyMoney(1, payDetails.getUserId(), money); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setClassify(4); + userMoneyDetails.setUserId(payDetails.getUserId()); + userMoneyDetails.setTitle("[保证金]缴纳保证金"); + userMoneyDetails.setContent("缴纳保证金,保证金增加:" + money); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(money); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(payDetails.getUserId()); + userMoneyService.updateSafetyMoneyWay(userMoney.getId(), 1, payDetails.getOrderId()); + UserEntity userEntity = userService.selectUserById(payDetails.getUserId()); + userEntity.setIsSafetyMoney(1); + userService.updateById(userEntity); + } else if (payDetails.getType() == 5) { + List ordersList = JSONObject.parseArray(payDetails.getRemark(), Orders.class); + for (Orders orders : ordersList) { + GoodsSku goodsSku = goodsSkuService.getById(orders.getSkuId()); + goodsSku.setStock(goodsSku.getStock() - orders.getOrderNumber()); + goodsSkuService.updateById(goodsSku); + UserEntity userEntity = userService.selectUserById(orders.getUserId()); + UserMoneyDetails userMoneyDetails = new UserMoneyDetails(); + userMoneyDetails.setMoney(orders.getPayMoney()); + userMoneyDetails.setUserId(orders.getUserId()); + userMoneyDetails.setContent("微信支付订单"); + userMoneyDetails.setTitle("下单成功,订单号:" + orders.getOrdersNo()); + userMoneyDetails.setType(2); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("订单下单成功:" + orders.getOrdersNo()); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + orders.setState("4"); + orders.setIsRemind(0); + orders.setPayWay(2); + + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + ordersDao.updateById(orders); + } + } else if (payDetails.getType() == 6) { + ticketsService.businessCallback(2, payDetails.getUserId(), BigDecimal.valueOf(payDetails.getMoney()), payDetails.getRelationId(), payDetails.getBuyNum(), payDetails.getTradeNo()); + } else if (payDetails.getType() == 7) { + couponUserService.businessCallback(2, payDetails.getUserId(), payDetails.getRelationId(), payDetails.getBuyNum(), BigDecimal.valueOf(payDetails.getMoney())); + } else if (payDetails.getType() == 8) { + userService.bucketCallback(payDetails.getUserId(), payDetails.getBuyNum(), BigDecimal.valueOf(payDetails.getMoney()), payDetails.getClassify()); + } + } + System.err.println("微信手机支付回调成功订单号:" + out_trade_no + ""); + xmlBack = "" + "" + "" + " "; + } else { + System.err.println("微信手机支付回调成功订单号:" + out_trade_no + ""); + xmlBack = "" + "" + "" + " "; + } + } else { + } + return xmlBack; + } else { + // 签名错误,如果数据里没有sign字段,也认为是签名错误 + System.err.println("手机支付回调通知签名错误"); + xmlBack = "" + "" + "" + " "; + return xmlBack; + } + } catch ( + Exception e) { + System.err.println("手机支付回调通知失败" + e); + xmlBack = "" + "" + "" + " "; + } + return xmlBack; + } + + + public String getGeneralOrder() { + Date date = new Date(); + String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000)); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + String format = sdf.format(date); + return format + newString; + } + + + @Override + public boolean refund(String ordersNo) { + WXConfigUtil config = null; + String h5Url = commonInfoService.findOne(19).getValue().split("://")[1]; + String filePath = "/www/wwwroot/" + h5Url + "/service/apiclient_cert.p12"; + try { + config = new WXConfigUtil(filePath); + } catch (Exception e) { + e.printStackTrace(); + } + int commInfoId = 0; + PayDetails payDetails = payDetailsDao.selectByOrderId(ordersNo); + Integer payWay = payDetails.getClassify(); + //orders.getPayWay(); //1app微信 2微信公众号 3微信小程序 + switch (payWay) { + case 1: + commInfoId = 74; + break; //appId + case 2: + commInfoId = 5; + break; //公众号id + case 3: + commInfoId = 45; + break; //小程序id + } + config.setAppId(commonInfoService.findOne(commInfoId).getValue()); + config.setKey(commonInfoService.findOne(75).getValue()); + config.setMchId(commonInfoService.findOne(76).getValue()); + WXPay wxpay = new WXPay(config); + Map data = new HashMap<>(); + data.put("appid", config.getAppID()); + data.put("mch_id", config.getMchID()); + data.put("nonce_str", WXPayUtil.generateNonceStr()); + try { + data.put("sign", WXPayUtil.generateSignature(data, config.getKey(), WXPayConstants.SignType.MD5)); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + + data.put("out_trade_no", payDetails.getOrderId()); //订单号,支付单号一致 + data.put("out_refund_no", payDetails.getOrderId()); //退款单号,同一笔用不同的退款单号 + BigDecimal multiply = BigDecimal.valueOf(payDetails.getMoney()).multiply(BigDecimal.valueOf(100)); + String fee = String.valueOf(multiply.intValue()); + data.put("total_fee", fee); //1块等于微信支付传入100); + data.put("refund_fee", fee); //1块等于微信支付传入100); + //使用官方API退款 + try { + Map response = wxpay.refund(data); + if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数 + System.err.println("退款成功"); + return true; + } else { + return false; + } + } catch (Exception e) { + log.info("微信退款异常:" + e.getMessage(), e); + e.printStackTrace(); + return false; + } + } + + @Override + public Result wxTicketOrder(Long userId, Long ticketsId, Integer buyNum, Integer payType, HttpServletRequest request) throws Exception { + Tickets tickets = ticketsService.getById(ticketsId); + PayDetails payDetails = new PayDetails(); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setState(0); + payDetails.setBuyNum(buyNum); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setUserId(userId); + payDetails.setMoney(tickets.getBuyMoney().multiply(new BigDecimal(buyNum)).doubleValue()); + payDetails.setClassify(payType); + payDetails.setType(6); + payDetails.setRelationId(ticketsId); + payDetailsDao.insert(payDetails); + return pay(payDetails.getMoney(), payType, userId, payDetails.getOrderId(), request, null); + } + + @Override + public Result payCoupon(Long userId, Long couponId, Integer buyNum, Integer payType, HttpServletRequest request) throws Exception { + TbCoupon tbCoupon = couponService.getById(couponId); + if (tbCoupon == null || tbCoupon.getIsEnable() == 0 || tbCoupon.getDeleteFlag() == 1) { + return Result.error("优惠券暂未出售或不存在"); + } + if (tbCoupon.getCouponType() != 2) { + return Result.error("当前优惠券不支持购买"); + } + //查看当前用户已购买或领取数量 + Integer num = couponUserService.count(new QueryWrapper().eq("user_id", userId).eq("coupon_id", couponId)); + if (tbCoupon.getMaxReceive() != 0) { + if ((tbCoupon.getMaxReceive() - num) <= buyNum) { + return Result.error("当前可购买或领取的数量已到达上限"); + } + } + BigDecimal totalPrice = tbCoupon.getBuyMoney().multiply(new BigDecimal(buyNum)); + PayDetails payDetails = new PayDetails(); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setState(0); + payDetails.setBuyNum(buyNum); + payDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + payDetails.setUserId(userId); + payDetails.setMoney(totalPrice.doubleValue()); + payDetails.setClassify(payType); + payDetails.setType(7); + payDetails.setRelationId(couponId); + payDetailsDao.insert(payDetails); + return pay(payDetails.getMoney(), payType, userId, payDetails.getOrderId(), request, null); + } + + @Override + public Result buyBucket(Integer num, Long userId, Integer classify, HttpServletRequest request) throws Exception { + CommonInfo bucket = commonInfoService.findOne(326); + BigDecimal money = new BigDecimal(num).multiply(new BigDecimal(bucket.getValue())); + PayDetails payDetails = new PayDetails(); + payDetails.setState(0); + payDetails.setCreateTime(sdf.format(new Date())); + payDetails.setOrderId(getGeneralOrder()); + payDetails.setUserId(userId); + payDetails.setMoney(money.doubleValue()); + payDetails.setClassify(classify); + payDetails.setType(8); + payDetails.setBuyNum(num); + payDetailsDao.insert(payDetails); + return pay(money.doubleValue(), classify, payDetails.getUserId(), payDetails.getOrderId(), request, null); + + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/search/Response/SearchResponse.java b/src/main/java/com/sqx/modules/search/Response/SearchResponse.java new file mode 100644 index 0000000..da91e63 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/Response/SearchResponse.java @@ -0,0 +1,22 @@ +package com.sqx.modules.search.Response; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SearchResponse implements Serializable { + + //用户的搜索记录 + List userSearchName = new ArrayList<>(); + //所有搜索记录前几名 + List AllSerchName = new ArrayList<>(); + + +} diff --git a/src/main/java/com/sqx/modules/search/controller/SearchController.java b/src/main/java/com/sqx/modules/search/controller/SearchController.java new file mode 100644 index 0000000..88d02d3 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/controller/SearchController.java @@ -0,0 +1,46 @@ +package com.sqx.modules.search.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.search.entity.Search; +import com.sqx.modules.search.service.SearchService; +import com.sqx.modules.sys.controller.AbstractController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "搜索记录", tags = {"搜索记录"}) +@RequestMapping(value = "/search") +public class SearchController extends AbstractController { + @Autowired + private SearchService searchService; + @PostMapping("/insertSearch") + @ApiOperation("记录搜索信息") + public Result insertSearch(@RequestBody Search search){ + return searchService.insertSearch(search); + } + @GetMapping("/selectByUserId") + @ApiOperation("查看搜索信息") + public Result selectByUserId(Long userId){ + return searchService.selectByUserId(userId); + } + + @GetMapping("/deleteById") + @ApiOperation("删除搜索信息") + public Result deleteById(Long id){ + return searchService.deleteById(id); + } + + + + + + + + + + + + +} diff --git a/src/main/java/com/sqx/modules/search/controller/app/AppSearchController.java b/src/main/java/com/sqx/modules/search/controller/app/AppSearchController.java new file mode 100644 index 0000000..e3b4f66 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/controller/app/AppSearchController.java @@ -0,0 +1,46 @@ +package com.sqx.modules.search.controller.app; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.app.entity.App; +import com.sqx.modules.search.entity.Search; +import com.sqx.modules.search.service.AppSearchService; +import com.sqx.modules.search.service.SearchService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +/** + * 搜索记录 + * + * @author liyuan + * @since 2021-07-17 + */ +@RestController +@RequestMapping("app/Search") +@AllArgsConstructor +@Slf4j +public class AppSearchController { + + private AppSearchService appSearchService; + /** + * 查询搜索记录 + */ + @CrossOrigin + @Login + @RequestMapping(value = "/selectAppSearchNum", method = RequestMethod.GET) + public Result selectAppSearchNum(@RequestAttribute Long userId) { + return appSearchService.selectAppSearchNum(userId); + } + + /** + * 删除用户的搜索记录 + */ + @Login + @RequestMapping(value = "/deleteAppSearch", method = RequestMethod.GET) + public Result deleteAppSearch(@RequestAttribute Long userId) { + return appSearchService.deleteAppSearch(userId); + } +} diff --git a/src/main/java/com/sqx/modules/search/dao/AppSearchDao.java b/src/main/java/com/sqx/modules/search/dao/AppSearchDao.java new file mode 100644 index 0000000..db4444a --- /dev/null +++ b/src/main/java/com/sqx/modules/search/dao/AppSearchDao.java @@ -0,0 +1,26 @@ +package com.sqx.modules.search.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.search.entity.Search; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +public interface AppSearchDao extends BaseMapper { + + /** + * 经常搜索的名称 + * + * @return + */ + List selectAppSearchNum(); + + /** + * 删除用户的搜索记录 + */ + int deleteAppSearch(Long userId); +} diff --git a/src/main/java/com/sqx/modules/search/dao/SearchDao.java b/src/main/java/com/sqx/modules/search/dao/SearchDao.java new file mode 100644 index 0000000..060cee4 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/dao/SearchDao.java @@ -0,0 +1,9 @@ +package com.sqx.modules.search.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.search.entity.Search; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface SearchDao extends BaseMapper { +} diff --git a/src/main/java/com/sqx/modules/search/entity/Search.java b/src/main/java/com/sqx/modules/search/entity/Search.java new file mode 100644 index 0000000..f3348e0 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/entity/Search.java @@ -0,0 +1,35 @@ +package com.sqx.modules.search.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +@Data +@TableName("search") +public class Search implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 搜索id + */ + @TableId(type = IdType.AUTO) + private Long searchId; + /** + * 搜索名称 + */ + private String searchName; + /** + * 用户 + */ + private Long userId; + + /** + * 更新时间 + */ + @TableField("update_time") + private String updateTime; + + public Search() {} +} diff --git a/src/main/java/com/sqx/modules/search/service/AppSearchService.java b/src/main/java/com/sqx/modules/search/service/AppSearchService.java new file mode 100644 index 0000000..38af0e3 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/service/AppSearchService.java @@ -0,0 +1,17 @@ +package com.sqx.modules.search.service; + +import com.sqx.common.utils.Result; +import com.sqx.modules.search.entity.Search; +import org.springframework.web.bind.annotation.RequestAttribute; + +/** + * app搜索 + */ +public interface AppSearchService { + + Result insetAppSearch(String searchName, Long userId); + + Result selectAppSearchNum(Long userId); + + Result deleteAppSearch( Long userId); +} diff --git a/src/main/java/com/sqx/modules/search/service/SearchService.java b/src/main/java/com/sqx/modules/search/service/SearchService.java new file mode 100644 index 0000000..9e27453 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/service/SearchService.java @@ -0,0 +1,11 @@ +package com.sqx.modules.search.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.search.entity.Search; + +public interface SearchService extends IService { + Result insertSearch(Search search); + Result selectByUserId(Long userId); + Result deleteById(Long id); +} diff --git a/src/main/java/com/sqx/modules/search/service/impl/AppSearchServiceImpl.java b/src/main/java/com/sqx/modules/search/service/impl/AppSearchServiceImpl.java new file mode 100644 index 0000000..84110bc --- /dev/null +++ b/src/main/java/com/sqx/modules/search/service/impl/AppSearchServiceImpl.java @@ -0,0 +1,106 @@ +package com.sqx.modules.search.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.search.Response.SearchResponse; +import com.sqx.modules.search.dao.AppSearchDao; +import com.sqx.modules.search.entity.Search; +import com.sqx.modules.search.service.AppSearchService; +import com.sqx.modules.search.service.SearchService; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Map; + + +@Service +@AllArgsConstructor +public class AppSearchServiceImpl extends ServiceImpl implements AppSearchService { + private AppSearchDao appSearchDao; + private SearchService searchService; + + /** + * 记录用户搜索的内容 + * + * + * @param userId + * @return + */ + @Override + public Result insetAppSearch(String searchName, Long userId) { + //判断传过来的搜索信息不为空 + if (searchName != null) { + //去查询用户搜索内容是否有重复 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("search_name", searchName); + queryWrapper.eq("user_id", userId); + Search search1 = baseMapper.selectOne(queryWrapper); + //有重复则更新改变时间 + if (search1 != null) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + search1.setUpdateTime(simpleDateFormat.format(new Date())); + int i = baseMapper.updateById(search1); + if (i > 0) { + return Result.success("更新成功!"); + } else { + return Result.error("更新失败!"); + } + } else { + //没有则记录 + Search search=new Search(); + search.setUserId(userId); + search.setSearchName(searchName); + int count = baseMapper.insert(search); + if (count > 0) { + return Result.success("记录成功!"); + } else { + return Result.error("记录失败!"); + } + } + + } else { + return Result.error("搜索信息为空!"); + } + } + + /** + * 经常搜索的名称 + * + * @return + */ + @Override + public Result selectAppSearchNum(Long userId) { + //经常搜索的名称 + List list = appSearchDao.selectAppSearchNum(); + //用户经常搜索的名称 + Result result = searchService.selectByUserId(userId); + //创建返回对象 + SearchResponse searchResponse = new SearchResponse(); + searchResponse.setAllSerchName(list); + List searches = (List) result.get("data"); + for (Search search : searches) { + searchResponse.getUserSearchName().add(search.getSearchName()); + } + + return Result.success().put("data", searchResponse); + } + + /** + * 删除用户的搜索记录 + * + * @param userId + * @return + */ + @Override + public Result deleteAppSearch(Long userId) { + appSearchDao.deleteAppSearch(userId); + return Result.success(); + } +} diff --git a/src/main/java/com/sqx/modules/search/service/impl/SearchServiceImpl.java b/src/main/java/com/sqx/modules/search/service/impl/SearchServiceImpl.java new file mode 100644 index 0000000..4f15b56 --- /dev/null +++ b/src/main/java/com/sqx/modules/search/service/impl/SearchServiceImpl.java @@ -0,0 +1,31 @@ +package com.sqx.modules.search.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.search.dao.SearchDao; +import com.sqx.modules.search.entity.Search; +import com.sqx.modules.search.service.SearchService; +import org.springframework.stereotype.Service; + +@Service +public class SearchServiceImpl extends ServiceImpl implements SearchService { + @Override + public Result insertSearch(Search search) { + baseMapper.insert(search); + return Result.success(); + } + + @Override + public Result selectByUserId(Long userId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("user_id",userId); + return Result.success().put("data",baseMapper.selectList(queryWrapper)); + } + + @Override + public Result deleteById(Long id) { + baseMapper.deleteById(id); + return Result.success(); + } +} diff --git a/src/main/java/com/sqx/modules/sys/controller/AbstractController.java b/src/main/java/com/sqx/modules/sys/controller/AbstractController.java new file mode 100644 index 0000000..b403433 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/AbstractController.java @@ -0,0 +1,22 @@ +package com.sqx.modules.sys.controller; + +import com.sqx.modules.sys.entity.SysUserEntity; +import org.apache.shiro.SecurityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Controller公共组件 + * + */ +public abstract class AbstractController { + protected Logger logger = LoggerFactory.getLogger(getClass()); + + protected SysUserEntity getUser() { + return (SysUserEntity) SecurityUtils.getSubject().getPrincipal(); + } + + protected Long getUserId() { + return getUser().getUserId(); + } +} diff --git a/src/main/java/com/sqx/modules/sys/controller/SysConfigController.java b/src/main/java/com/sqx/modules/sys/controller/SysConfigController.java new file mode 100644 index 0000000..5fe42ad --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/SysConfigController.java @@ -0,0 +1,89 @@ +package com.sqx.modules.sys.controller; + + +import com.sqx.common.annotation.SysLog; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.common.validator.ValidatorUtils; +import com.sqx.modules.sys.entity.SysConfigEntity; +import com.sqx.modules.sys.service.SysConfigService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * 系统配置信息 + * + */ +@RestController +@RequestMapping("/sys/config") +public class SysConfigController extends AbstractController { + @Autowired + private SysConfigService sysConfigService; + + /** + * 所有配置列表 + */ + @GetMapping("/list") + @RequiresPermissions("sys:config:list") + public Result list(@RequestParam Map params){ + PageUtils page = sysConfigService.queryPage(params); + + return Result.success().put("page", page); + } + + + /** + * 配置信息 + */ + @GetMapping("/info/{id}") + @RequiresPermissions("sys:config:info") + public Result info(@PathVariable("id") Long id){ + SysConfigEntity config = sysConfigService.getById(id); + + return Result.success().put("config", config); + } + + /** + * 保存配置 + */ + @SysLog("保存配置") + @PostMapping("/save") + @RequiresPermissions("sys:config:save") + public Result save(@RequestBody SysConfigEntity config){ + ValidatorUtils.validateEntity(config); + + sysConfigService.saveConfig(config); + + return Result.success(); + } + + /** + * 修改配置 + */ + @SysLog("修改配置") + @PostMapping("/update") + @RequiresPermissions("sys:config:update") + public Result update(@RequestBody SysConfigEntity config){ + ValidatorUtils.validateEntity(config); + + sysConfigService.update(config); + + return Result.success(); + } + + /** + * 删除配置 + */ + @SysLog("删除配置") + @PostMapping("/delete") + @RequiresPermissions("sys:config:delete") + public Result delete(@RequestBody Long[] ids){ + sysConfigService.deleteBatch(ids); + + return Result.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/sys/controller/SysDictController.java b/src/main/java/com/sqx/modules/sys/controller/SysDictController.java new file mode 100644 index 0000000..5f2213e --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/SysDictController.java @@ -0,0 +1,87 @@ +package com.sqx.modules.sys.controller; + +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.common.validator.ValidatorUtils; +import com.sqx.modules.sys.entity.SysDictEntity; +import com.sqx.modules.sys.service.SysDictService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; +import java.util.Map; + +/** + * 数据字典 + * + */ +@RestController +@RequestMapping("sys/dict") +public class SysDictController { + @Autowired + private SysDictService sysDictService; + + /** + * 列表 + */ + @RequestMapping("/list") + @RequiresPermissions("sys:dict:list") + public Result list(@RequestParam Map params){ + PageUtils page = sysDictService.queryPage(params); + + return Result.success().put("page", page); + } + + + /** + * 信息 + */ + @RequestMapping("/info/{id}") + @RequiresPermissions("sys:dict:info") + public Result info(@PathVariable("id") Long id){ + SysDictEntity dict = sysDictService.getById(id); + + return Result.success().put("dict", dict); + } + + /** + * 保存 + */ + @RequestMapping("/save") + @RequiresPermissions("sys:dict:save") + public Result save(@RequestBody SysDictEntity dict){ + //校验类型 + ValidatorUtils.validateEntity(dict); + + sysDictService.save(dict); + + return Result.success(); + } + + /** + * 修改 + */ + @RequestMapping("/update") + @RequiresPermissions("sys:dict:update") + public Result update(@RequestBody SysDictEntity dict){ + //校验类型 + ValidatorUtils.validateEntity(dict); + + sysDictService.updateById(dict); + + return Result.success(); + } + + /** + * 删除 + */ + @RequestMapping("/delete") + @RequiresPermissions("sys:dict:delete") + public Result delete(@RequestBody Long[] ids){ + sysDictService.removeByIds(Arrays.asList(ids)); + + return Result.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/sys/controller/SysLogController.java b/src/main/java/com/sqx/modules/sys/controller/SysLogController.java new file mode 100644 index 0000000..d7a08df --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/SysLogController.java @@ -0,0 +1,39 @@ +package com.sqx.modules.sys.controller; + +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.sys.service.SysLogService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +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.ResponseBody; + +import java.util.Map; + + +/** + * 系统日志 + * + */ +@Controller +@RequestMapping("/sys/log") +public class SysLogController { + @Autowired + private SysLogService sysLogService; + + /** + * 列表 + */ + @ResponseBody + @GetMapping("/list") + @RequiresPermissions("sys:log:list") + public Result list(@RequestParam Map params){ + PageUtils page = sysLogService.queryPage(params); + + return Result.success().put("page", page); + } + +} diff --git a/src/main/java/com/sqx/modules/sys/controller/SysLoginController.java b/src/main/java/com/sqx/modules/sys/controller/SysLoginController.java new file mode 100644 index 0000000..930ea58 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/SysLoginController.java @@ -0,0 +1,91 @@ +package com.sqx.modules.sys.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.form.SysLoginForm; +import com.sqx.modules.sys.service.SysCaptchaService; +import com.sqx.modules.sys.service.SysUserService; +import com.sqx.modules.sys.service.SysUserTokenService; +import org.apache.commons.io.IOUtils; +import org.apache.shiro.crypto.hash.Sha256Hash; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.imageio.ImageIO; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.util.Map; + +/** + * 登录相关 + * + */ +@RestController +public class SysLoginController extends AbstractController { + @Autowired + private SysUserService sysUserService; + @Autowired + private SysUserTokenService sysUserTokenService; + @Autowired + private SysCaptchaService sysCaptchaService; + + /** + * 验证码 + */ + @GetMapping("captcha.jpg") + public void captcha(HttpServletResponse response, String uuid)throws IOException { + response.setHeader("Cache-Control", "no-store, no-cache"); + response.setContentType("image/jpeg"); + + //获取图片验证码 + BufferedImage image = sysCaptchaService.getCaptcha(uuid); + + ServletOutputStream out = response.getOutputStream(); + ImageIO.write(image, "jpg", out); + IOUtils.closeQuietly(out); + } + + /** + * 登录 + */ + @PostMapping("/sys/login") + public Map login(@RequestBody SysLoginForm form)throws IOException { + boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha()); + if(!captcha){ + return Result.error("验证码不正确"); + } + + //用户信息 + SysUserEntity user = sysUserService.queryByUserName(form.getUsername()); + + //账号不存在、密码错误 + if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) { + return Result.error("账号或密码不正确"); + } + + //账号锁定 + if(user.getStatus() == 0){ + return Result.error("账号已被锁定,请联系管理员"); + } + + //生成token,并保存到数据库 + Result r = sysUserTokenService.createToken(user.getUserId()); + return r; + } + + + /** + * 退出 + */ + @PostMapping("/sys/logout") + public Result logout() { + sysUserTokenService.logout(getUserId()); + return Result.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/sys/controller/SysMenuController.java b/src/main/java/com/sqx/modules/sys/controller/SysMenuController.java new file mode 100644 index 0000000..3f876eb --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/SysMenuController.java @@ -0,0 +1,183 @@ +package com.sqx.modules.sys.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.annotation.SysLog; +import com.sqx.common.exception.SqxException; +import com.sqx.common.utils.Constant; +import com.sqx.common.utils.Result; +import com.sqx.modules.sys.entity.SysMenuEntity; +import com.sqx.modules.sys.service.ShiroService; +import com.sqx.modules.sys.service.SysMenuService; +import org.apache.commons.lang.StringUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Set; + +/** + * 系统菜单 + * + */ +@RestController +@RequestMapping("/sys/menu") +public class SysMenuController extends AbstractController { + @Autowired + private SysMenuService sysMenuService; + @Autowired + private ShiroService shiroService; + + /** + * 导航菜单 + */ + @GetMapping("/nav") + public Result nav(){ + List menuList = sysMenuService.getUserMenuList(getUserId()); + Set permissions = shiroService.getUserPermissions(getUserId()); + return Result.success().put("menuList", menuList).put("permissions", permissions); + } + + /** + * 所有菜单列表 + */ + @GetMapping("/list") + @RequiresPermissions("sys:menu:list") + public List list(){ + List menuList = sysMenuService.list(new QueryWrapper().orderByAsc("order_num")); + for(SysMenuEntity sysMenuEntity : menuList){ + SysMenuEntity parentMenuEntity = sysMenuService.getById(sysMenuEntity.getParentId()); + if(parentMenuEntity != null){ + sysMenuEntity.setParentName(parentMenuEntity.getName()); + } + } + + return menuList; + } + + /** + * 选择菜单(添加、修改菜单) + */ + @GetMapping("/select") + @RequiresPermissions("sys:menu:select") + public Result select(){ + //查询列表数据 + List menuList = sysMenuService.queryNotButtonList(); + + //添加顶级菜单 + SysMenuEntity root = new SysMenuEntity(); + root.setMenuId(0L); + root.setName("一级菜单"); + root.setParentId(-1L); + root.setOpen(true); + menuList.add(root); + + return Result.success().put("menuList", menuList); + } + + /** + * 菜单信息 + */ + @GetMapping("/info/{menuId}") + @RequiresPermissions("sys:menu:info") + public Result info(@PathVariable("menuId") Long menuId){ + SysMenuEntity menu = sysMenuService.getById(menuId); + return Result.success().put("menu", menu); + } + + /** + * 保存 + */ + @SysLog("保存菜单") + @PostMapping("/save") + @RequiresPermissions("sys:menu:save") + public Result save(@RequestBody SysMenuEntity menu){ + //数据校验 + verifyForm(menu); + + sysMenuService.save(menu); + + return Result.success(); + } + + /** + * 修改 + */ + @SysLog("修改菜单") + @PostMapping("/update") + @RequiresPermissions("sys:menu:update") + public Result update(@RequestBody SysMenuEntity menu){ + //数据校验 + verifyForm(menu); + + sysMenuService.updateById(menu); + + return Result.success(); + } + + /** + * 删除 + */ + @SysLog("删除菜单") + @PostMapping("/delete/{menuId}") + @RequiresPermissions("sys:menu:delete") + public Result delete(@PathVariable("menuId") long menuId){ + if(menuId <= 31){ + return Result.error("系统菜单,不能删除"); + } + + //判断是否有子菜单或按钮 + List menuList = sysMenuService.queryListParentId(menuId); + if(menuList.size() > 0){ + return Result.error("请先删除子菜单或按钮"); + } + + sysMenuService.delete(menuId); + + return Result.success(); + } + + /** + * 验证参数是否正确 + */ + private void verifyForm(SysMenuEntity menu){ + if(StringUtils.isBlank(menu.getName())){ + throw new SqxException("菜单名称不能为空"); + } + + if(menu.getParentId() == null){ + throw new SqxException("上级菜单不能为空"); + } + + //菜单 + if(menu.getType() == Constant.MenuType.MENU.getValue()){ + if(StringUtils.isBlank(menu.getUrl())){ + throw new SqxException("菜单URL不能为空"); + } + } + + //上级菜单类型 + int parentType = Constant.MenuType.CATALOG.getValue(); + if(menu.getParentId() != 0){ + SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId()); + parentType = parentMenu.getType(); + } + + //目录、菜单 + if(menu.getType() == Constant.MenuType.CATALOG.getValue() || + menu.getType() == Constant.MenuType.MENU.getValue()){ + if(parentType != Constant.MenuType.CATALOG.getValue()){ + throw new SqxException("上级菜单只能为目录类型"); + } + return ; + } + + //按钮 + if(menu.getType() == Constant.MenuType.BUTTON.getValue()){ + if(parentType != Constant.MenuType.MENU.getValue()){ + throw new SqxException("上级菜单只能为菜单类型"); + } + return ; + } + } +} diff --git a/src/main/java/com/sqx/modules/sys/controller/SysRoleController.java b/src/main/java/com/sqx/modules/sys/controller/SysRoleController.java new file mode 100644 index 0000000..88db465 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/SysRoleController.java @@ -0,0 +1,117 @@ +package com.sqx.modules.sys.controller; + +import com.sqx.common.annotation.SysLog; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.common.validator.ValidatorUtils; +import com.sqx.modules.sys.entity.SysRoleEntity; +import com.sqx.modules.sys.service.SysRoleMenuService; +import com.sqx.modules.sys.service.SysRoleService; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 角色管理 + * + */ +@RestController +@RequestMapping("/sys/role") +public class SysRoleController extends AbstractController { + @Autowired + private SysRoleService sysRoleService; + @Autowired + private SysRoleMenuService sysRoleMenuService; + + /** + * 角色列表 + */ + @GetMapping("/list") + @RequiresPermissions("sys:role:list") + public Result list(@RequestParam Map params){ + //如果不是超级管理员,则只查询自己创建的角色列表 + /*if(getUserId() != Constant.SUPER_ADMIN){ + params.put("createUserId", getUserId()); + }*/ + PageUtils page = sysRoleService.queryPage(params); + return Result.success().put("page", page); + } + + /** + * 角色列表 + */ + @GetMapping("/select") + @RequiresPermissions("sys:role:select") + public Result select(){ + Map map = new HashMap<>(); + + //如果不是超级管理员,则只查询自己所拥有的角色列表 + /*if(getUserId() != Constant.SUPER_ADMIN){ + map.put("create_user_id", getUserId()); + }*/ + List list = (List) sysRoleService.listByMap(map); + + return Result.success().put("list", list); + } + + /** + * 角色信息 + */ + @GetMapping("/info/{roleId}") + @RequiresPermissions("sys:role:info") + public Result info(@PathVariable("roleId") Long roleId){ + SysRoleEntity role = sysRoleService.getById(roleId); + + //查询角色对应的菜单 + List menuIdList = sysRoleMenuService.queryMenuIdList(roleId); + role.setMenuIdList(menuIdList); + + return Result.success().put("role", role); + } + + /** + * 保存角色 + */ + @SysLog("保存角色") + @PostMapping("/save") + @RequiresPermissions("sys:role:save") + public Result save(@RequestBody SysRoleEntity role){ + ValidatorUtils.validateEntity(role); + + role.setCreateUserId(getUserId()); + sysRoleService.saveRole(role); + + return Result.success(); + } + + /** + * 修改角色 + */ + @SysLog("修改角色") + @PostMapping("/update") + @RequiresPermissions("sys:role:update") + public Result update(@RequestBody SysRoleEntity role){ + ValidatorUtils.validateEntity(role); + + role.setCreateUserId(getUserId()); + sysRoleService.update(role); + + return Result.success(); + } + + /** + * 删除角色 + */ + @SysLog("删除角色") + @PostMapping("/delete") + @RequiresPermissions("sys:role:delete") + public Result delete(@RequestBody Long[] roleIds){ + sysRoleService.deleteBatch(roleIds); + + return Result.success(); + } +} diff --git a/src/main/java/com/sqx/modules/sys/controller/SysUserController.java b/src/main/java/com/sqx/modules/sys/controller/SysUserController.java new file mode 100644 index 0000000..4783e37 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/controller/SysUserController.java @@ -0,0 +1,145 @@ +package com.sqx.modules.sys.controller; + +import com.sqx.common.annotation.SysLog; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.common.validator.Assert; +import com.sqx.common.validator.ValidatorUtils; +import com.sqx.common.validator.group.AddGroup; +import com.sqx.common.validator.group.UpdateGroup; +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.form.PasswordForm; +import com.sqx.modules.sys.service.SysUserRoleService; +import com.sqx.modules.sys.service.SysUserService; +import org.apache.commons.lang.ArrayUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.apache.shiro.crypto.hash.Sha256Hash; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +/** + * 系统用户 + * + */ +@RestController +@RequestMapping("/sys/user") +public class SysUserController extends AbstractController { + @Autowired + private SysUserService sysUserService; + @Autowired + private SysUserRoleService sysUserRoleService; + + + /** + * 所有用户列表 + */ + @GetMapping("/list") + @RequiresPermissions("sys:user:list") + public Result list(@RequestParam Map params){ + //只有超级管理员,才能查看所有管理员列表 + /*if(getUserId() != Constant.SUPER_ADMIN){ + params.put("createUserId", getUserId()); + }*/ + PageUtils page = sysUserService.queryPage(params); + + return Result.success().put("page", page); + } + + /** + * 获取登录的用户信息 + */ + @GetMapping("/info") + public Result info(){ + return Result.success().put("user", getUser()); + } + + /** + * 修改登录用户密码 + */ + @SysLog("修改密码") + @PostMapping("/password") + public Result password(@RequestBody PasswordForm form){ + Assert.isBlank(form.getNewPassword(), "新密码不为能空"); + + //sha256加密 + String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex(); + //sha256加密 + String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex(); + + //更新密码 + boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword); + if(!flag){ + return Result.error("原密码不正确"); + } + + return Result.success(); + } + + /** + * 用户信息 + */ + @GetMapping("/info/{userId}") + @RequiresPermissions("sys:user:info") + public Result info(@PathVariable("userId") Long userId){ + SysUserEntity user = sysUserService.getById(userId); + + //获取用户所属的角色列表 + List roleIdList = sysUserRoleService.queryRoleIdList(userId); + user.setRoleIdList(roleIdList); + + return Result.success().put("user", user); + } + + /** + * 保存用户 + */ + @SysLog("保存用户") + @PostMapping("/save") + @RequiresPermissions("sys:user:save") + public Result save(@RequestBody SysUserEntity user){ + ValidatorUtils.validateEntity(user, AddGroup.class); + + user.setCreateUserId(getUserId()); + sysUserService.saveUser(user); + + return Result.success(); + } + + /** + * 修改用户 + */ + @SysLog("修改用户") + @PostMapping("/update") + @RequiresPermissions("sys:user:update") + public Result update(@RequestBody SysUserEntity user){ + ValidatorUtils.validateEntity(user, UpdateGroup.class); + + user.setCreateUserId(getUserId()); + sysUserService.update(user); + + return Result.success(); + } + + /** + * 删除用户 + */ + @SysLog("删除用户") + @PostMapping("/delete") + @RequiresPermissions("sys:user:delete") + public Result delete(@RequestBody Long[] userIds){ + if(ArrayUtils.contains(userIds, 1L)){ + return Result.error("系统管理员不能删除"); + } + + if(ArrayUtils.contains(userIds, getUserId())){ + return Result.error("当前用户不能删除"); + } + + sysUserService.deleteBatch(userIds); + + return Result.success(); + } +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysCaptchaDao.java b/src/main/java/com/sqx/modules/sys/dao/SysCaptchaDao.java new file mode 100644 index 0000000..402e1a2 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysCaptchaDao.java @@ -0,0 +1,14 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysCaptchaEntity; +import org.apache.ibatis.annotations.Mapper; + +/** + * 验证码 + * + */ +@Mapper +public interface SysCaptchaDao extends BaseMapper { + +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysConfigDao.java b/src/main/java/com/sqx/modules/sys/dao/SysConfigDao.java new file mode 100644 index 0000000..2ed6515 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysConfigDao.java @@ -0,0 +1,26 @@ +package com.sqx.modules.sys.dao; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysConfigEntity; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + * 系统配置信息 + * + */ +@Mapper +public interface SysConfigDao extends BaseMapper { + + /** + * 根据key,查询value + */ + SysConfigEntity queryByKey(String paramKey); + + /** + * 根据key,更新value + */ + int updateValueByKey(@Param("paramKey") String paramKey, @Param("paramValue") String paramValue); + +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysDictDao.java b/src/main/java/com/sqx/modules/sys/dao/SysDictDao.java new file mode 100644 index 0000000..47d22ba --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysDictDao.java @@ -0,0 +1,14 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysDictEntity; +import org.apache.ibatis.annotations.Mapper; + +/** + * 数据字典 + * + */ +@Mapper +public interface SysDictDao extends BaseMapper { + +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysLogDao.java b/src/main/java/com/sqx/modules/sys/dao/SysLogDao.java new file mode 100644 index 0000000..2e78f97 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysLogDao.java @@ -0,0 +1,15 @@ +package com.sqx.modules.sys.dao; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysLogEntity; +import org.apache.ibatis.annotations.Mapper; + +/** + * 系统日志 + * + */ +@Mapper +public interface SysLogDao extends BaseMapper { + +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysMenuDao.java b/src/main/java/com/sqx/modules/sys/dao/SysMenuDao.java new file mode 100644 index 0000000..0510df4 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysMenuDao.java @@ -0,0 +1,27 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysMenuEntity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 菜单管理 + * + */ +@Mapper +public interface SysMenuDao extends BaseMapper { + + /** + * 根据父菜单,查询子菜单 + * @param parentId 父菜单ID + */ + List queryListParentId(Long parentId); + + /** + * 获取不包含按钮的菜单列表 + */ + List queryNotButtonList(); + +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysRoleDao.java b/src/main/java/com/sqx/modules/sys/dao/SysRoleDao.java new file mode 100644 index 0000000..e8b4576 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysRoleDao.java @@ -0,0 +1,20 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysRoleEntity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 角色管理 + * + */ +@Mapper +public interface SysRoleDao extends BaseMapper { + + /** + * 查询用户创建的角色ID列表 + */ + List queryRoleIdList(Long createUserId); +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysRoleMenuDao.java b/src/main/java/com/sqx/modules/sys/dao/SysRoleMenuDao.java new file mode 100644 index 0000000..2716b21 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysRoleMenuDao.java @@ -0,0 +1,25 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysRoleMenuEntity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 角色与菜单对应关系 + * + */ +@Mapper +public interface SysRoleMenuDao extends BaseMapper { + + /** + * 根据角色ID,获取菜单ID列表 + */ + List queryMenuIdList(Long roleId); + + /** + * 根据角色ID数组,批量删除 + */ + int deleteBatch(Long[] roleIds); +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysUserDao.java b/src/main/java/com/sqx/modules/sys/dao/SysUserDao.java new file mode 100644 index 0000000..b21c796 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysUserDao.java @@ -0,0 +1,32 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysUserEntity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 系统用户 + * + */ +@Mapper +public interface SysUserDao extends BaseMapper { + + /** + * 查询用户的所有权限 + * @param userId 用户ID + */ + List queryAllPerms(Long userId); + + /** + * 查询用户的所有菜单ID + */ + List queryAllMenuId(Long userId); + + /** + * 根据用户名,查询系统用户 + */ + SysUserEntity queryByUserName(String username); + +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysUserRoleDao.java b/src/main/java/com/sqx/modules/sys/dao/SysUserRoleDao.java new file mode 100644 index 0000000..b0d82b7 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysUserRoleDao.java @@ -0,0 +1,26 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysUserRoleEntity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 用户与角色对应关系 + * + */ +@Mapper +public interface SysUserRoleDao extends BaseMapper { + + /** + * 根据用户ID,获取角色ID列表 + */ + List queryRoleIdList(Long userId); + + + /** + * 根据角色ID数组,批量删除 + */ + int deleteBatch(Long[] roleIds); +} diff --git a/src/main/java/com/sqx/modules/sys/dao/SysUserTokenDao.java b/src/main/java/com/sqx/modules/sys/dao/SysUserTokenDao.java new file mode 100644 index 0000000..6df7ec8 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/dao/SysUserTokenDao.java @@ -0,0 +1,16 @@ +package com.sqx.modules.sys.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.sys.entity.SysUserTokenEntity; +import org.apache.ibatis.annotations.Mapper; + +/** + * 系统用户Token + * + */ +@Mapper +public interface SysUserTokenDao extends BaseMapper { + + SysUserTokenEntity queryByToken(String token); + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysCaptchaEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysCaptchaEntity.java new file mode 100644 index 0000000..4b8de05 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysCaptchaEntity.java @@ -0,0 +1,28 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.util.Date; + +/** + * 系统验证码 + * + */ +@Data +@TableName("sys_captcha") +public class SysCaptchaEntity { + @TableId(type = IdType.INPUT) + private String uuid; + /** + * 验证码 + */ + private String code; + /** + * 过期时间 + */ + private Date expireTime; + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysConfigEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysConfigEntity.java new file mode 100644 index 0000000..6ca6d53 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysConfigEntity.java @@ -0,0 +1,24 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * 系统配置信息 + * + */ +@Data +@TableName("sys_config") +public class SysConfigEntity { + @TableId + private Long id; + @NotBlank(message="参数名不能为空") + private String paramKey; + @NotBlank(message="参数值不能为空") + private String paramValue; + private String remark; + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysDictEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysDictEntity.java new file mode 100644 index 0000000..3cc548a --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysDictEntity.java @@ -0,0 +1,56 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * 数据字典 + * + */ +@Data +@TableName("sys_dict") +public class SysDictEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @TableId + private Long id; + /** + * 字典名称 + */ + @NotBlank(message="字典名称不能为空") + private String name; + /** + * 字典类型 + */ + @NotBlank(message="字典类型不能为空") + private String type; + /** + * 字典码 + */ + @NotBlank(message="字典码不能为空") + private String code; + /** + * 字典值 + */ + @NotBlank(message="字典值不能为空") + private String value; + /** + * 排序 + */ + private Integer orderNum; + /** + * 备注 + */ + private String remark; + /** + * 删除标记 -1:已删除 0:正常 + */ + @TableLogic + private Integer delFlag; + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysLogEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysLogEntity.java new file mode 100644 index 0000000..1239aff --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysLogEntity.java @@ -0,0 +1,36 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + + +/** + * 系统日志 + * + */ +@Data +@TableName("sys_log") +public class SysLogEntity implements Serializable { + private static final long serialVersionUID = 1L; + @TableId + private Long id; + //用户名 + private String username; + //用户操作 + private String operation; + //请求方法 + private String method; + //请求参数 + private String params; + //执行时长(毫秒) + private Long time; + //IP地址 + private String ip; + //创建时间 + private Date createDate; + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysMenuEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysMenuEntity.java new file mode 100644 index 0000000..410cbdb --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysMenuEntity.java @@ -0,0 +1,76 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * 菜单管理 + * + */ +@Data +@TableName("sys_menu") +public class SysMenuEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 菜单ID + */ + @TableId + private Long menuId; + + /** + * 父菜单ID,一级菜单为0 + */ + private Long parentId; + + /** + * 父菜单名称 + */ + @TableField(exist=false) + private String parentName; + + /** + * 菜单名称 + */ + private String name; + + /** + * 菜单URL + */ + private String url; + + /** + * 授权(多个用逗号分隔,如:user:list,user:create) + */ + private String perms; + + /** + * 类型 0:目录 1:菜单 2:按钮 + */ + private Integer type; + + /** + * 菜单图标 + */ + private String icon; + + /** + * 排序 + */ + private Integer orderNum; + + /** + * ztree属性 + */ + @TableField(exist=false) + private Boolean open; + + @TableField(exist=false) + private List list; + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysRoleEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysRoleEntity.java new file mode 100644 index 0000000..bd5f074 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysRoleEntity.java @@ -0,0 +1,53 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * 角色 + * + */ +@Data +@TableName("sys_role") +public class SysRoleEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 角色ID + */ + @TableId + private Long roleId; + + /** + * 角色名称 + */ + @NotBlank(message="角色名称不能为空") + private String roleName; + + /** + * 备注 + */ + private String remark; + + /** + * 创建者ID + */ + private Long createUserId; + + @TableField(exist=false) + private List menuIdList; + + /** + * 创建时间 + */ + private Date createTime; + + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysRoleMenuEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysRoleMenuEntity.java new file mode 100644 index 0000000..dcdce80 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysRoleMenuEntity.java @@ -0,0 +1,31 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * 角色与菜单对应关系 + * + */ +@Data +@TableName("sys_role_menu") +public class SysRoleMenuEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @TableId + private Long id; + + /** + * 角色ID + */ + private Long roleId; + + /** + * 菜单ID + */ + private Long menuId; + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysUserEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysUserEntity.java new file mode 100644 index 0000000..46362be --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysUserEntity.java @@ -0,0 +1,98 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.sqx.common.validator.group.AddGroup; +import com.sqx.common.validator.group.UpdateGroup; +import com.sqx.modules.laundry.model.Laundry; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * 系统用户 + * + */ +@Data +@TableName("sys_user") +public class SysUserEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 用户ID + */ + @TableId + private Long userId; + + /** + * 用户名 + */ + @NotBlank(message="用户名不能为空", groups = {AddGroup.class, UpdateGroup.class}) + private String username; + + /** + * 密码 + */ + @NotBlank(message="密码不能为空", groups = AddGroup.class) + private String password; + + /** + * 盐 + */ + private String salt; + + /** + * 邮箱 + */ + @NotBlank(message="邮箱不能为空", groups = {AddGroup.class, UpdateGroup.class}) + @Email(message="邮箱格式不正确", groups = {AddGroup.class, UpdateGroup.class}) + private String email; + + /** + * 手机号 + */ + private String mobile; + + /** + * 状态 0:禁用 1:正常 + */ + private Integer status; + + /** + * 角色ID列表 + */ + @TableField(exist=false) + private List roleIdList; + + /** + * 创建者ID + */ + private Long createUserId; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 是否是站点管理员 1是 + */ + private Integer isLaundry; + + /** + * 站点id + */ + private Long laundryId; + + @TableField(exist = false) + private Laundry laundry; + + + + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysUserRoleEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysUserRoleEntity.java new file mode 100644 index 0000000..ba913a6 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysUserRoleEntity.java @@ -0,0 +1,31 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * 用户与角色对应关系 + * + */ +@Data +@TableName("sys_user_role") +public class SysUserRoleEntity implements Serializable { + private static final long serialVersionUID = 1L; + @TableId + private Long id; + + /** + * 用户ID + */ + private Long userId; + + /** + * 角色ID + */ + private Long roleId; + + +} diff --git a/src/main/java/com/sqx/modules/sys/entity/SysUserTokenEntity.java b/src/main/java/com/sqx/modules/sys/entity/SysUserTokenEntity.java new file mode 100644 index 0000000..d5e9ffd --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/entity/SysUserTokenEntity.java @@ -0,0 +1,31 @@ +package com.sqx.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + + +/** + * 系统用户Token + * + */ +@Data +@TableName("sys_user_token") +public class SysUserTokenEntity implements Serializable { + private static final long serialVersionUID = 1L; + + //用户ID + @TableId(type = IdType.INPUT) + private Long userId; + //token + private String token; + //过期时间 + private Date expireTime; + //更新时间 + private Date updateTime; + +} diff --git a/src/main/java/com/sqx/modules/sys/form/PasswordForm.java b/src/main/java/com/sqx/modules/sys/form/PasswordForm.java new file mode 100644 index 0000000..e10a377 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/form/PasswordForm.java @@ -0,0 +1,20 @@ +package com.sqx.modules.sys.form; + +import lombok.Data; + +/** + * 密码表单 + * + */ +@Data +public class PasswordForm { + /** + * 原密码 + */ + private String password; + /** + * 新密码 + */ + private String newPassword; + +} diff --git a/src/main/java/com/sqx/modules/sys/form/SysLoginForm.java b/src/main/java/com/sqx/modules/sys/form/SysLoginForm.java new file mode 100644 index 0000000..46efd2d --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/form/SysLoginForm.java @@ -0,0 +1,17 @@ +package com.sqx.modules.sys.form; + +import lombok.Data; + +/** + * 登录表单 + * + */ +@Data +public class SysLoginForm { + private String username; + private String password; + private String captcha; + private String uuid; + + +} diff --git a/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Filter.java b/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Filter.java new file mode 100644 index 0000000..43e9437 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Filter.java @@ -0,0 +1,101 @@ +package com.sqx.modules.sys.oauth2; + +import com.google.gson.Gson; +import com.sqx.common.utils.HttpContextUtils; +import com.sqx.common.utils.Result; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpStatus; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.web.filter.authc.AuthenticatingFilter; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * oauth2过滤器 + * + */ +public class OAuth2Filter extends AuthenticatingFilter { + + @Override + protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception { + //获取请求token + String token = getRequestToken((HttpServletRequest) request); + + if(StringUtils.isBlank(token)){ + return null; + } + + return new OAuth2Token(token); + } + + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { + if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){ + return true; + } + + return false; + } + + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + //获取请求token,如果token不存在,直接返回401 + String token = getRequestToken((HttpServletRequest) request); + if(StringUtils.isBlank(token)){ + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); + httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); + + String json = new Gson().toJson(Result.error(HttpStatus.SC_UNAUTHORIZED, "invalid token")); + + httpResponse.getWriter().print(json); + + return false; + } + + return executeLogin(request, response); + } + + @Override + protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.setContentType("application/json;charset=utf-8"); + httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); + httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); + try { + //处理登录失败的异常 + Throwable throwable = e.getCause() == null ? e : e.getCause(); + Result r = Result.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage()); + + String json = new Gson().toJson(r); + httpResponse.getWriter().print(json); + } catch (IOException e1) { + + } + + return false; + } + + /** + * 获取请求的token + */ + private String getRequestToken(HttpServletRequest httpRequest){ + //从header中获取token + String token = httpRequest.getHeader("token"); + + //如果header中不存在token,则从参数中获取token + if(StringUtils.isBlank(token)){ + token = httpRequest.getParameter("token"); + } + + return token; + } + + +} diff --git a/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Realm.java b/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Realm.java new file mode 100644 index 0000000..4f1adee --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Realm.java @@ -0,0 +1,70 @@ +package com.sqx.modules.sys.oauth2; + +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.entity.SysUserTokenEntity; +import com.sqx.modules.sys.service.ShiroService; +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Set; + +/** + * 认证 + * + */ +@Component +public class OAuth2Realm extends AuthorizingRealm { + @Autowired + private ShiroService shiroService; + + @Override + public boolean supports(AuthenticationToken token) { + return token instanceof OAuth2Token; + } + + /** + * 授权(验证权限时调用) + */ + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal(); + Long userId = user.getUserId(); + + //用户权限列表 + Set permsSet = shiroService.getUserPermissions(userId); + + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); + info.setStringPermissions(permsSet); + return info; + } + + /** + * 认证(登录时调用) + */ + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { + String accessToken = (String) token.getPrincipal(); + + //根据accessToken,查询用户信息 + SysUserTokenEntity tokenEntity = shiroService.queryByToken(accessToken); + //token失效 + if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){ + throw new IncorrectCredentialsException("token失效,请重新登录"); + } + + //查询用户信息 + SysUserEntity user = shiroService.queryUser(tokenEntity.getUserId()); + //账号锁定 + if(user.getStatus() == 0){ + throw new LockedAccountException("账号已被锁定,请联系管理员"); + } + + SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName()); + return info; + } +} diff --git a/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Token.java b/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Token.java new file mode 100644 index 0000000..67fac8c --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/oauth2/OAuth2Token.java @@ -0,0 +1,26 @@ +package com.sqx.modules.sys.oauth2; + + +import org.apache.shiro.authc.AuthenticationToken; + +/** + * token + * + */ +public class OAuth2Token implements AuthenticationToken { + private String token; + + public OAuth2Token(String token){ + this.token = token; + } + + @Override + public String getPrincipal() { + return token; + } + + @Override + public Object getCredentials() { + return token; + } +} diff --git a/src/main/java/com/sqx/modules/sys/oauth2/TokenGenerator.java b/src/main/java/com/sqx/modules/sys/oauth2/TokenGenerator.java new file mode 100644 index 0000000..527154b --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/oauth2/TokenGenerator.java @@ -0,0 +1,43 @@ +package com.sqx.modules.sys.oauth2; + +import com.sqx.common.exception.SqxException; + +import java.security.MessageDigest; +import java.util.UUID; + +/** + * 生成token + * + */ +public class TokenGenerator { + + public static String generateValue() { + return generateValue(UUID.randomUUID().toString()); + } + + private static final char[] HexCode = "0123456789abcdef".toCharArray(); + + public static String toHexString(byte[] data) { + if(data == null) { + return null; + } + StringBuilder r = new StringBuilder(data.length*2); + for ( byte b : data) { + r.append(HexCode[(b >> 4) & 0xF]); + r.append(HexCode[(b & 0xF)]); + } + return r.toString(); + } + + public static String generateValue(String param) { + try { + MessageDigest algorithm = MessageDigest.getInstance("MD5"); + algorithm.reset(); + algorithm.update(param.getBytes()); + byte[] messageDigest = algorithm.digest(); + return toHexString(messageDigest); + } catch (Exception e) { + throw new SqxException("生成Token失败", e); + } + } +} diff --git a/src/main/java/com/sqx/modules/sys/redis/SysConfigRedis.java b/src/main/java/com/sqx/modules/sys/redis/SysConfigRedis.java new file mode 100644 index 0000000..6336a4c --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/redis/SysConfigRedis.java @@ -0,0 +1,36 @@ +package com.sqx.modules.sys.redis; + + +import com.sqx.common.utils.RedisKeys; +import com.sqx.common.utils.RedisUtils; +import com.sqx.modules.sys.entity.SysConfigEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * 系统配置Redis + * + */ +@Component +public class SysConfigRedis { + @Autowired + private RedisUtils redisUtils; + + public void saveOrUpdate(SysConfigEntity config) { + if(config == null){ + return ; + } + String key = RedisKeys.getSysConfigKey(config.getParamKey()); + redisUtils.set(key, config); + } + + public void delete(String configKey) { + String key = RedisKeys.getSysConfigKey(configKey); + redisUtils.delete(key); + } + + public SysConfigEntity get(String configKey){ + String key = RedisKeys.getSysConfigKey(configKey); + return redisUtils.get(key, SysConfigEntity.class); + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/ShiroService.java b/src/main/java/com/sqx/modules/sys/service/ShiroService.java new file mode 100644 index 0000000..1eb275f --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/ShiroService.java @@ -0,0 +1,25 @@ +package com.sqx.modules.sys.service; + +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.entity.SysUserTokenEntity; + +import java.util.Set; + +/** + * shiro相关接口 + * + */ +public interface ShiroService { + /** + * 获取用户权限列表 + */ + Set getUserPermissions(long userId); + + SysUserTokenEntity queryByToken(String token); + + /** + * 根据用户ID,查询用户 + * @param userId + */ + SysUserEntity queryUser(Long userId); +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysCaptchaService.java b/src/main/java/com/sqx/modules/sys/service/SysCaptchaService.java new file mode 100644 index 0000000..3a47f89 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysCaptchaService.java @@ -0,0 +1,26 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.sys.entity.SysCaptchaEntity; + +import java.awt.image.BufferedImage; + +/** + * 验证码 + * + */ +public interface SysCaptchaService extends IService { + + /** + * 获取图片验证码 + */ + BufferedImage getCaptcha(String uuid); + + /** + * 验证码效验 + * @param uuid uuid + * @param code 验证码 + * @return true:成功 false:失败 + */ + boolean validate(String uuid, String code); +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysConfigService.java b/src/main/java/com/sqx/modules/sys/service/SysConfigService.java new file mode 100644 index 0000000..5becf42 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysConfigService.java @@ -0,0 +1,51 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.sys.entity.SysConfigEntity; + +import java.util.Map; + +/** + * 系统配置信息 + * + */ +public interface SysConfigService extends IService { + + PageUtils queryPage(Map params); + + /** + * 保存配置信息 + */ + public void saveConfig(SysConfigEntity config); + + /** + * 更新配置信息 + */ + public void update(SysConfigEntity config); + + /** + * 根据key,更新value + */ + public void updateValueByKey(String key, String value); + + /** + * 删除配置信息 + */ + public void deleteBatch(Long[] ids); + + /** + * 根据key,获取配置的value值 + * + * @param key key + */ + public String getValue(String key); + + /** + * 根据key,获取value的Object对象 + * @param key key + * @param clazz Object对象 + */ + public T getConfigObject(String key, Class clazz); + +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysDictService.java b/src/main/java/com/sqx/modules/sys/service/SysDictService.java new file mode 100644 index 0000000..e64044c --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysDictService.java @@ -0,0 +1,17 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.sys.entity.SysDictEntity; + +import java.util.Map; + +/** + * 数据字典 + * + */ +public interface SysDictService extends IService { + + PageUtils queryPage(Map params); +} + diff --git a/src/main/java/com/sqx/modules/sys/service/SysLogService.java b/src/main/java/com/sqx/modules/sys/service/SysLogService.java new file mode 100644 index 0000000..f24f42c --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysLogService.java @@ -0,0 +1,19 @@ +package com.sqx.modules.sys.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.sys.entity.SysLogEntity; + +import java.util.Map; + + +/** + * 系统日志 + * + */ +public interface SysLogService extends IService { + + PageUtils queryPage(Map params); + +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysMenuService.java b/src/main/java/com/sqx/modules/sys/service/SysMenuService.java new file mode 100644 index 0000000..bda1f3d --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysMenuService.java @@ -0,0 +1,43 @@ +package com.sqx.modules.sys.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.sys.entity.SysMenuEntity; + +import java.util.List; + + +/** + * 菜单管理 + * + */ +public interface SysMenuService extends IService { + + /** + * 根据父菜单,查询子菜单 + * @param parentId 父菜单ID + * @param menuIdList 用户菜单ID + */ + List queryListParentId(Long parentId, List menuIdList); + + /** + * 根据父菜单,查询子菜单 + * @param parentId 父菜单ID + */ + List queryListParentId(Long parentId); + + /** + * 获取不包含按钮的菜单列表 + */ + List queryNotButtonList(); + + /** + * 获取用户菜单列表 + */ + List getUserMenuList(Long userId); + + /** + * 删除 + */ + void delete(Long menuId); +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysRoleMenuService.java b/src/main/java/com/sqx/modules/sys/service/SysRoleMenuService.java new file mode 100644 index 0000000..6ccb8ba --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysRoleMenuService.java @@ -0,0 +1,28 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.sys.entity.SysRoleMenuEntity; + +import java.util.List; + + + +/** + * 角色与菜单对应关系 + * + */ +public interface SysRoleMenuService extends IService { + + void saveOrUpdate(Long roleId, List menuIdList); + + /** + * 根据角色ID,获取菜单ID列表 + */ + List queryMenuIdList(Long roleId); + + /** + * 根据角色ID数组,批量删除 + */ + int deleteBatch(Long[] roleIds); + +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysRoleService.java b/src/main/java/com/sqx/modules/sys/service/SysRoleService.java new file mode 100644 index 0000000..d2e5d08 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysRoleService.java @@ -0,0 +1,30 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.sys.entity.SysRoleEntity; + +import java.util.List; +import java.util.Map; + + +/** + * 角色 + * + */ +public interface SysRoleService extends IService { + + PageUtils queryPage(Map params); + + void saveRole(SysRoleEntity role); + + void update(SysRoleEntity role); + + void deleteBatch(Long[] roleIds); + + + /** + * 查询用户创建的角色ID列表 + */ + List queryRoleIdList(Long createUserId); +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysUserRoleService.java b/src/main/java/com/sqx/modules/sys/service/SysUserRoleService.java new file mode 100644 index 0000000..66abf8c --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysUserRoleService.java @@ -0,0 +1,27 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.sys.entity.SysUserRoleEntity; + +import java.util.List; + + + +/** + * 用户与角色对应关系 + * + */ +public interface SysUserRoleService extends IService { + + void saveOrUpdate(Long userId, List roleIdList); + + /** + * 根据用户ID,获取角色ID列表 + */ + List queryRoleIdList(Long userId); + + /** + * 根据角色ID数组,批量删除 + */ + int deleteBatch(Long[] roleIds); +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysUserService.java b/src/main/java/com/sqx/modules/sys/service/SysUserService.java new file mode 100644 index 0000000..1ed0289 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysUserService.java @@ -0,0 +1,57 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.PageUtils; +import com.sqx.modules.sys.entity.SysUserEntity; + +import java.util.List; +import java.util.Map; + + +/** + * 系统用户 + * + */ +public interface SysUserService extends IService { + + PageUtils queryPage(Map params); + + /** + * 查询用户的所有权限 + * @param userId 用户ID + */ + List queryAllPerms(Long userId); + + /** + * 查询用户的所有菜单ID + */ + List queryAllMenuId(Long userId); + + /** + * 根据用户名,查询系统用户 + */ + SysUserEntity queryByUserName(String username); + + /** + * 保存用户 + */ + void saveUser(SysUserEntity user); + + /** + * 修改用户 + */ + void update(SysUserEntity user); + + /** + * 删除用户 + */ + void deleteBatch(Long[] userIds); + + /** + * 修改密码 + * @param userId 用户ID + * @param password 原密码 + * @param newPassword 新密码 + */ + boolean updatePassword(Long userId, String password, String newPassword); +} diff --git a/src/main/java/com/sqx/modules/sys/service/SysUserTokenService.java b/src/main/java/com/sqx/modules/sys/service/SysUserTokenService.java new file mode 100644 index 0000000..2cec7a4 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/SysUserTokenService.java @@ -0,0 +1,25 @@ +package com.sqx.modules.sys.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.sys.entity.SysUserTokenEntity; + +/** + * 用户Token + * + */ +public interface SysUserTokenService extends IService { + + /** + * 生成token + * @param userId 用户ID + */ + Result createToken(long userId); + + /** + * 退出,修改token值 + * @param userId 用户ID + */ + void logout(long userId); + +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/ShiroServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/ShiroServiceImpl.java new file mode 100644 index 0000000..4a600b7 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/ShiroServiceImpl.java @@ -0,0 +1,60 @@ +package com.sqx.modules.sys.service.impl; + +import com.sqx.common.utils.Constant; +import com.sqx.modules.sys.dao.SysMenuDao; +import com.sqx.modules.sys.dao.SysUserDao; +import com.sqx.modules.sys.dao.SysUserTokenDao; +import com.sqx.modules.sys.entity.SysMenuEntity; +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.entity.SysUserTokenEntity; +import com.sqx.modules.sys.service.ShiroService; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; + +@Service +public class ShiroServiceImpl implements ShiroService { + @Autowired + private SysMenuDao sysMenuDao; + @Autowired + private SysUserDao sysUserDao; + @Autowired + private SysUserTokenDao sysUserTokenDao; + + @Override + public Set getUserPermissions(long userId) { + List permsList; + + //系统管理员,拥有最高权限 + if(userId == Constant.SUPER_ADMIN){ + List menuList = sysMenuDao.selectList(null); + permsList = new ArrayList<>(menuList.size()); + for(SysMenuEntity menu : menuList){ + permsList.add(menu.getPerms()); + } + }else{ + permsList = sysUserDao.queryAllPerms(userId); + } + //用户权限列表 + Set permsSet = new HashSet<>(); + for(String perms : permsList){ + if(StringUtils.isBlank(perms)){ + continue; + } + permsSet.addAll(Arrays.asList(perms.trim().split(","))); + } + return permsSet; + } + + @Override + public SysUserTokenEntity queryByToken(String token) { + return sysUserTokenDao.queryByToken(token); + } + + @Override + public SysUserEntity queryUser(Long userId) { + return sysUserDao.selectById(userId); + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysCaptchaServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysCaptchaServiceImpl.java new file mode 100644 index 0000000..ad23106 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysCaptchaServiceImpl.java @@ -0,0 +1,62 @@ +package com.sqx.modules.sys.service.impl; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.google.code.kaptcha.Producer; +import com.sqx.common.exception.SqxException; +import com.sqx.common.utils.DateUtils; +import com.sqx.modules.sys.dao.SysCaptchaDao; +import com.sqx.modules.sys.entity.SysCaptchaEntity; +import com.sqx.modules.sys.service.SysCaptchaService; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.awt.image.BufferedImage; +import java.util.Date; + +/** + * 验证码 + * + */ +@Service("sysCaptchaService") +public class SysCaptchaServiceImpl extends ServiceImpl implements SysCaptchaService { + @Autowired + private Producer producer; + + @Override + public BufferedImage getCaptcha(String uuid) { + if(StringUtils.isBlank(uuid)){ + throw new SqxException("uuid不能为空"); + } + //生成文字验证码 + String code = producer.createText(); + + SysCaptchaEntity captchaEntity = new SysCaptchaEntity(); + captchaEntity.setUuid(uuid); + captchaEntity.setCode(code); + //5分钟后过期 + captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5)); + this.save(captchaEntity); + + return producer.createImage(code); + } + + @Override + public boolean validate(String uuid, String code) { + SysCaptchaEntity captchaEntity = this.getOne(new QueryWrapper().eq("uuid", uuid)); + if(captchaEntity == null){ + return false; + } + + //删除验证码 + this.removeById(uuid); + + if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){ + return true; + } + + return false; + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysConfigServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysConfigServiceImpl.java new file mode 100644 index 0000000..4a694ea --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysConfigServiceImpl.java @@ -0,0 +1,96 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.google.gson.Gson; +import com.sqx.common.exception.SqxException; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.modules.sys.dao.SysConfigDao; +import com.sqx.modules.sys.entity.SysConfigEntity; +import com.sqx.modules.sys.redis.SysConfigRedis; +import com.sqx.modules.sys.service.SysConfigService; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.Map; + +@Service("sysConfigService") +public class SysConfigServiceImpl extends ServiceImpl implements SysConfigService { + @Autowired + private SysConfigRedis sysConfigRedis; + + @Override + public PageUtils queryPage(Map params) { + String paramKey = (String)params.get("paramKey"); + + IPage page = this.page( + new Query().getPage(params), + new QueryWrapper() + .like(StringUtils.isNotBlank(paramKey),"param_key", paramKey) + .eq("status", 1) + ); + + return new PageUtils(page); + } + + @Override + public void saveConfig(SysConfigEntity config) { + this.save(config); + sysConfigRedis.saveOrUpdate(config); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void update(SysConfigEntity config) { + this.updateById(config); + sysConfigRedis.saveOrUpdate(config); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateValueByKey(String key, String value) { + baseMapper.updateValueByKey(key, value); + sysConfigRedis.delete(key); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteBatch(Long[] ids) { + for(Long id : ids){ + SysConfigEntity config = this.getById(id); + sysConfigRedis.delete(config.getParamKey()); + } + + this.removeByIds(Arrays.asList(ids)); + } + + @Override + public String getValue(String key) { + SysConfigEntity config = sysConfigRedis.get(key); + if(config == null){ + config = baseMapper.queryByKey(key); + sysConfigRedis.saveOrUpdate(config); + } + + return config == null ? null : config.getParamValue(); + } + + @Override + public T getConfigObject(String key, Class clazz) { + String value = getValue(key); + if(StringUtils.isNotBlank(value)){ + return new Gson().fromJson(value, clazz); + } + + try { + return clazz.newInstance(); + } catch (Exception e) { + throw new SqxException("获取参数失败"); + } + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysDictServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysDictServiceImpl.java new file mode 100644 index 0000000..15cf346 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysDictServiceImpl.java @@ -0,0 +1,33 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.modules.sys.dao.SysDictDao; +import com.sqx.modules.sys.entity.SysDictEntity; +import com.sqx.modules.sys.service.SysDictService; +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Service; + +import java.util.Map; + + +@Service("sysDictService") +public class SysDictServiceImpl extends ServiceImpl implements SysDictService { + + @Override + public PageUtils queryPage(Map params) { + String name = (String)params.get("name"); + + IPage page = this.page( + new Query().getPage(params), + new QueryWrapper() + .like(StringUtils.isNotBlank(name),"name", name) + ); + + return new PageUtils(page); + } + +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysLogServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysLogServiceImpl.java new file mode 100644 index 0000000..fe77587 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysLogServiceImpl.java @@ -0,0 +1,31 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.modules.sys.dao.SysLogDao; +import com.sqx.modules.sys.entity.SysLogEntity; +import com.sqx.modules.sys.service.SysLogService; +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Service; + +import java.util.Map; + + +@Service("sysLogService") +public class SysLogServiceImpl extends ServiceImpl implements SysLogService { + + @Override + public PageUtils queryPage(Map params) { + String key = (String)params.get("key"); + + IPage page = this.page( + new Query().getPage(params), + new QueryWrapper().like(StringUtils.isNotBlank(key),"username", key) + ); + + return new PageUtils(page); + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysMenuServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysMenuServiceImpl.java new file mode 100644 index 0000000..2f2c197 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysMenuServiceImpl.java @@ -0,0 +1,99 @@ +package com.sqx.modules.sys.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Constant; +import com.sqx.common.utils.MapUtils; +import com.sqx.modules.sys.dao.SysMenuDao; +import com.sqx.modules.sys.entity.SysMenuEntity; +import com.sqx.modules.sys.service.SysMenuService; +import com.sqx.modules.sys.service.SysRoleMenuService; +import com.sqx.modules.sys.service.SysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + + +@Service("sysMenuService") +public class SysMenuServiceImpl extends ServiceImpl implements SysMenuService { + @Autowired + private SysUserService sysUserService; + @Autowired + private SysRoleMenuService sysRoleMenuService; + + @Override + public List queryListParentId(Long parentId, List menuIdList) { + List menuList = queryListParentId(parentId); + if(menuIdList == null){ + return menuList; + } + + List userMenuList = new ArrayList<>(); + for(SysMenuEntity menu : menuList){ + if(menuIdList.contains(menu.getMenuId())){ + userMenuList.add(menu); + } + } + return userMenuList; + } + + @Override + public List queryListParentId(Long parentId) { + return baseMapper.queryListParentId(parentId); + } + + @Override + public List queryNotButtonList() { + return baseMapper.queryNotButtonList(); + } + + @Override + public List getUserMenuList(Long userId) { + //系统管理员,拥有最高权限 + if(userId == Constant.SUPER_ADMIN){ + return getAllMenuList(null); + } + //用户菜单列表 + List menuIdList = sysUserService.queryAllMenuId(userId); + return getAllMenuList(menuIdList); + } + + @Override + public void delete(Long menuId){ + //删除菜单 + this.removeById(menuId); + //删除菜单与角色关联 + sysRoleMenuService.removeByMap(new MapUtils().put("menu_id", menuId)); + } + + /** + * 获取所有菜单列表 + */ + private List getAllMenuList(List menuIdList){ + //查询根菜单列表 + List menuList = queryListParentId(0L, menuIdList); + //递归获取子菜单 + getMenuTreeList(menuList, menuIdList); + + return menuList; + } + + /** + * 递归 + */ + private List getMenuTreeList(List menuList, List menuIdList){ + List subMenuList = new ArrayList(); + + for(SysMenuEntity entity : menuList){ + //目录 + if(entity.getType() == Constant.MenuType.CATALOG.getValue()){ + entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList)); + } + subMenuList.add(entity); + } + + return subMenuList; + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysRoleMenuServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysRoleMenuServiceImpl.java new file mode 100644 index 0000000..c68928e --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysRoleMenuServiceImpl.java @@ -0,0 +1,51 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.sys.dao.SysRoleMenuDao; +import com.sqx.modules.sys.entity.SysRoleMenuEntity; +import com.sqx.modules.sys.service.SysRoleMenuService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + + + +/** + * 角色与菜单对应关系 + * + */ +@Service("sysRoleMenuService") +public class SysRoleMenuServiceImpl extends ServiceImpl implements SysRoleMenuService { + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveOrUpdate(Long roleId, List menuIdList) { + //先删除角色与菜单关系 + deleteBatch(new Long[]{roleId}); + + if(menuIdList.size() == 0){ + return ; + } + + //保存角色与菜单关系 + for(Long menuId : menuIdList){ + SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity(); + sysRoleMenuEntity.setMenuId(menuId); + sysRoleMenuEntity.setRoleId(roleId); + + this.save(sysRoleMenuEntity); + } + } + + @Override + public List queryMenuIdList(Long roleId) { + return baseMapper.queryMenuIdList(roleId); + } + + @Override + public int deleteBatch(Long[] roleIds){ + return baseMapper.deleteBatch(roleIds); + } + +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysRoleServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysRoleServiceImpl.java new file mode 100644 index 0000000..7416971 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysRoleServiceImpl.java @@ -0,0 +1,113 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.modules.sys.dao.SysRoleDao; +import com.sqx.modules.sys.entity.SysRoleEntity; +import com.sqx.modules.sys.service.SysRoleMenuService; +import com.sqx.modules.sys.service.SysRoleService; +import com.sqx.modules.sys.service.SysUserRoleService; +import com.sqx.modules.sys.service.SysUserService; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * 角色 + * + */ +@Service("sysRoleService") +public class SysRoleServiceImpl extends ServiceImpl implements SysRoleService { + @Autowired + private SysRoleMenuService sysRoleMenuService; + @Autowired + private SysUserService sysUserService; + @Autowired + private SysUserRoleService sysUserRoleService; + + @Override + public PageUtils queryPage(Map params) { + String roleName = (String)params.get("roleName"); + Long createUserId = (Long)params.get("createUserId"); + + IPage page = this.page( + new Query().getPage(params), + new QueryWrapper() + .like(StringUtils.isNotBlank(roleName),"role_name", roleName) + .eq(createUserId != null,"create_user_id", createUserId) + ); + + return new PageUtils(page); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveRole(SysRoleEntity role) { + role.setCreateTime(new Date()); + this.save(role); + + //检查权限是否越权 + checkPrems(role); + + //保存角色与菜单关系 + sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void update(SysRoleEntity role) { + this.updateById(role); + + //检查权限是否越权 + checkPrems(role); + + //更新角色与菜单关系 + sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteBatch(Long[] roleIds) { + //删除角色 + this.removeByIds(Arrays.asList(roleIds)); + + //删除角色与菜单关联 + sysRoleMenuService.deleteBatch(roleIds); + + //删除角色与用户关联 + sysUserRoleService.deleteBatch(roleIds); + } + + + @Override + public List queryRoleIdList(Long createUserId) { + return baseMapper.queryRoleIdList(createUserId); + } + + /** + * 检查权限是否越权 + */ + private void checkPrems(SysRoleEntity role){ + /*//如果不是超级管理员,则需要判断角色的权限是否超过自己的权限 + if(role.getCreateUserId() == Constant.SUPER_ADMIN){ + return ; + } + + //查询用户所拥有的菜单列表 + List menuIdList = sysUserService.queryAllMenuId(role.getCreateUserId()); + + //判断是否越权 + if(!menuIdList.containsAll(role.getMenuIdList())){ + throw new SqxException("新增角色的权限,已超出你的权限范围"); + }*/ + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysUserRoleServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysUserRoleServiceImpl.java new file mode 100644 index 0000000..786102a --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysUserRoleServiceImpl.java @@ -0,0 +1,49 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.MapUtils; +import com.sqx.modules.sys.dao.SysUserRoleDao; +import com.sqx.modules.sys.entity.SysUserRoleEntity; +import com.sqx.modules.sys.service.SysUserRoleService; +import org.springframework.stereotype.Service; + +import java.util.List; + + + +/** + * 用户与角色对应关系 + * + */ +@Service("sysUserRoleService") +public class SysUserRoleServiceImpl extends ServiceImpl implements SysUserRoleService { + + @Override + public void saveOrUpdate(Long userId, List roleIdList) { + //先删除用户与角色关系 + this.removeByMap(new MapUtils().put("user_id", userId)); + + if(roleIdList == null || roleIdList.size() == 0){ + return ; + } + + //保存用户与角色关系 + for(Long roleId : roleIdList){ + SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity(); + sysUserRoleEntity.setUserId(userId); + sysUserRoleEntity.setRoleId(roleId); + + this.save(sysUserRoleEntity); + } + } + + @Override + public List queryRoleIdList(Long userId) { + return baseMapper.queryRoleIdList(userId); + } + + @Override + public int deleteBatch(Long[] roleIds){ + return baseMapper.deleteBatch(roleIds); + } +} diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysUserServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysUserServiceImpl.java new file mode 100644 index 0000000..31255b8 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysUserServiceImpl.java @@ -0,0 +1,204 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Query; +import com.sqx.modules.laundry.dao.LaundryRepository; +import com.sqx.modules.laundry.model.Laundry; +import com.sqx.modules.laundry.service.LaundryService; +import com.sqx.modules.sys.dao.SysUserDao; +import com.sqx.modules.sys.entity.SysUserEntity; +import com.sqx.modules.sys.service.SysRoleService; +import com.sqx.modules.sys.service.SysUserRoleService; +import com.sqx.modules.sys.service.SysUserService; +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.shiro.crypto.hash.Sha256Hash; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + + +/** + * 系统用户 + */ +@SuppressWarnings("ALL") +@Service("sysUserService") +public class SysUserServiceImpl extends ServiceImpl implements SysUserService { + @Autowired + private SysUserRoleService sysUserRoleService; + @Autowired + private SysRoleService sysRoleService; + @Autowired + private LaundryRepository laundryRepository; + + @Override + public PageUtils queryPage(Map params) { + String username = (String) params.get("username"); + Long createUserId = (Long) params.get("createUserId"); + String isLaundry = String.valueOf(params.get("isLaundry")); + String laundryId = String.valueOf(params.get("laundryId")); + IPage page = this.page( + new Query().getPage(params), + new QueryWrapper() + .like(StringUtils.isNotBlank(username), "username", username) + .eq(StringUtils.isNotBlank(isLaundry) && !"null".equals(isLaundry), "is_laundry", isLaundry) + .eq(StringUtils.isNotBlank(laundryId) && !"null".equals(laundryId), "laundry_id", laundryId) + .isNull(StringUtils.isEmpty(isLaundry) || "null".equals(isLaundry), "is_laundry") + .eq(createUserId != null, "create_user_id", createUserId) + ); + List records = page.getRecords(); + for (SysUserEntity userEntity : records) { + if (userEntity.getLaundryId() != null) { + userEntity.setLaundry(laundryRepository.findById(userEntity.getLaundryId()).orElse(null)); + } + } + return new PageUtils(page); + } + + @Override + public List queryAllPerms(Long userId) { + return baseMapper.queryAllPerms(userId); + } + + @Override + public List queryAllMenuId(Long userId) { + return baseMapper.queryAllMenuId(userId); + } + + @Override + public SysUserEntity queryByUserName(String username) { + return baseMapper.queryByUserName(username); + } + + @SuppressWarnings("AlibabaTransactionMustHaveRollback") + @Override + @Transactional + public void saveUser(SysUserEntity user) { + user.setCreateTime(new Date()); + //sha256加密 + String salt = RandomStringUtils.randomAlphanumeric(20); + user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex()); + user.setSalt(salt); + this.save(user); + + //检查角色是否越权 + checkRole(user); + + //保存用户与角色关系 + sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList()); + + //保存站点信息 + if(user.getLaundryId()!=null){ + Laundry laundry = laundryRepository.findById(user.getLaundryId()).orElse(null); + if(laundry!=null){ + if(StringUtils.isNotEmpty(laundry.getSysUserIds())){ + laundry.setSysUserIds(laundry.getSysUserIds()+","+user.getUserId()); + }else{ + laundry.setSysUserIds(user.getUserId().toString()); + } + laundryRepository.save(laundry); + } + } + } + + @Override + @Transactional + public void update(SysUserEntity user) { + if (StringUtils.isBlank(user.getPassword())) { + user.setPassword(null); + } else { + user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex()); + } + + //保存站点信息 + if(user.getLaundryId()!=null){ + SysUserEntity oldUser = this.getById(user.getUserId()); + if(oldUser.getLaundryId()==null || oldUser.getLaundryId().equals(user.getLaundryId())){ + Laundry laundry = laundryRepository.findById(user.getLaundryId()).orElse(null); + if(laundry!=null){ + if(StringUtils.isNotEmpty(laundry.getSysUserIds())){ + laundry.setSysUserIds(laundry.getSysUserIds()+","+user.getUserId()); + }else{ + laundry.setSysUserIds(user.getUserId().toString()); + } + laundryRepository.save(laundry); + } + if(oldUser.getLaundryId()!=null){ + Laundry oldLaundry = laundryRepository.findById(oldUser.getLaundryId()).orElse(null); + if(oldLaundry!=null){ + StringBuilder stringBuilders=new StringBuilder(); + for(String userIds:oldLaundry.getSysUserIds().split(",")){ + if(!userIds.equals(String.valueOf(user.getUserId()))){ + stringBuilders.append(userIds).append(","); + } + } + String str=stringBuilders.toString(); + if(org.apache.commons.lang3.StringUtils.isNotEmpty(str)){ + if(stringBuilders.charAt(stringBuilders.length()-1) == ',') { + str=stringBuilders.substring(0, stringBuilders.length()-1); + } + } + oldLaundry.setSysUserIds(str); + laundryRepository.save(oldLaundry); + } + } + } + + } + + + this.updateById(user); + + //检查角色是否越权 + checkRole(user); + + //保存用户与角色关系 + sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList()); + + + + + } + + @Override + public void deleteBatch(Long[] userId) { + this.removeByIds(Arrays.asList(userId)); + } + + @Override + public boolean updatePassword(Long userId, String password, String newPassword) { + SysUserEntity userEntity = new SysUserEntity(); + userEntity.setPassword(newPassword); + return this.update(userEntity, + new QueryWrapper().eq("user_id", userId).eq("password", password)); + } + + /** + * 检查角色是否越权 + */ + private void checkRole(SysUserEntity user) { + /*if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){ + return; + } + //如果不是超级管理员,则需要判断用户的角色是否自己创建 + if(user.getCreateUserId() == Constant.SUPER_ADMIN){ + return ; + } + + //查询用户创建的角色列表 + List roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId()); + + //判断是否越权 + if(!roleIdList.containsAll(user.getRoleIdList())){ + throw new SqxException("新增用户所选角色,不是本人创建"); + }*/ + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/sys/service/impl/SysUserTokenServiceImpl.java b/src/main/java/com/sqx/modules/sys/service/impl/SysUserTokenServiceImpl.java new file mode 100644 index 0000000..1e40e84 --- /dev/null +++ b/src/main/java/com/sqx/modules/sys/service/impl/SysUserTokenServiceImpl.java @@ -0,0 +1,66 @@ +package com.sqx.modules.sys.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.sys.dao.SysUserTokenDao; +import com.sqx.modules.sys.entity.SysUserTokenEntity; +import com.sqx.modules.sys.oauth2.TokenGenerator; +import com.sqx.modules.sys.service.SysUserTokenService; +import org.springframework.stereotype.Service; + +import java.util.Date; + + +@Service("sysUserTokenService") +public class SysUserTokenServiceImpl extends ServiceImpl implements SysUserTokenService { + //12小时后过期 + private final static int EXPIRE = 3600 * 12; + + + @Override + public Result createToken(long userId) { + //生成一个token + String token = TokenGenerator.generateValue(); + + //当前时间 + Date now = new Date(); + //过期时间 + Date expireTime = new Date(now.getTime() + EXPIRE * 1000); + + //判断是否生成过token + SysUserTokenEntity tokenEntity = this.getById(userId); + if(tokenEntity == null){ + tokenEntity = new SysUserTokenEntity(); + tokenEntity.setUserId(userId); + tokenEntity.setToken(token); + tokenEntity.setUpdateTime(now); + tokenEntity.setExpireTime(expireTime); + + //保存token + this.save(tokenEntity); + }else{ + tokenEntity.setToken(token); + tokenEntity.setUpdateTime(now); + tokenEntity.setExpireTime(expireTime); + + //更新token + this.updateById(tokenEntity); + } + + Result r = Result.success().put("token", token).put("expire", EXPIRE); + + return r; + } + + @Override + public void logout(long userId) { + //生成一个token + String token = TokenGenerator.generateValue(); + + //修改token + SysUserTokenEntity tokenEntity = new SysUserTokenEntity(); + tokenEntity.setUserId(userId); + tokenEntity.setToken(token); + this.updateById(tokenEntity); + } +} diff --git a/src/main/java/com/sqx/modules/taking/controller/CollectOrderTakingController.java b/src/main/java/com/sqx/modules/taking/controller/CollectOrderTakingController.java new file mode 100644 index 0000000..56ceb2e --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/CollectOrderTakingController.java @@ -0,0 +1,40 @@ +package com.sqx.modules.taking.controller; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.service.CollectOrderTakingService; +import com.sqx.modules.taking.service.GameService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/collect") +@Api("收藏") +public class CollectOrderTakingController { + + @Autowired + private CollectOrderTakingService collectOrderTakingService; + + @PostMapping("/insertCollectOrderTaking") + @ApiOperation("添加收藏或移除") + public Result insertCollectOrderTaking(Long orderTakingId,Long userId){ + return collectOrderTakingService.insertCollectOrderTaking(orderTakingId, userId); + } + + @GetMapping("/selectCollectOrderTaking") + @ApiOperation("查询是否收藏") + public Result selectCollectOrderTaking(Long userId,Long orderTakingId){ + return Result.success().put("data",collectOrderTakingService.selectOrderTakingByUserId(orderTakingId,userId)); + } + + @GetMapping("/selectCollectOrderTakingList") + @ApiOperation("查询收藏列表") + public Result selectCollectOrderTakingList(Integer page,Integer limit,Long userId){ + return collectOrderTakingService.selectCollectOrderTakingList(page, limit, userId); + } + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/GameController.java b/src/main/java/com/sqx/modules/taking/controller/GameController.java new file mode 100644 index 0000000..ab74dfc --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/GameController.java @@ -0,0 +1,77 @@ +package com.sqx.modules.taking.controller; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.service.GameService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@AllArgsConstructor +@RequestMapping("/game") +@Api("游戏分类") +public class GameController { + private GameService gameService; + + /** + * 查看游戏分类 + */ + @GetMapping("/queryGameName") + @ApiOperation("查看游戏分类") + public Result queryAllGameName(Long page, Long limit) { + return gameService.queryAllGameName(page, limit); + } + + /** + * 添加游戏分类 + */ + @GetMapping("/addGameName") + @ApiOperation("添加游戏分类") + public Result addGameName(String gameName,String gameImg) { + return gameService.addGameName(gameName,gameImg); + } + + /** + * 修改游戏分类 + */ + @GetMapping("/updateGameName") + @ApiOperation("修改游戏分类") + public Result updateGameName(Long id, String gameName,String gameImg, Long status) { + return gameService.updateGameName(id, gameName,gameImg, status); + } + + /** + * 删除游戏分类 + */ + @GetMapping("/deleteGameName") + @ApiOperation("删除游戏分类") + public Result deleteGameName(Long id) { + return gameService.deleteGameName(id); + } + + /** + * 查看启用的游戏分类 + */ + @GetMapping("/queryGame") + @ApiOperation("查看启用的游戏分类") + public Result queryGameName() { + return gameService.queryGameName(); + } + + /** + * 是否启用游戏分类 + */ + @GetMapping("/enableGameName") + @ApiOperation("是否启用游戏分类") + public Result enableGameName(Long status, Long id) { + if (status == null || id == null) { + return Result.error("启用分类的条件为空"); + } else { + return gameService.enableGameName(status, id); + } + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/GoodsRuleController.java b/src/main/java/com/sqx/modules/taking/controller/GoodsRuleController.java new file mode 100644 index 0000000..77c4a7f --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/GoodsRuleController.java @@ -0,0 +1,87 @@ +package com.sqx.modules.taking.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.GoodsAttr; +import com.sqx.modules.taking.entity.GoodsRule; +import com.sqx.modules.taking.service.GoodsRuleService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="商户端-商品规格",tags={"商户端-商品规格"}) +@RequestMapping(value = "/selfGoodsRule") +public class GoodsRuleController { + @Autowired + private GoodsRuleService goodsRuleService; + + @GetMapping("/list") + @ApiOperation("列表") + public Result findAll(Integer page, Integer limit) { + return goodsRuleService.findAll(page, limit); + } + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return goodsRuleService.findOne(id); + } + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody GoodsRule entity) { + return goodsRuleService.saveBody(entity); + } + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody GoodsRule entity) { + return goodsRuleService.updateBody(entity); + } + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return goodsRuleService.delete(id); + } + + @ApiOperation(value = "单规格生成sku") + @GetMapping(value = "/onlyFormatAttr") + public Result onlyFormatSku(@ApiParam("商品图片")@RequestParam(required = false) String coverImg, + @ApiParam("原价")@RequestParam(required = false) String skuMemberPrice, + @ApiParam("售价")@RequestParam(required = false) String price){ + return goodsRuleService.onlyFormatAttr(coverImg, skuMemberPrice, price); + } + + @ApiOperation(value = "多规格生成sku") + @PostMapping(value = "/isFormatAttr") + public Result isFormatSku(@RequestBody GoodsAttr attr, + @ApiParam("商品图片")@RequestParam(required = false) String coverImg, + @ApiParam("原价")@RequestParam(required = false) String skuMemberPrice, + @ApiParam("售价")@RequestParam(required = false) String price){ + return goodsRuleService.isFormatAttr(attr, coverImg, skuMemberPrice, price); + } + + @ApiOperation(value = "回显属性") + @GetMapping(value = "/formatAttr") + public Result formatAttr(Long goodsId){ + return goodsRuleService.formatAttr(goodsId); + } + + @ApiOperation(value = "回显规格") + @GetMapping(value = "/findAttrValue") + public Result findAttrValue(Long goodsId){ + return goodsRuleService.findAttrValue(goodsId); + } + + @PostMapping("/updateStock") + @ApiOperation("修改库存数量") + public Result updateStock(Long skuId,Integer num){ + return goodsRuleService.updateStock(skuId,num); + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/OrderTakingCommentController.java b/src/main/java/com/sqx/modules/taking/controller/OrderTakingCommentController.java new file mode 100644 index 0000000..98c9139 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/OrderTakingCommentController.java @@ -0,0 +1,46 @@ +package com.sqx.modules.taking.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.service.OrderTakingCommentService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/takingComment") +@Api(value = "评论", tags = {"评论"}) +public class OrderTakingCommentController { + + @Autowired + private OrderTakingCommentService orderTakingCommentService; + + /** + * 查看我的评论 + */ + @GetMapping("/queryMyComment") + public Result queryMyComment(Long userId) { + return orderTakingCommentService.queryMyComment(userId); + } + + + @GetMapping("/selectCommentByOrderTakingUserId") + @ApiOperation("查看我发布的服务的评论") + public Result selectCommentByOrderTakingUserId(Integer page, Integer limit, Long userId) { + return orderTakingCommentService.selectCommentByOrderTakingUserId(page, limit, userId); + } + + @GetMapping("/selectOrderTakingComment") + @ApiOperation("查看评论") + public Result selectOrderTakingComment(Integer page, Integer limit, Long id) { + return orderTakingCommentService.selectOrderTakingComment(page, limit, id); + } + + @PostMapping("/deleteOrderTakingComment/{id}") + @ApiOperation("删除评论") + public Result deleteOrderTakingComment(@PathVariable Long id) { + orderTakingCommentService.removeById(id); + return Result.success(); + } + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/OrderTakingController.java b/src/main/java/com/sqx/modules/taking/controller/OrderTakingController.java new file mode 100644 index 0000000..718ce7b --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/OrderTakingController.java @@ -0,0 +1,175 @@ +package com.sqx.modules.taking.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.taking.dao.OrderTakingDao; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.OrderTakingRewardService; +import com.sqx.modules.taking.service.OrderTakingService; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/orderTaking") +public class OrderTakingController { + + @Autowired + private OrderTakingService orderTakingService; + @Autowired + private OrdersDao ordersDao; + @Autowired + private OrderTakingDao orderTakingDao; + @Autowired + private OrdersService ordersService; + @Autowired + private OrderTakingRewardService orderTakingRewardService; + @Autowired + private UserService userService; + + + /** + * 发布接单 + */ + @ApiOperation("发布接单") + @PostMapping("/insertOrderTaking") + public Result insertOrderTaking(@RequestBody OrderTaking orderTaking) { + return orderTakingService.insertOrderTaking(orderTaking); + } + + /** + * 删除订单 + */ + @ApiOperation("删除接单") + @GetMapping("/deleteOrderTaking") + public Result deleteOrderTaking(Long id) { + return orderTakingService.deleteOrderTaking(id); + } + + /** + * 查询所有接单 + */ + @ApiOperation("查询所有接单") + @GetMapping("/queryAllOrderTaking") + public Result queryAllOrderTaking(@ApiParam("页") Integer page, @ApiParam("条") Integer limit, Long gameId, Long status, + String userName, Long userId, Integer classify, String longitude, String latitude, + Integer isIntegral, String serviceName, Long laundryId, Integer serviceType) { + return orderTakingService.queryAllOrderTaking(page, limit, gameId, status, userName, userId, classify, longitude, latitude, isIntegral, serviceName, laundryId, serviceType); + } + + + @ApiOperation("查询接单详情") + @GetMapping("/queryTakingDetailss") + public Result queryTakingDetailss(Long id) { + return orderTakingService.queryTakingDetails(id, null, null, null); + } + + /** + * 审核接单 + */ + @ApiOperation("审核接单") + @GetMapping("/auditorOrderTaking") + public Result auditorOrderTaking(Long id, Integer status, String content) { + return orderTakingService.auditorOrderTaking(id, status, content); + } + + /** + * 修改 + */ + @ApiOperation("修改接单") + @PostMapping("/updateTakingOrder") + public Result updateTakingOrder(@RequestBody OrderTaking orderTaking) { + return orderTakingService.updateTakingOrder(orderTaking); + } + + @ApiOperation("修改接单") + @PostMapping("/updateTakingOrders") + public Result updateTakingOrders(@RequestBody OrderTaking orderTaking) { + return orderTakingService.updateTakingOrders(orderTaking); + } + + @PostMapping("/updateOrderTakingStatus/{id}") + @ApiOperation("修改状态") + public Result updateOrderTakingStatus(@PathVariable Long id) { + OrderTaking byId = orderTakingService.getById(id); + if (byId.getStatus() == 0) { + byId.setStatus(2); + } else { + byId.setStatus(0); + } + orderTakingService.updateById(byId); + return Result.success(); + } + + + @PostMapping("/updateOrderTakingRecommend/{id}") + @ApiOperation("修改状态") + public Result updateOrderTakingRecommend(@PathVariable Long id) { + OrderTaking byId = orderTakingService.getById(id); + if ("0".equals(byId.getIsRecommend())) { + byId.setIsRecommend("1"); + } else { + byId.setIsRecommend("0"); + } + orderTakingService.updateById(byId); + return Result.success(); + } + + @ApiOperation("任务分析") + @GetMapping("/taskAnalysis") + public Result taskAnalysis(String time, Integer flag, Long laundryId) { + Integer orderCount = ordersDao.orderCount(time, flag, null, laundryId); + Integer completeCount = ordersDao.orderCount(time, flag, 2, laundryId); + + BigDecimal orderMoney = ordersDao.getMoney(time, flag, null, laundryId); + BigDecimal completeMoney = ordersDao.getMoney(time, flag, 2, laundryId); + Map map = new HashMap<>(); + //订单总数 + map.put("orderCount", orderCount); //订单总数 + map.put("completeCount", completeCount); //订单完成总数 + map.put("orderMoney", orderMoney);//订单总金额 + map.put("completeMoney", completeMoney);//完成订单总金额 + return Result.success().put("data", map); + } + + @GetMapping("/selectUserOrdersList") + @ApiOperation("查询站点师傅的收益") + public Result selectUserOrdersList(Integer page, Integer limit, Long laundryId, String userName, String phone, String time, Integer flag) { + return userService.selectUserOrdersList(page, limit, laundryId, userName, phone, time, flag); + } + + @GetMapping("/selectOrderTakingStock") + @ApiOperation("库存预警") + public Result selectOrderTakingStock(Integer page, Integer limit, Long laundryId, String serviceName, String detailJson) { + return orderTakingService.selectOrderTakingStockList(page, limit, laundryId, serviceName, detailJson); + } + + + @ApiOperation("接单收入分析") + @GetMapping("/incomeAnalysis") + public Result incomeAnalysis(String time, Integer flag, int page, int limit) { + return Result.success().put("data", ordersService.incomeAnalysisOrders(page, limit, time, flag)); + } + + @ApiOperation("查询打赏列表") + @PostMapping("/selectOrderTakingRewardList") + public Result selectOrderTakingRewardList(Integer page, Integer limit, Long userId, Long orderTakingId) { + return orderTakingRewardService.selectOrderTakingRewardList(page, limit, userId, orderTakingId); + } + + @ApiOperation("修改商品详情") + @PostMapping("/updateTaking") + public Result updateTaking(@RequestBody OrderTaking orderTaking) { + return orderTakingService.updateById(orderTaking) ? Result.success() : Result.error(); + } + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/app/AppCollectOrderTakingController.java b/src/main/java/com/sqx/modules/taking/controller/app/AppCollectOrderTakingController.java new file mode 100644 index 0000000..c3bea8e --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/app/AppCollectOrderTakingController.java @@ -0,0 +1,39 @@ +package com.sqx.modules.taking.controller.app; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.taking.service.CollectOrderTakingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/app/collect") +@Api("收藏") +public class AppCollectOrderTakingController { + + @Autowired + private CollectOrderTakingService collectOrderTakingService; + + @Login + @PostMapping("/insertCollectOrderTaking") + @ApiOperation("添加收藏或移除") + public Result insertCollectOrderTaking(Long orderTakingId,@RequestAttribute Long userId){ + return collectOrderTakingService.insertCollectOrderTaking(orderTakingId, userId); + } + + @Login + @GetMapping("/selectCollectOrderTaking") + @ApiOperation("查询是否收藏") + public Result selectCollectOrderTaking(@RequestAttribute Long userId,Long orderTakingId){ + return Result.success().put("data",collectOrderTakingService.selectOrderTakingByUserId(orderTakingId,userId)); + } + + @Login + @GetMapping("/selectCollectOrderTakingList") + @ApiOperation("查询收藏列表") + public Result selectCollectOrderTakingList(Integer page,Integer limit,@RequestAttribute Long userId){ + return collectOrderTakingService.selectCollectOrderTakingList(page, limit, userId); + } + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/app/AppGameController.java b/src/main/java/com/sqx/modules/taking/controller/app/AppGameController.java new file mode 100644 index 0000000..c733921 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/app/AppGameController.java @@ -0,0 +1,32 @@ +package com.sqx.modules.taking.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.service.GameService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@AllArgsConstructor +@RequestMapping("app/appGame") +@Api("分类") +public class AppGameController { + + private GameService gameService; + + @GetMapping("/queryGameName") + @ApiOperation("查询首页分类") + public Result queryGameName() { + return gameService.queryGameName(); + } + + @GetMapping("/queryGameNameList") + @ApiOperation("查询分类和数据") + public Result queryGameNameList() { + return gameService.queryGameNameList(); + } + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/app/AppGoodsRuleController.java b/src/main/java/com/sqx/modules/taking/controller/app/AppGoodsRuleController.java new file mode 100644 index 0000000..f09ef50 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/app/AppGoodsRuleController.java @@ -0,0 +1,81 @@ +package com.sqx.modules.taking.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.GoodsAttr; +import com.sqx.modules.taking.entity.GoodsRule; +import com.sqx.modules.taking.service.GoodsRuleService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value="商品规格",tags={"商品规格"}) +@RequestMapping(value = "/app/selfGoodsRule") +public class AppGoodsRuleController { + @Autowired + private GoodsRuleService goodsRuleService; + + @GetMapping("/list") + @ApiOperation("列表") + public Result findAll(Integer page, Integer limit) { + return goodsRuleService.findAll(page, limit); + } + + @GetMapping("/find") + @ApiOperation("查询") + public Result findOne(Long id) { + return goodsRuleService.findOne(id); + } + + @PostMapping("/save") + @ApiOperation("添加") + public Result saveBody(@RequestBody GoodsRule entity) { + return goodsRuleService.saveBody(entity); + } + + @PostMapping("/update") + @ApiOperation("修改") + public Result updateBody(@RequestBody GoodsRule entity) { + return goodsRuleService.updateBody(entity); + } + + + @GetMapping("/delete") + @ApiOperation("删除") + public Result delete(Long id) { + return goodsRuleService.delete(id); + } + + @ApiOperation(value = "单规格生成sku") + @GetMapping(value = "/onlyFormatAttr") + public Result onlyFormatSku(@ApiParam("商品图片")@RequestParam(required = false) String coverImg, + @ApiParam("原价")@RequestParam(required = false) String skuMemberPrice, + @ApiParam("售价")@RequestParam(required = false) String price){ + return goodsRuleService.onlyFormatAttr(coverImg, skuMemberPrice, price); + } + + @ApiOperation(value = "多规格生成sku") + @PostMapping(value = "/isFormatAttr") + public Result isFormatSku(@RequestBody GoodsAttr attr, + @ApiParam("商品图片")@RequestParam(required = false) String coverImg, + @ApiParam("原价")@RequestParam(required = false) String skuMemberPrice, + @ApiParam("售价")@RequestParam(required = false) String price){ + return goodsRuleService.isFormatAttr(attr, coverImg, skuMemberPrice, price); + } + + @ApiOperation(value = "回显属性") + @GetMapping(value = "/formatAttr") + public Result formatAttr(Long goodsId){ + return goodsRuleService.formatAttr(goodsId); + } + + @ApiOperation(value = "回显规格") + @GetMapping(value = "/findAttrValue") + public Result findAttrValue(Long goodsId){ + return goodsRuleService.findAttrValue(goodsId); + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/app/AppOrderTakingCommentController.java b/src/main/java/com/sqx/modules/taking/controller/app/AppOrderTakingCommentController.java new file mode 100644 index 0000000..c4a5042 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/app/AppOrderTakingCommentController.java @@ -0,0 +1,74 @@ +package com.sqx.modules.taking.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.taking.service.OrderTakingCommentService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@AllArgsConstructor +@RequestMapping("/app/takingComment") +@Api(value = "APP评论|点赞", tags = {"APP评论|点赞"}) +public class AppOrderTakingCommentController { + + private OrderTakingCommentService orderTakingCommentService; + + /** + * 查看接单下的所有评论内容 时间 评论人 评论人图像 评论点赞次数 + * + * @param page + * @param limit + * @param id + */ + @CrossOrigin + @GetMapping("/selectOrderTakingComment") + @ApiOperation("查看评论") + public Result selectOrderTakingComment(Integer page, Integer limit, Long id) { + return orderTakingCommentService.selectOrderTakingComment(page, limit, id); + } + + /** + * 有赞时取消点赞 没赞时点赞 + * + * @param commentId + * @param userId + * @return + */ + @Login + @GetMapping("/updateGoodsNum") + @ApiOperation("点赞评论") + public Result updateGoodsNum(Long commentId, @RequestAttribute("userId") Long userId) { + return orderTakingCommentService.updateGoodsNum(commentId, userId); + } + + @GetMapping("/selectCommentByOrderTakingUserId") + @ApiOperation("查看我发布的服务的评论") + public Result selectCommentByOrderTakingUserId(Integer page, Integer limit, Long userId) { + return orderTakingCommentService.selectCommentByOrderTakingUserId(page, limit, userId); + } + + + + + /** + * 添加评论 + */ + @Login + @PostMapping("/addGoodsNum") + @ApiOperation("添加评论") + public Result addGoodsNum(Long id, @RequestAttribute("userId") Long userId, String content, Integer score,Long ordersId) { + return orderTakingCommentService.addGoodsNum(id, userId, content, score,ordersId); + } + + @Login + @GetMapping("/selectTakingCommentCount") + @ApiOperation("查询评论次数") + public Result selectTakingCommentCount(Long ordersId, @RequestAttribute("userId") Long userId) { + return Result.success().put("data",orderTakingCommentService.selectTakingCommentCount(ordersId, userId)); + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/controller/app/AppOrderTakingController.java b/src/main/java/com/sqx/modules/taking/controller/app/AppOrderTakingController.java new file mode 100644 index 0000000..fda2c59 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/controller/app/AppOrderTakingController.java @@ -0,0 +1,181 @@ +package com.sqx.modules.taking.controller.app; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.OrderTakingRewardService; +import com.sqx.modules.taking.service.OrderTakingService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; + +@RestController +@AllArgsConstructor +@Api("app接单详情") +@RequestMapping("/app/orderTaking") +public class AppOrderTakingController { + + private OrderTakingService orderTakingService; + private OrderTakingRewardService orderTakingRewardService; + + /** + * 按照指定条件查询接单 + * + * @param bannerid + * @return + */ + @CrossOrigin + @Login + @ApiOperation("按照指定条件查询接单") + @GetMapping("/queryTaking") + public Result queryTaking(@ApiParam("城市")String city,@ApiParam("精度") String longitude, @ApiParam("维度") String latitude, + @RequestAttribute Long userId, @ApiParam("模糊") String like, @ApiParam("条件") String condition, + @ApiParam("bannerid") Long bannerid, @ApiParam("推荐") Long isRecommend, @ApiParam("游戏id") Long id, + @ApiParam("页") Long page, @ApiParam("条") Long limit, @ApiParam("性别") Long sex, @ApiParam("排序") String by, + Integer classify,Integer isIntegral ,Long laundryId) { + Page iPage = new Page<>(page, limit); + return orderTakingService.queryTaking(city,longitude, latitude, userId, like, condition, bannerid, isRecommend, id, iPage, sex, by,classify,isIntegral,laundryId); + } + + @CrossOrigin + @ApiOperation("按照指定条件查询接单") + @GetMapping("/queryTakings") + public Result queryTakings(@ApiParam("城市")String city,@ApiParam("精度") String longitude, @ApiParam("维度") String latitude, + Long userId, @ApiParam("模糊") String like, @ApiParam("条件") String condition, @ApiParam("bannerid") Long bannerid, + @ApiParam("推荐") Long isRecommend, @ApiParam("游戏id") Long id, @ApiParam("页") Long page, @ApiParam("条") Long limit, + @ApiParam("性别") Long sex, @ApiParam("排序") String by,Integer classify,Integer isIntegral,Long laundryId) { + Page iPage = new Page<>(page, limit); + return orderTakingService.queryTaking(city,longitude, latitude, userId, like, condition, bannerid, isRecommend, id, iPage, sex, by,classify,isIntegral,laundryId); + } + + + + /** + * 查询低价系列的接单 + */ + @ApiOperation("查询低价系列的接单") + @GetMapping("/queryLowTaking") + public Result queryLowTaking(Integer page, Integer limit,@ApiParam("精度") String longitude, @ApiParam("维度") String latitude,Long laundryId) { + return orderTakingService.queryLowTaking(page,limit,longitude,latitude,laundryId); + } + + /** + * 查询接单详情 + */ + @ApiOperation("查询接单详情") + @CrossOrigin + @GetMapping("/queryTakingDetails") + public Result queryTakingDetails(@RequestParam Long id, Long userId,String longitude,String latitude) { + return orderTakingService.queryTakingDetails(id, userId,longitude,latitude); + } + + @ApiOperation("查询接单详情(不需要token)") + @CrossOrigin + @GetMapping("/queryTakingDetailss") + public Result queryTakingDetailss(@RequestParam Long id, String longitude,String latitude) { + return orderTakingService.queryTakingDetails(id, null,longitude,latitude); + } + + /** + * 发布接单 + */ + @ApiOperation("发布接单") + @PostMapping("/insertOrderTaking") + @Login + public Result insertOrderTaking(@RequestBody OrderTaking orderTaking,@RequestAttribute Long userId) { + orderTaking.setUserId(userId); + return orderTakingService.insertOrderTaking(orderTaking); + } + + /** + * 查看我的发布 + */ + @Login + @ApiOperation("查看我的发布") + @GetMapping("/selectMyRelease") + public Result selectMyRelease(@RequestAttribute Long userId, Long page, Long limit, @ApiParam("状态") String status) { + return orderTakingService.selectMyRelease(userId, page, limit, status); + } + + + @ApiOperation("查看其他用户发布") + @GetMapping("/selectUserOrderTaking") + public Result selectUserOrderTaking(Long userId, Long page, Long limit) { + return orderTakingService.selectMyRelease(userId, page, limit, "0"); + } + + /** + * 修改发布状态 + */ + @Login + @ApiOperation("修改发布状态") + @GetMapping("/updateTakingStatus") + public Result updateTakingStatus(Long id, @ApiParam("状态") Integer status,String content) { + return orderTakingService.updateTakingStatus(id, status,content); + } + + /** + * 删除发布接单 + */ + @ApiOperation("删除发布接单") + @GetMapping("/deleteTaking") + public Result deleteTaking(Long id) { + + return orderTakingService.deleteTaking(id); + } + + /** + * 查询接单想详情 + */ + @ApiOperation("查询接单详情") + @GetMapping("/queryTakingOrder") + public Result queryTakingOrder(Long id,Long userId) { + + return orderTakingService.queryTakingOrder(id,userId); + } + + /** + * 重新编辑 + */ + @ApiOperation("重新编辑") + @PostMapping("/updateTakingOrder") + @Login + public Result updateTakingOrder(@RequestBody OrderTaking orderTaking,@RequestAttribute Long userId) { + orderTaking.setUserId(userId); + return orderTakingService.updateTakingOrder(orderTaking); + } + + + + /** + * 查看我的接单 + */ + @ApiOperation("查看我的接单") + @GetMapping("/queryMyTakingOrder") + @Login + public Result queryMyTakingOrder(@RequestAttribute Long userId, Long page, Long limit,Long status) { + return orderTakingService.queryMyTakingOrder(userId,page,limit,status); + } + + + @GetMapping("/selectShopData") + @ApiOperation("商户首页数据统计") + @Login + public Result selectShopData(@RequestAttribute Long userId,String startTime,String endTime){ + return orderTakingService.selectShopData(userId, startTime, endTime); + } + + + @GetMapping("/getOrderTakingList") + @ApiOperation("一键下单服务列表") + public Result getOrderTakingList(Integer page, Integer limit, Long laundryId) { + return Result.success().put("data", orderTakingService.getOrderTakingList(page, limit,laundryId)); + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/dao/CollectOrderTakingDao.java b/src/main/java/com/sqx/modules/taking/dao/CollectOrderTakingDao.java new file mode 100644 index 0000000..23a9498 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/CollectOrderTakingDao.java @@ -0,0 +1,10 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.taking.entity.CollectOrderTaking; +import com.sqx.modules.taking.entity.Game; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface CollectOrderTakingDao extends BaseMapper { +} diff --git a/src/main/java/com/sqx/modules/taking/dao/GameDao.java b/src/main/java/com/sqx/modules/taking/dao/GameDao.java new file mode 100644 index 0000000..1780d9f --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/GameDao.java @@ -0,0 +1,9 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.taking.entity.Game; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface GameDao extends BaseMapper { +} diff --git a/src/main/java/com/sqx/modules/taking/dao/GoodsAttrDao.java b/src/main/java/com/sqx/modules/taking/dao/GoodsAttrDao.java new file mode 100644 index 0000000..61f5e03 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/GoodsAttrDao.java @@ -0,0 +1,12 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.taking.entity.GoodsAttr; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface GoodsAttrDao extends BaseMapper { + + int insertGoodsAttr(GoodsAttr goodsAttr); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/dao/GoodsAttrValueDao.java b/src/main/java/com/sqx/modules/taking/dao/GoodsAttrValueDao.java new file mode 100644 index 0000000..0bb4768 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/GoodsAttrValueDao.java @@ -0,0 +1,11 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.taking.entity.GoodsAttrValue; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface GoodsAttrValueDao extends BaseMapper { + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/dao/GoodsRuleMapper.java b/src/main/java/com/sqx/modules/taking/dao/GoodsRuleMapper.java new file mode 100644 index 0000000..fd678c3 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/GoodsRuleMapper.java @@ -0,0 +1,16 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.taking.entity.GoodsRule; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface GoodsRuleMapper extends BaseMapper { + + int insertGoodsRule(GoodsRule goodsRule); + + IPage selectRuleByShopId(Page page); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/dao/GoodsRuleValueMapper.java b/src/main/java/com/sqx/modules/taking/dao/GoodsRuleValueMapper.java new file mode 100644 index 0000000..0ef4d82 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/GoodsRuleValueMapper.java @@ -0,0 +1,11 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.taking.entity.GoodsRuleValue; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface GoodsRuleValueMapper extends BaseMapper { + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/dao/GoodsSkuDao.java b/src/main/java/com/sqx/modules/taking/dao/GoodsSkuDao.java new file mode 100644 index 0000000..645cb11 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/GoodsSkuDao.java @@ -0,0 +1,11 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sqx.modules.taking.entity.GoodsSku; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface GoodsSkuDao extends BaseMapper { + + +} diff --git a/src/main/java/com/sqx/modules/taking/dao/OrderTakingCommentDao.java b/src/main/java/com/sqx/modules/taking/dao/OrderTakingCommentDao.java new file mode 100644 index 0000000..a8f0611 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/OrderTakingCommentDao.java @@ -0,0 +1,32 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.modules.taking.entity.CommentFabulous; +import com.sqx.modules.taking.entity.TakingCommnt; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.Map; + +@Mapper +public interface OrderTakingCommentDao extends BaseMapper { + IPage> selectOrderTakingComment(IPage page, @Param("takingId") Long id); + + IPage> selectCommentByOrderTakingUserId(IPage page, @Param("userId") Long userId); + + int selectCommentNumber(@Param("id") Long id); + + CommentFabulous selectGoodsNum(@Param("commentId") Long commentId, @Param("userId") Long userId); + + int deleteGoodsNum(@Param("id") Long id); + + int insertGoodsNum(@Param("commentId") Long commentId, @Param("userId") Long userId); + + Double selectAvgScore(@Param("orderTakingId") Long orderTakingId); + + Double selectAvgScoreByUserId(@Param("userId") Long userId); + + Integer selectCommntCountByUserId(Long userId,String startTime,String endTime); + +} diff --git a/src/main/java/com/sqx/modules/taking/dao/OrderTakingDao.java b/src/main/java/com/sqx/modules/taking/dao/OrderTakingDao.java new file mode 100644 index 0000000..49233ed --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/OrderTakingDao.java @@ -0,0 +1,43 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.taking.entity.OrderTaking; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface OrderTakingDao extends BaseMapper { + + IPage queryTaking(Page page,@Param("city") String city, @Param("longitude") String longitude, + @Param("latitude") String latitude, @Param("like") String like, @Param("condition") Integer condition, + @Param("bannerid") Long bannerid, @Param("isRecommend") Long isRecommend, @Param("id") Long id, + @Param("sex") Long sex, @Param("by") String by,@Param("classify") Integer classify, + @Param("isIntegral") Integer isIntegral,@Param("laundryId") Long laundryId); + + List queryLowTaking(String longitude,String latitude,@Param("laundryId") Long laundryId); + + IPage queryLowTakings(Page pages,String longitude,String latitude,@Param("laundryId") Long laundryId); + + OrderTaking queryTakingDetails(@Param("id") Long id,String longitude,String latitude); + + IPage selectMyRelease(Page page, @Param("userId") Long userId, @Param("status") String status); + + IPage queryAllOrderTaking(Page page, @Param("gameId") Long gameId, @Param("status") Long status, @Param("userName") String userName, @Param("userId") Long userId, @Param("classify") Integer classify, String longitude, String latitude, Integer isIntegral, String serviceName, @Param("laundryId") Long laundryId, Integer serviceType); + + Integer countGoodsByCreateTime(@Param("time")String time,@Param("flag")Integer flag); + + Double sumGoodsByCreateTime(@Param("time")String time,@Param("flag")Integer flag); + + int updateTakingStatusByUserId(@Param("userId") Long userId); + + + Integer selectOrderTakingCountByUserId(Long userId,Integer status); + + IPage> selectOrderTakingStockList(Page> page,Long laundryId,String serviceName,String detailJson,String stock); + +} diff --git a/src/main/java/com/sqx/modules/taking/dao/OrderTakingRewardDao.java b/src/main/java/com/sqx/modules/taking/dao/OrderTakingRewardDao.java new file mode 100644 index 0000000..cc39d9a --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/dao/OrderTakingRewardDao.java @@ -0,0 +1,18 @@ +package com.sqx.modules.taking.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.taking.entity.OrderTakingReward; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.Map; + +@Mapper +public interface OrderTakingRewardDao extends BaseMapper { + + IPage> selectOrderTakingRewardList(Page> page,@Param("userId") Long userId,@Param("orderTakingId") Long orderTakingId); + + +} diff --git a/src/main/java/com/sqx/modules/taking/entity/CollectOrderTaking.java b/src/main/java/com/sqx/modules/taking/entity/CollectOrderTaking.java new file mode 100644 index 0000000..ca8d606 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/CollectOrderTaking.java @@ -0,0 +1,47 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description collect_order_taking + * @author fang + * @date 2022-10-10 + */ +@Data +public class CollectOrderTaking implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 收藏id + */ + private Long collectOrderTakingId; + + /** + * 用户id + */ + private Long userId; + + /** + * 服务id + */ + private Long orderTakingId; + + @TableField(exist = false) + private OrderTaking orderTaking; + + /** + * 时间 + */ + private String createTime; + + public CollectOrderTaking() {} +} diff --git a/src/main/java/com/sqx/modules/taking/entity/CommentFabulous.java b/src/main/java/com/sqx/modules/taking/entity/CommentFabulous.java new file mode 100644 index 0000000..170d295 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/CommentFabulous.java @@ -0,0 +1,41 @@ +package com.sqx.modules.taking.entity; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description comment_fabulous + * @author liyuan + * @date 2021-08-12 + */ +@Data +@ApiModel("comment_fabulous") +public class CommentFabulous implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + /** + * 点赞id + */ + @ApiModelProperty("点赞id") + private Long id; + + /** + * 接单评论id + */ + @ApiModelProperty("接单评论id") + private Long takingCommentId; + + /** + * 用户id + */ + @ApiModelProperty("用户id") + private Long userId; + + public CommentFabulous() {} +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/entity/Game.java b/src/main/java/com/sqx/modules/taking/entity/Game.java new file mode 100644 index 0000000..a9eff61 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/Game.java @@ -0,0 +1,43 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.io.Serializable; +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +@ApiModel("游戏分类") +public class Game implements Serializable { + @ApiModelProperty("id") + @TableId(type = IdType.AUTO) + private Long id; + @ApiModelProperty("游戏名称") + @TableField("game_name") + private String gameName; + @ApiModelProperty("0启用1删除") + @TableField("status") + private Long status; + @ApiModelProperty("创建时间") + @TableField("create_time") + private String createTime; + @ApiModelProperty("修改时间") + @TableField("update_time") + private String updateTime; + @ApiModelProperty("游戏图片") + @TableField("game_img") + private String gameImg; + @TableField(exist = false) + private List orderTakingList; + +} diff --git a/src/main/java/com/sqx/modules/taking/entity/GoodsAttr.java b/src/main/java/com/sqx/modules/taking/entity/GoodsAttr.java new file mode 100644 index 0000000..2330dee --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/GoodsAttr.java @@ -0,0 +1,41 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +@Data +@ApiModel("goods_attr") +public class GoodsAttr implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + + @ApiModelProperty("规格id") + private Long id; + + + @ApiModelProperty("属性名称") + private String attrName; + + + @ApiModelProperty("商品id") + private Long goodsId; + + + @ApiModelProperty("规格模板id") + private Long ruleId; + + @ApiModelProperty("规格值") + @TableField(exist = false) + private List attrValue; + + public GoodsAttr() {} +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/entity/GoodsAttrValue.java b/src/main/java/com/sqx/modules/taking/entity/GoodsAttrValue.java new file mode 100644 index 0000000..55fc425 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/GoodsAttrValue.java @@ -0,0 +1,39 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +@Data +@ApiModel("goods_attr_value") +public class GoodsAttrValue implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + + @ApiModelProperty("属性id") + private Long id; + + + @ApiModelProperty("属性值组合:{尺寸: 7寸 , 颜色: 红底 }") + private String detail; + + + @ApiModelProperty("商品id") + private Long goodsId; + + + @ApiModelProperty("商品规格id") + private Long attrId; + + + @ApiModelProperty("规格属性名称") + private String value; + + public GoodsAttrValue() {} +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/entity/GoodsRule.java b/src/main/java/com/sqx/modules/taking/entity/GoodsRule.java new file mode 100644 index 0000000..6148aae --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/GoodsRule.java @@ -0,0 +1,36 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author fang + * @date 2021.9.14 + * 商品规格 + */ +@Data +public class GoodsRule { + + @TableId(type = IdType.INPUT) + @ApiModelProperty("id") + private Long id; + + @ApiModelProperty("规格名称") + private String ruleName; + + @ApiModelProperty("游戏id") + private Long gameId; + + @ApiModelProperty("创建时间") + private String createTime; + + @ApiModelProperty("规格值") + @TableField(exist = false) + private List ruleValue; + +} diff --git a/src/main/java/com/sqx/modules/taking/entity/GoodsRuleValue.java b/src/main/java/com/sqx/modules/taking/entity/GoodsRuleValue.java new file mode 100644 index 0000000..86fb9bb --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/GoodsRuleValue.java @@ -0,0 +1,29 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author fang + * @date 2021.9.14 + * 商品规格属性 + */ +@Data +public class GoodsRuleValue { + + @TableId(type = IdType.INPUT) + @ApiModelProperty("id") + private Long id; + + @ApiModelProperty("规格id") + private Long ruleId; + + @ApiModelProperty("规格属性名称") + private String value; + + @ApiModelProperty("规格属性值") + private String detail; + +} diff --git a/src/main/java/com/sqx/modules/taking/entity/GoodsSku.java b/src/main/java/com/sqx/modules/taking/entity/GoodsSku.java new file mode 100644 index 0000000..e4c4f5b --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/GoodsSku.java @@ -0,0 +1,58 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * @author fang + * @date 2021.9.14 + * 商品sku + */ + +@Data +@ApiModel("goods_sku") +public class GoodsSku implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + + @ApiModelProperty("id") + private Long id; + + + @ApiModelProperty("商品id") + private Long goodsId; + + + @ApiModelProperty("sku图片") + private String skuImg; + + + @ApiModelProperty("sku原价") + private BigDecimal skuMemberPrice; + + + @ApiModelProperty("sku商品售价") + private BigDecimal skuPrice; + + + @ApiModelProperty("库存") + private Integer stock; + + + @ApiModelProperty("销量") + private Integer sales; + + + @ApiModelProperty("sku信息,json封装") + private String detailJson; + + public GoodsSku() {} +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/entity/OrderTaking.java b/src/main/java/com/sqx/modules/taking/entity/OrderTaking.java new file mode 100644 index 0000000..e0b2b82 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/OrderTaking.java @@ -0,0 +1,123 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.sqx.modules.orders.entity.Orders; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +public class OrderTaking implements Serializable { + @ApiModelProperty("接单id") + @TableId(type = IdType.AUTO, value = "id") + private Long id; + @ApiModelProperty("游戏id类型") + @TableField("game_id") + private String gameId; + @TableField(exist = false) + private String gameName; + @TableField(exist = false) + private Game game; + @ApiModelProperty("我的段位") + @TableField("my_level") + private String myLevel; + @ApiModelProperty("接单段位") + @TableField("order_level") + private String orderLevel; + @ApiModelProperty("接单时间") + @TableField("order_taking_time") + private String orderTakingTime; + @ApiModelProperty("接单大区") + @TableField("order_taking_area") + private String orderTakingArea; + @ApiModelProperty("价格") + @TableField("old_money") + private BigDecimal oldMoney; + @ApiModelProperty("价格") + @TableField("money") + private BigDecimal money; + @ApiModelProperty("会员价格") + @TableField("member_money") + private BigDecimal memberMoney; + @ApiModelProperty("语音介绍") + @TableField("voice_introduce") + private String voiceIntroduce; + @ApiModelProperty("主页图片") + @TableField("homepage_img") + private String homepageImg; + @ApiModelProperty("详情图") + @TableField("details_img") + private String detailsImg; + @ApiModelProperty("创建时间") + @TableField("create_time") + private String createTime; + @ApiModelProperty("接单状态0进行中1待审核2已取消") + @TableField("status") + private int status; + @ApiModelProperty("修改时间") + @TableField("update_time") + private String updateTime; + @ApiModelProperty("是否是推荐接单0是1不是") + @TableField("is_recommend") + private String isRecommend; + @ApiModelProperty("发布人") + @TableField("user_id") + private Long userId; + @ApiModelProperty("城市") + private String city; + @ApiModelProperty("人数") + private Integer count; + @ApiModelProperty("评分") + @TableField("order_score") + private Double orderScore; + @ApiModelProperty("精度") + private String longitude; + @ApiModelProperty("维度") + private String latitude; + @TableField(exist = false) + private List orders = new ArrayList<>(); + @ApiModelProperty("假删除") + private Long isdelete; + private String content; + private Integer sec; + private Integer classify; + private String unit; + private Integer salesNum; + private Integer authentication; + private String region; + private String detailadd; + private String serviceName; + private Integer minNum; + private Integer sort; + @TableLogic + private Integer isDelete; + @ApiModelProperty("积分商品 1是") + private String isIntegral; + @ApiModelProperty("站点id") + private String laundryIds; + + @ApiModelProperty("是否需要压桶 0否 1是") + private Integer isNeedBucket; + + @TableField(exist = false) + private String laundryName; + @TableField(exist = false) + private List goodsSkuList; + + @TableField(exist = false) + private List goodsAttrList; + +} diff --git a/src/main/java/com/sqx/modules/taking/entity/OrderTakingReward.java b/src/main/java/com/sqx/modules/taking/entity/OrderTakingReward.java new file mode 100644 index 0000000..8480a28 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/OrderTakingReward.java @@ -0,0 +1,43 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.math.BigDecimal; + +/** + * @author fang + * @date 2021/12/27 + */ +@Data +public class OrderTakingReward { + private static final long serialVersionUID = 1L; + + /** + * 打赏id + */ + @TableId(type = IdType.AUTO, value = "id") + private Long rewardId; + + /** + * 用户id + */ + private Long userId; + + /** + * 动态id + */ + private Long orderTakingId; + + /** + * 金额 + */ + private BigDecimal money; + + /** + * 时间 + */ + private String createTime; + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/entity/TakingCommnt.java b/src/main/java/com/sqx/modules/taking/entity/TakingCommnt.java new file mode 100644 index 0000000..36979d9 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/entity/TakingCommnt.java @@ -0,0 +1,52 @@ +package com.sqx.modules.taking.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +@ApiModel("接单评论") +public class TakingCommnt implements Serializable { + @TableId(type = IdType.AUTO) + private Long id; + /** + * 接单id + */ + private Long orderTakingId; + /** + * 用户id + */ + private Long userId; + /** + * 评论内容 + */ + private String content; + /** + * 创建时间 + */ + private String createTime; + /** + * 点赞次数 + */ + @TableField(exist = false) + private Long count; + /** + * 邮件 + */ + private String mail; + + private Integer score; + + private Long ordersId; + +} diff --git a/src/main/java/com/sqx/modules/taking/response/MyReleaseResponse.java b/src/main/java/com/sqx/modules/taking/response/MyReleaseResponse.java new file mode 100644 index 0000000..af401b7 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/response/MyReleaseResponse.java @@ -0,0 +1,46 @@ +package com.sqx.modules.taking.response; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +public class MyReleaseResponse implements Serializable { + /** + * 接单id + */ + private Long id; + /** + * 发布状态 + */ + private String status; + /** + * 更新时间 + */ + private String updateTime; + /** + * 游戏名称 + */ + private String gameName; + /** + * 价格 + */ + private Double money; + /** + * 接单时间 + */ + private String orderTakingTime; + private BigDecimal oldMoney; + private BigDecimal memberMoney; + private String gameImg; + private String content; + private String city; + private Integer sec; + private String createTime; + private Integer classify; + private String unit; + private String myLevel; + private String count; + private String orderScore; +} diff --git a/src/main/java/com/sqx/modules/taking/response/OrderTakingResponse.java b/src/main/java/com/sqx/modules/taking/response/OrderTakingResponse.java new file mode 100644 index 0000000..23a6b83 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/response/OrderTakingResponse.java @@ -0,0 +1,68 @@ +package com.sqx.modules.taking.response; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +public class OrderTakingResponse implements Serializable { + /** + * 接单id + */ + private Long id; + /** + * 发布人id + */ + private Long userId; + + /** + * 发布人姓名 + */ + private String userName; + + /** + * 性别 + */ + private Integer sex; + + /** + * 年龄 + */ + private Integer age; + /** + * 发布城市 + */ + private String city; + /** + * 发布人图像 + */ + private String avatar; + /** + * 接单游戏 + */ + private String gameName; + /** + * 我的段位 + */ + private String myLevel; + /** + * 订单评分 + */ + private Double orderScore; + /** + * 价钱 + */ + private BigDecimal money; + /** + * 服务人数 + */ + private int count; + private BigDecimal oldMoney; + private BigDecimal memberMoney; + private String gameImg; + private Integer sec; + private Integer classify; + private String unit; + private Integer distance; +} diff --git a/src/main/java/com/sqx/modules/taking/response/TakingCommentResponse.java b/src/main/java/com/sqx/modules/taking/response/TakingCommentResponse.java new file mode 100644 index 0000000..642d7f2 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/response/TakingCommentResponse.java @@ -0,0 +1,46 @@ +package com.sqx.modules.taking.response; + +import com.baomidou.mybatisplus.annotation.TableField; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +@Data +public class TakingCommentResponse implements Serializable { + + /** + * 评论id + */ + private Long id; + /** + * 用户名 + */ + @ApiModelProperty("用户名") + @TableField("user_name") + private String userName; + + /** + * 头像 + */ + @ApiModelProperty("头像") + private String avatar; + /** + * 评论内容 + */ + private String content; + /** + * 点赞量 + */ + private int count; + /** + * 等级 + */ + private String grade; + + private Integer score; + + private String createTime; + + +} diff --git a/src/main/java/com/sqx/modules/taking/response/TakingDetailsResponse.java b/src/main/java/com/sqx/modules/taking/response/TakingDetailsResponse.java new file mode 100644 index 0000000..d3db8d0 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/response/TakingDetailsResponse.java @@ -0,0 +1,88 @@ +package com.sqx.modules.taking.response; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * 接单详情返回字段 + */ +@Data +public class TakingDetailsResponse implements Serializable { + + + private Long id; + /** + *发布用户id + */ + private Long userId; + /** + * 主页显示图片 + */ + private String homepageImg; + /** + * 用户图像 + */ + private String avatar; + /** + * 用户名 + */ + private String userName; + /** + * 城市 + */ + private String city; + /** + * 游戏名称 + */ + private String gameName; + /** + * 性别 1男 2女 + */ + private Integer sex; + /** + * 年龄 + */ + private Integer age; + /** + * 价格 + */ + private Double money; + /** + * 单位 + */ + private String unitType; + /** + * 评分 + */ + private Double orderScore; + /** + * 下单 + */ + private int count; + /** + * 语音介绍 + */ + private String voiceIntroduce; + /** + * 接单大区 + */ + private String orderTakingArea; + /** + * 接单时间 + */ + private String orderTakingTime; + private BigDecimal oldMoney; + private BigDecimal memberMoney; + private String gameImg; + private Integer sec; + private String createTime; + private String myLevel; + private Integer classify; + private String unit; + private Integer rewardCount; + private Integer myRewardCount; + private Integer distance; + private String status; +} diff --git a/src/main/java/com/sqx/modules/taking/response/TakingResponse.java b/src/main/java/com/sqx/modules/taking/response/TakingResponse.java new file mode 100644 index 0000000..5a5baa4 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/response/TakingResponse.java @@ -0,0 +1,81 @@ +package com.sqx.modules.taking.response; + +import com.baomidou.mybatisplus.annotation.TableField; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * 接单返回字段 + */ +@Data +public class TakingResponse implements Serializable { + @ApiModelProperty("接单id") + private Long id; + @ApiModelProperty("游戏id类型") + @TableField("game_id") + private Long gameId; + @TableField(exist = false) + private String gameName; + @ApiModelProperty("我的段位") + @TableField("my_level") + private String myLevel; + @ApiModelProperty("接单段位") + @TableField("order_level") + private String orderLevel; + @ApiModelProperty("接单时间") + @TableField("order_taking_time") + private String orderTakingTime; + @ApiModelProperty("接单大区") + @TableField("order_taking_area") + private String orderTakingArea; + @ApiModelProperty("价格") + @TableField("money") + private BigDecimal money; + @ApiModelProperty("语音介绍") + @TableField("voice_introduce") + private String voiceIntroduce; + @ApiModelProperty("主页图片") + @TableField("homepage_img") + private String homepageImg; + @ApiModelProperty("创建时间") + @TableField("create_time") + private String createTime; + @ApiModelProperty("接单状态0进行中1待审核2已取消3完成") + @TableField("status") + private int status; + @ApiModelProperty("是否是推荐接单0是1不是") + @TableField("is_recommend") + private String isRecommend; + @ApiModelProperty("发布人") + @TableField("user_id") + private Long userId; + @TableField(exist = false) + private String userName; + @TableField(exist = false) + private String avatar; + @ApiModelProperty("城市") + private String city; + @ApiModelProperty("人数") + private int count; + @ApiModelProperty("评分") + @TableField("order_score") + private Double orderScore; + @ApiModelProperty("精度") + private String longitude; + @ApiModelProperty("维度") + private String latitude; + private BigDecimal oldMoney; + private BigDecimal memberMoney; + private String content; + private String gameImg; + private Integer sec; + private Integer sex; + private Integer age; + private Integer classify; + private String unit; + private Integer distance; +// private String createTime; +} diff --git a/src/main/java/com/sqx/modules/taking/service/CollectOrderTakingService.java b/src/main/java/com/sqx/modules/taking/service/CollectOrderTakingService.java new file mode 100644 index 0000000..736feb9 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/CollectOrderTakingService.java @@ -0,0 +1,16 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.CollectOrderTaking; +import com.sqx.modules.taking.entity.Game; + +public interface CollectOrderTakingService extends IService { + + Result insertCollectOrderTaking(Long orderTakingId,Long userId); + + CollectOrderTaking selectOrderTakingByUserId(Long orderTakingId,Long userId ); + + Result selectCollectOrderTakingList(Integer page,Integer limit,Long userId); + +} diff --git a/src/main/java/com/sqx/modules/taking/service/GameService.java b/src/main/java/com/sqx/modules/taking/service/GameService.java new file mode 100644 index 0000000..28bc294 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/GameService.java @@ -0,0 +1,57 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.Game; + +public interface GameService extends IService { + + + Result queryGameNameList(); + + /** + * 查询首页游戏分类 + * + * @return + */ + Result queryGameName(); + + + /** + * 添加游戏分类 + * + * @param + * @return + */ + Result addGameName(String gameName,String gameImg); + + /** + * 修改游戏分类 + * + * @param + * @return + */ + Result updateGameName(Long id, String gameName,String gameImg, Long status); + + /** + * 删除游戏分类 + * + * @param id + * @return + */ + Result deleteGameName(Long id); + + /** + * 查看所有游戏分类信息 + * + * @param page + * @param limit + * @return + */ + Result queryAllGameName(Long page, Long limit); + + /** + * 是否启用游戏分类 + */ + Result enableGameName(Long status, Long id); +} diff --git a/src/main/java/com/sqx/modules/taking/service/GoodsAttrService.java b/src/main/java/com/sqx/modules/taking/service/GoodsAttrService.java new file mode 100644 index 0000000..564b609 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/GoodsAttrService.java @@ -0,0 +1,21 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.taking.entity.GoodsAttr; + +import java.util.List; + +public interface GoodsAttrService extends IService { + + int updateGoodsAttr(List goodsAttrList,Long goodsId); + + void deleteAttrAndValue(Long goodsId); + + int deleteGoodsAttr(Long goodsId); + + int saveGoodsAttr(GoodsAttr goodsAttr); + + List findByGoodsId(Long goodsId); + + List findAllByGoodsId(Long goodsId); +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/GoodsAttrValueService.java b/src/main/java/com/sqx/modules/taking/service/GoodsAttrValueService.java new file mode 100644 index 0000000..3578392 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/GoodsAttrValueService.java @@ -0,0 +1,14 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.taking.entity.GoodsAttrValue; + +import java.util.List; + +public interface GoodsAttrValueService extends IService { + + List findAllByGoodsId(Long goodsId); + + int deleteGoodsAttrValueByGoodsId(Long goodsId); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/GoodsRuleService.java b/src/main/java/com/sqx/modules/taking/service/GoodsRuleService.java new file mode 100644 index 0000000..05ef2d0 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/GoodsRuleService.java @@ -0,0 +1,32 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.GoodsAttr; +import com.sqx.modules.taking.entity.GoodsRule; + +public interface GoodsRuleService extends IService { + + Result findAll(Integer page, Integer limit); + + Result info(); + + Result saveBody(GoodsRule goodsRule); + + Result updateBody(GoodsRule goodsRule); + + Result findOne(Long id); + + Result delete(Long id); + + Result onlyFormatAttr(String coverImg, String skuMemberPrice, String price); + + Result isFormatAttr(GoodsAttr goodsAttr, String coverImg, String skuMemberPrice, String price); + + Result formatAttr(Long goodsId); + + Result findAttrValue(Long goodsId); + + Result updateStock(Long skuId,Integer num); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/GoodsRuleValueService.java b/src/main/java/com/sqx/modules/taking/service/GoodsRuleValueService.java new file mode 100644 index 0000000..29a3d56 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/GoodsRuleValueService.java @@ -0,0 +1,14 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.modules.taking.entity.GoodsRuleValue; + +import java.util.List; + +public interface GoodsRuleValueService extends IService { + + List selectGoodsRuleValue(Long ruleId); + + int deleteGoodsRuleValue( Long ruleId); + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/GoodsSkuService.java b/src/main/java/com/sqx/modules/taking/service/GoodsSkuService.java new file mode 100644 index 0000000..be97d73 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/GoodsSkuService.java @@ -0,0 +1,19 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.GoodsSku; + +import java.util.List; + +public interface GoodsSkuService extends IService { + + Result insertSku(GoodsSku goodsSku); + + int deleteGoodsSkuByGoodsId(Long goodsId); + + List selectGoodsSkuByGoodsId(Long goodsId); + + + +} diff --git a/src/main/java/com/sqx/modules/taking/service/OrderTakingCommentService.java b/src/main/java/com/sqx/modules/taking/service/OrderTakingCommentService.java new file mode 100644 index 0000000..d7c3a79 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/OrderTakingCommentService.java @@ -0,0 +1,42 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.TakingCommnt; + +public interface OrderTakingCommentService extends IService { + /** + * 查看接单的评论 + */ + Result selectOrderTakingComment(Integer page, Integer limit, Long id); + + Result selectCommentByOrderTakingUserId(Integer page, Integer limit, Long userId); + + /** + * 点赞 + * + * @param commentId + * @param userId + * @return + */ + Result updateGoodsNum(Long commentId, Long userId); + + /** + * 添加评论 + * + * @param id + * @param userId + * @param content + */ + Result addGoodsNum(Long id, Long userId, String content, Integer score,Long ordersId); + + /** + * 我的评论 + * + * @param userId + * @return + */ + Result queryMyComment(Long userId); + + int selectTakingCommentCount(Long orderTakingId,Long userId); +} diff --git a/src/main/java/com/sqx/modules/taking/service/OrderTakingRewardService.java b/src/main/java/com/sqx/modules/taking/service/OrderTakingRewardService.java new file mode 100644 index 0000000..15d50ba --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/OrderTakingRewardService.java @@ -0,0 +1,15 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.OrderTakingReward; + +import java.math.BigDecimal; + +public interface OrderTakingRewardService extends IService { + + Result rewardMoney(Long userId, BigDecimal money, Long orderTakingId); + + Result selectOrderTakingRewardList(Integer page,Integer limit,Long userId,Long orderTakingId); + +} diff --git a/src/main/java/com/sqx/modules/taking/service/OrderTakingService.java b/src/main/java/com/sqx/modules/taking/service/OrderTakingService.java new file mode 100644 index 0000000..0fd50e0 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/OrderTakingService.java @@ -0,0 +1,90 @@ +package com.sqx.modules.taking.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.entity.OrderTaking; + +public interface OrderTakingService extends IService { + /** + * + */ + Result queryTaking(String city, String longitude, String latitude, Long userId, + String like, String condition, Long bannerid, Long isRecommend, + Long id, Page iPage, Long sex, String by, Integer classify, + Integer isGood,Long laundryId); + + /** + * 查询乐享低价系列 + * + * @return + */ + Result queryLowTaking(Integer page,Integer limit,String longitude,String latitude,Long laundryId); + + + /** + * 接单详情 + */ + Result queryTakingDetails(Long id, Long userId,String longitude,String latitude); + + /** + * 发布接单 + */ + Result insertOrderTaking(OrderTaking orderTaking); + + Result selectOrderTakingStockList(Integer page,Integer limit,Long laundryId,String serviceName,String detailJson); + + /** + * 查看我的发布 + * + * @return + */ + Result selectMyRelease(Long userId, Long page, Long limit, String status); + + /** + * 删除接单 + */ + Result deleteOrderTaking(Long id); + + /** + * 查询所有接单 + */ + Result queryAllOrderTaking(Integer page, Integer limit, Long gameId, Long status, String userName, Long userId, Integer classify, String longitude, String latitude, Integer isIntegral, String serviceName, Long laundryId, Integer serviceType); + + /** + * 审核接单 + */ + Result auditorOrderTaking(Long id, Integer status,String content); + + /** + * 修改发布订单 + */ + Result updateTakingStatus(Long id, Integer status,String content); + + /** + * 删除发布接单 + */ + Result deleteTaking(Long id); + + /** + * 查询接单详情 + */ + Result queryTakingOrder(Long id,Long userId); + + /** + * 修改接单详情 + */ + Result updateTakingOrder(OrderTaking orderTaking); + + Result updateTakingOrders(OrderTaking orderTaking); + + /** + * 查看我的接单 + */ + Result queryMyTakingOrder(Long userId,Long page, Long limit,Long status); + + Result selectShopData(Long userId,String startTime,String endTime); + + IPage getOrderTakingList(Integer page, Integer limit, Long laundryId); +} diff --git a/src/main/java/com/sqx/modules/taking/service/impl/CollectOrderTakingServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/CollectOrderTakingServiceImpl.java new file mode 100644 index 0000000..2bc1109 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/CollectOrderTakingServiceImpl.java @@ -0,0 +1,78 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.DateUtils; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.dao.CollectOrderTakingDao; +import com.sqx.modules.taking.dao.GameDao; +import com.sqx.modules.taking.entity.CollectOrderTaking; +import com.sqx.modules.taking.entity.Game; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.CollectOrderTakingService; +import com.sqx.modules.taking.service.GameService; +import com.sqx.modules.taking.service.OrderTakingService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +@Slf4j +@Service +public class CollectOrderTakingServiceImpl extends ServiceImpl implements CollectOrderTakingService { + + @Autowired + private OrderTakingService orderTakingService; + private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true); + + + @Override + public Result insertCollectOrderTaking(Long orderTakingId,Long userId){ + reentrantReadWriteLock.writeLock().lock(); + try{ + CollectOrderTaking collectOrderTaking = selectOrderTakingByUserId(orderTakingId, userId); + if(collectOrderTaking!=null){ + baseMapper.deleteById(collectOrderTaking.getCollectOrderTakingId()); + return Result.success("取消收藏"); + } + collectOrderTaking=new CollectOrderTaking(); + collectOrderTaking.setOrderTakingId(orderTakingId); + collectOrderTaking.setUserId(userId); + collectOrderTaking.setCreateTime(DateUtils.format(new Date())); + baseMapper.insert(collectOrderTaking); + return Result.success("收藏成功"); + }catch (Exception e){ + e.printStackTrace(); + log.error("收藏异常:"+e.getMessage(),e); + }finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请稍后再试!"); + } + + + @Override + public CollectOrderTaking selectOrderTakingByUserId(Long orderTakingId,Long userId ){ + return baseMapper.selectOne(new QueryWrapper().eq("order_taking_id",orderTakingId).eq("user_id",userId)); + } + + @Override + public Result selectCollectOrderTakingList(Integer page,Integer limit,Long userId){ + IPage orderTakingPage = baseMapper.selectPage(new Page<>(page, limit), new QueryWrapper().eq("user_id", userId)); + List records = orderTakingPage.getRecords(); + for(CollectOrderTaking collectOrderTaking:records){ + collectOrderTaking.setOrderTaking(orderTakingService.getById(collectOrderTaking.getOrderTakingId())); + } + return Result.success().put("data",new PageUtils(orderTakingPage)); + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/service/impl/GameServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/GameServiceImpl.java new file mode 100644 index 0000000..132d4d8 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/GameServiceImpl.java @@ -0,0 +1,125 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.dao.GameDao; +import com.sqx.modules.taking.entity.Game; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.GameService; +import com.sqx.modules.taking.service.OrderTakingService; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +@Service +@AllArgsConstructor +public class GameServiceImpl extends ServiceImpl implements GameService { + private OrderTakingService orderTakingService; + + @Override + public Result queryGameName() { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("status", 0); + List games = baseMapper.selectList(queryWrapper); + return Result.success().put("data", games); + } + + @Override + public Result queryGameNameList() { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("status", 0); + List games = baseMapper.selectList(queryWrapper); + for(Game game:games){ + game.setOrderTakingList(orderTakingService.list(new QueryWrapper().eq("game_id",game.getId()).eq("status",0).ne("is_delete",-1).orderByAsc("sort"))); + } + return Result.success().put("data", games); + } + + + + @Override + public Result addGameName(String gameName,String gameImg) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if (gameName == null) { + return Result.error("游戏分类信息为null"); + } else { + Game game = new Game(); + game.setCreateTime(simpleDateFormat.format(new Date())); + game.setUpdateTime(simpleDateFormat.format(new Date())); + game.setGameName(gameName); + game.setGameImg(gameImg); + game.setStatus((long) 0); + int i = baseMapper.insert(game); + if (i > 0) { + return Result.success(); + } else { + return Result.error(); + } + } + + } + + @Override + public Result updateGameName(Long id, String gameName, String gameImg,Long status) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Game game = baseMapper.selectById(id); + if (game == null) { + return Result.error("游戏分类信息为null"); + } else { + game.setUpdateTime(simpleDateFormat.format(new Date())); + game.setGameName(gameName); + game.setStatus(status); + game.setGameImg(gameImg); + int i = baseMapper.updateById(game); + if (i > 0) { + return Result.success(); + } else { + return Result.error(); + } + } + } + + @Override + public Result deleteGameName(Long id) { + + Game game = baseMapper.selectById(id); + if (game != null) { + baseMapper.deleteById(id); + return Result.success(); + } else { + return Result.error("游戏信息不存在!"); + + } + } + + @Override + public Result queryAllGameName(Long page, Long limit) { + if (page == null || limit == null) { + return Result.error("分页条件为空!"); + } else { + Page page1 = new Page<>(page, limit); + return Result.success().put("data", baseMapper.selectPage(page1, null)); + } + } + + @Override + public Result enableGameName(Long status, Long id) { + Game game = baseMapper.selectById(id); + if (game == null) { + return Result.error("游戏分类信息不存在"); + } else { + game.setStatus(status); + game.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + baseMapper.updateById(game); + return Result.success(); + } + + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/service/impl/GoodsAttrServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/GoodsAttrServiceImpl.java new file mode 100644 index 0000000..fb0f94e --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/GoodsAttrServiceImpl.java @@ -0,0 +1,77 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.taking.dao.GoodsAttrDao; +import com.sqx.modules.taking.entity.GoodsAttr; +import com.sqx.modules.taking.entity.GoodsAttrValue; +import com.sqx.modules.taking.service.GoodsAttrService; +import com.sqx.modules.taking.service.GoodsAttrValueService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class GoodsAttrServiceImpl extends ServiceImpl implements GoodsAttrService { + + @Autowired + private GoodsAttrValueService goodsAttrValueService; + + @Override + public int updateGoodsAttr(List goodsAttrList,Long goodsId) { + for(GoodsAttr goodsAttr:goodsAttrList){ + goodsAttr.setGoodsId(goodsId); + //放入新值 + for (GoodsAttrValue v : goodsAttr.getAttrValue()) { + v.setId(null); + v.setGoodsId(goodsAttr.getGoodsId()); + v.setAttrId(goodsAttr.getId()); + goodsAttrValueService.save(v); + } + baseMapper.insert(goodsAttr); + } + return 1; + } + + @Override + public void deleteAttrAndValue(Long goodsId){ + goodsAttrValueService.deleteGoodsAttrValueByGoodsId(goodsId); + deleteGoodsAttr(goodsId); + } + + @Override + public int deleteGoodsAttr(Long goodsId){ + return baseMapper.delete(new QueryWrapper().eq("goods_id",goodsId)); + } + + @Override + public List findAllByGoodsId(Long goodsId){ + return baseMapper.selectList(new QueryWrapper().eq("goods_id",goodsId)); + } + + @Override + public int saveGoodsAttr(GoodsAttr goodsAttr) { + baseMapper.insertGoodsAttr(goodsAttr); + List list = goodsAttr.getAttrValue(); + for (GoodsAttrValue goodsAttrValue : list) { + goodsAttrValue.setId(null); + goodsAttrValue.setGoodsId(goodsAttr.getGoodsId()); + goodsAttrValue.setAttrId(goodsAttr.getId()); + goodsAttrValueService.save(goodsAttrValue); + } + return 1; + } + + @Override + public List findByGoodsId(Long goodsId) { + List list = findAllByGoodsId(goodsId); + for (GoodsAttr goodsAttr : list) { + List valueList = goodsAttrValueService.findAllByGoodsId(goodsAttr.getGoodsId()); + goodsAttr.setAttrValue(valueList); + } + return list; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/impl/GoodsAttrValueServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/GoodsAttrValueServiceImpl.java new file mode 100644 index 0000000..e40f940 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/GoodsAttrValueServiceImpl.java @@ -0,0 +1,27 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.taking.dao.GoodsAttrValueDao; +import com.sqx.modules.taking.entity.GoodsAttrValue; +import com.sqx.modules.taking.service.GoodsAttrValueService; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class GoodsAttrValueServiceImpl extends ServiceImpl implements GoodsAttrValueService { + + + @Override + public List findAllByGoodsId(Long goodsId){ + return baseMapper.selectList(new QueryWrapper().eq("goods_id",goodsId)); + } + + + @Override + public int deleteGoodsAttrValueByGoodsId(Long goodsId){ + return baseMapper.delete(new QueryWrapper().eq("goods_id",goodsId)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/impl/GoodsRuleServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/GoodsRuleServiceImpl.java new file mode 100644 index 0000000..6a3a6cd --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/GoodsRuleServiceImpl.java @@ -0,0 +1,257 @@ +package com.sqx.modules.taking.service.impl; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.dao.GoodsRuleMapper; +import com.sqx.modules.taking.entity.*; +import com.sqx.modules.taking.service.*; +import com.sqx.modules.taking.utils.SkuUtil; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.text.SimpleDateFormat; +import java.util.*; + + +@Service +public class GoodsRuleServiceImpl extends ServiceImpl implements GoodsRuleService { + + @Autowired + private GoodsRuleMapper goodsRuleMapper; + @Autowired + private GoodsRuleValueService goodsRuleValueService; + @Autowired + private GoodsAttrService goodsAttrService; + @Autowired + private GoodsAttrValueService goodsAttrValueService; + @Autowired + private GoodsSkuService goodsSkuService; + + + @Override + public Result findAll(Integer page, Integer limit) { + if(page==null || limit==null){ + List goodsRules = baseMapper.selectList(null); + for (GoodsRule r : goodsRules) { + r.setRuleValue(goodsRuleValueService.selectGoodsRuleValue(r.getId())); + } + return Result.success().put("data",goodsRules); + }else{ + Page pages=new Page<>(page,limit); + IPage goodsRules = goodsRuleMapper.selectRuleByShopId(pages); + List records = goodsRules.getRecords(); + for (GoodsRule r : records) { + r.setRuleValue(goodsRuleValueService.selectGoodsRuleValue(r.getId())); + } + return Result.success().put("data",goodsRules); + } + + } + + @Override + public Result info() { + List all = baseMapper.selectList(null); + for (GoodsRule r : all) { + r.setRuleValue(goodsRuleValueService.selectGoodsRuleValue(r.getId())); + } + return Result.success().put("data",all); + } + + @Transactional + @Override + public Result saveBody(GoodsRule goodsRule) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + goodsRule.setCreateTime(sdf.format(new Date())); //创建时间 + baseMapper.insertGoodsRule(goodsRule); + List list = goodsRule.getRuleValue(); + for (GoodsRuleValue goodsRuleValue : list) { + goodsRuleValue.setRuleId(goodsRule.getId()); + goodsRuleValueService.save(goodsRuleValue); + } + return Result.success(); + } + + @Transactional + @Override + public Result updateBody(GoodsRule goodsRule) { + goodsRuleValueService.deleteGoodsRuleValue(goodsRule.getId()); + //放入新值 + List list = goodsRule.getRuleValue(); + for (GoodsRuleValue goodsRuleValue : list) { + goodsRuleValue.setRuleId(goodsRule.getId()); + goodsRuleValueService.save(goodsRuleValue); + } + baseMapper.updateById(goodsRule); + return Result.success(); + } + + @Override + public Result findOne(Long id) { + GoodsRule s = baseMapper.selectById(id); + s.setRuleValue(goodsRuleValueService.selectGoodsRuleValue(id)); + return Result.success().put("data",s); + } + + @Override + public Result delete(Long id) { + int ruleCount = goodsAttrService.count(new QueryWrapper().eq("rule_id", id).last(" and goods_id in (select id from order_taking where is_delete=0)")); + if(ruleCount>0){ + return Result.error("当前规格有商品正在使用,请移除后删除!"); + } + baseMapper.deleteById(id); + return Result.success(); + } + + @Override + public Result isFormatAttr(GoodsAttr goodsAttr, String coverImg, String skuMemberPrice, String price) { + //1.获取商品规格值 + List attr = goodsAttr.getAttrValue(); + int attrSize = attr.size(); + //2.准备返回值 + Map map = new HashMap<>(); + List header = new ArrayList<>(); //表头 + List> value = new ArrayList<>(); //规格排列组合 + //3.sku规格处理集合 + List> skuInputList = new ArrayList<>(); + //4.循环规格值 + for (int i = 0; i < attrSize; i++) { + //5.放入表头数据 + header.add(attr.get(i).getValue()); + //6.sku规格计算 + String detail = attr.get(i).getDetail(); + String[] split = detail.split(","); + List skuList = new ArrayList<>(Arrays.asList(split)); + skuInputList.add(skuList); + } + //8.sku规格种类 + List> skuList = SkuUtil.skuSort(skuInputList); //计算规格种类 + for (int i = 0; i < skuList.size(); i++) { + Map sku = new HashMap<>(); + List strings = skuList.get(i); + String[] arr = strings.toArray(new String[strings.size()]); + StringBuilder json = new StringBuilder(); + for (int j = 0; j < attrSize; j++) { + String arrString = arr[j]; + sku.put("value"+j, arrString); + json.append(arrString).append(","); + } + json = new StringBuilder(json.substring(0, json.length() - 1)); + sku.put("json", json.toString()); + sku.put("detailJson", json.toString()); +// sku.put("skuMemberPrice", skuMemberPrice); + sku.put("skuPrice", price); + sku.put("stock", 999); + sku.put("sales", 0); + value.add(sku); + } + //表头 +// if (StringUtils.isNotEmpty(skuMemberPrice)){ +// header.add("会员价"); +// } + header.add("售价"); + header.add("库存"); + header.add("操作"); + //数据放入返回map + map.put("header", header); + map.put("value", value); + return Result.success().put("data",map); + } + + @Override + public Result onlyFormatAttr(String coverImg, String skuMemberPrice, String price) { + Map map = new HashMap<>(); + List header = new ArrayList<>(); //表头 + //表头 +// if (StringUtils.isNotEmpty(skuMemberPrice)){ +// header.add("会员价"); +// } + header.add("售价"); + header.add("库存"); + List> value = new ArrayList<>(); //规格排列组合 + Map sku = new HashMap<>(); + sku.put("json", null); + sku.put("detailJson", null); +// sku.put("skuMemberPrice", skuMemberPrice); + sku.put("skuPrice", price); + sku.put("stock", 999); + sku.put("sales", 0); + value.add(sku); + //数据放入返回map + map.put("header", header); + map.put("value", value); + return Result.success().put("data",map); + } + + @Override + public Result formatAttr(Long goodsId) { + //1.获取商品规格值 + List attr = goodsAttrValueService.findAllByGoodsId(goodsId); + //sku集合 + List goodsSkuList = goodsSkuService.selectGoodsSkuByGoodsId(goodsId); + int attrSize = attr.size(); + //2.准备返回值 + Map map = new HashMap<>(); + List header = new ArrayList<>(); //表头 + List> value = new ArrayList<>(); //规格排列组合 + if (attrSize > 0){ + //4.循环规格值 + for (int i = 0; i < attrSize; i++) { + //5.放入表头数据 + header.add(attr.get(i).getValue()); + } + } +// header.add("会员价"); + header.add("售价"); + header.add("库存"); + header.add("操作"); + //5.sku数据放入 + for (GoodsSku s : goodsSkuList) { + Map sku = new HashMap<>(); + String detailJson = s.getDetailJson(); + if (detailJson != null){ + String[] split = detailJson.split(","); + for (int i = 0; i < split.length; i++) { + sku.put("value"+i, split[i]); + } + } + sku.put("detailJson", detailJson); +// sku.put("skuMemberPrice", s.getSkuMemberPrice()); + sku.put("skuPrice", s.getSkuPrice()); + sku.put("stock", s.getStock()); + sku.put("sales", s.getSales()); + value.add(sku); + } + //数据放入返回map + map.put("header", header); + map.put("value", value); + return Result.success().put("data",map); + } + + @Override + public Result findAttrValue(Long goodsId) { + List attrList = goodsAttrService.findAllByGoodsId(goodsId); + GoodsAttr s = new GoodsAttr(); + if (attrList.size() > 0 ){ + s = attrList.get(0); + s.setAttrValue(goodsAttrValueService.findAllByGoodsId(goodsId)); + } + return Result.success().put("data",s); + } + + @Override + public Result updateStock(Long skuId,Integer num){ + GoodsSku goodsSku = goodsSkuService.getById(skuId); + goodsSku.setStock(goodsSku.getStock()+num); + goodsSkuService.updateById(goodsSku); + return Result.success(); + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/impl/GoodsRuleValueServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/GoodsRuleValueServiceImpl.java new file mode 100644 index 0000000..5fe7010 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/GoodsRuleValueServiceImpl.java @@ -0,0 +1,26 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.taking.dao.GoodsRuleValueMapper; +import com.sqx.modules.taking.entity.GoodsRuleValue; +import com.sqx.modules.taking.service.GoodsRuleValueService; +import org.springframework.stereotype.Service; + +import java.util.List; + + +@Service +public class GoodsRuleValueServiceImpl extends ServiceImpl implements GoodsRuleValueService { + + @Override + public List selectGoodsRuleValue( Long ruleId){ + return baseMapper.selectList(new QueryWrapper().eq("rule_id",ruleId)); + } + + @Override + public int deleteGoodsRuleValue( Long ruleId){ + return baseMapper.delete(new QueryWrapper().eq("rule_id",ruleId)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/taking/service/impl/GoodsSkuServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/GoodsSkuServiceImpl.java new file mode 100644 index 0000000..924c80a --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/GoodsSkuServiceImpl.java @@ -0,0 +1,37 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.Result; +import com.sqx.modules.taking.dao.GoodsSkuDao; +import com.sqx.modules.taking.entity.GoodsSku; +import com.sqx.modules.taking.service.GoodsSkuService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class GoodsSkuServiceImpl extends ServiceImpl implements GoodsSkuService { + + @Autowired + private GoodsSkuDao goodsSkuDao; + + @Override + public Result insertSku(GoodsSku goodsSku) { + baseMapper.insert(goodsSku); + return Result.success(); + } + + @Override + public List selectGoodsSkuByGoodsId(Long goodsId){ + return baseMapper.selectList(new QueryWrapper().eq("goods_id",goodsId)); + } + + @Override + public int deleteGoodsSkuByGoodsId(Long goodsId){ + return baseMapper.delete(new QueryWrapper().eq("goods_id",goodsId)); + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingCommentServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingCommentServiceImpl.java new file mode 100644 index 0000000..ed6ee8d --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingCommentServiceImpl.java @@ -0,0 +1,112 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.taking.dao.OrderTakingCommentDao; +import com.sqx.modules.taking.dao.OrderTakingDao; +import com.sqx.modules.taking.entity.CommentFabulous; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.entity.TakingCommnt; +import com.sqx.modules.taking.response.TakingDetailsResponse; +import com.sqx.modules.taking.service.OrderTakingCommentService; +import com.sqx.modules.utils.SenInfoCheckUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; + +@Service +public class OrderTakingCommentServiceImpl extends ServiceImpl implements OrderTakingCommentService { + + @Autowired + private OrderTakingCommentDao orderTakingCommentDao; + @Autowired + private OrderTakingDao orderTakingDao; + @Autowired + private OrdersDao ordersDao; + + @Override + public Result selectOrderTakingComment(Integer page, Integer limit, Long id) { + IPage page1 = new Page<>(page, limit); + IPage iPage = orderTakingCommentDao.selectOrderTakingComment(page1, id); + /* List lists = iPage.getRecords(); + for (TakingCommentResponse takingCommentResponse : lists) { + if (takingCommentResponse != null) { + takingCommentResponse.setCount(orderTakingCommentDao.selectCommentNumber(takingCommentResponse.getId())); + } + }*/ + return Result.success().put("data", new PageUtils(iPage)); + } + + + @Override + public Result selectCommentByOrderTakingUserId(Integer page, Integer limit, Long userId) { + IPage page1 = new Page<>(page, limit); + IPage iPage = orderTakingCommentDao.selectCommentByOrderTakingUserId(page1, userId); + return Result.success().put("data", new PageUtils(iPage)); + } + + + @Override + public Result updateGoodsNum(Long commentId, Long userId) { + //判断自己是否点过赞 + CommentFabulous commentFabulous = orderTakingCommentDao.selectGoodsNum(commentId, userId); + if (commentFabulous != null) { + //有赞则取消点赞 + int i = orderTakingCommentDao.deleteGoodsNum(commentFabulous.getId()); + if (i > 0) { + return Result.success("取消点赞成功!"); + } else { + return Result.error("取消点赞失败!"); + } + } else { + //无赞 点赞 + int i = orderTakingCommentDao.insertGoodsNum(commentId, userId); + if (i > 0) { + return Result.success("点赞成功!"); + } else { + return Result.error("点赞失败!"); + } + } + } + + @Override + public Result addGoodsNum(Long id, Long userId, String content, Integer score,Long ordersId) { + int i = selectTakingCommentCount(id, userId); + if(i>0){ + return Result.error("您已经评价过了!"); + } + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //创建 + TakingCommnt takingCommnt = new TakingCommnt(); + takingCommnt.setContent(content); + takingCommnt.setOrderTakingId(id); + takingCommnt.setUserId(userId); + takingCommnt.setCreateTime(simpleDateFormat.format(new Date())); + takingCommnt.setScore(score); + takingCommnt.setOrdersId(ordersId); + baseMapper.insert(takingCommnt); + OrderTaking orderTaking = new OrderTaking(); + orderTaking.setId(id); + orderTaking.setOrderScore(baseMapper.selectAvgScore(id)); + orderTakingDao.updateById(orderTaking); + return Result.success(); + } + + @Override + public int selectTakingCommentCount(Long ordersId,Long userId){ + return baseMapper.selectCount(new QueryWrapper().eq("orders_id",ordersId).eq("user_id",userId)); + } + + @Override + public Result queryMyComment(Long userId) { + + return null; + } +} diff --git a/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingRewardServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingRewardServiceImpl.java new file mode 100644 index 0000000..f9e9915 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingRewardServiceImpl.java @@ -0,0 +1,104 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.taking.dao.OrderTakingRewardDao; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.entity.OrderTakingReward; +import com.sqx.modules.taking.service.OrderTakingRewardService; +import com.sqx.modules.taking.service.OrderTakingService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; + +@Service +public class OrderTakingRewardServiceImpl extends ServiceImpl implements OrderTakingRewardService { + + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private OrderTakingService orderTakingService; + @Autowired + private UserService userService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private CommonInfoService commonInfoService; + + + @Override + public Result rewardMoney(Long userId, BigDecimal money, Long orderTakingId){ + String min = commonInfoService.findOne(203).getValue(); + if(Double.parseDouble(min)>money.doubleValue()){ + return Result.error("打赏金额太少!"); + } + String max = commonInfoService.findOne(204).getValue(); + if(money.doubleValue()>Double.parseDouble(max)){ + return Result.error("打赏金额太多!"); + } + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + if(money.doubleValue()>userMoney.getMoney().doubleValue()){ + return Result.error("金币不足!"); + } + + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String format = simpleDateFormat.format(new Date()); + + OrderTaking orderTaking = orderTakingService.getById(orderTakingId); + + OrderTakingReward orderTakingReward=new OrderTakingReward(); + orderTakingReward.setCreateTime(format); + orderTakingReward.setMoney(money); + orderTakingReward.setOrderTakingId(orderTakingId); + orderTakingReward.setUserId(userId); + baseMapper.insert(orderTakingReward); + + UserEntity userEntity = userService.selectUserById(orderTaking.getUserId()); + UserEntity sendUserEntity = userService.selectUserById(userId); + userMoneyService.updateMoney(2,userId,money); + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setMoney(money); + userMoneyDetails.setUserId(userId); + userMoneyDetails.setContent("打赏用户:"+userEntity.getUserName()); + userMoneyDetails.setTitle("打赏"); + userMoneyDetails.setType(2); + + userMoneyDetails.setCreateTime(format); + userMoneyDetailsService.save(userMoneyDetails); + + String value = commonInfoService.findOne(202).getValue(); + BigDecimal multiply = money.multiply(new BigDecimal(value)); + BigDecimal subtract = money.subtract(multiply); + userMoneyService.updateMoney(1,userEntity.getUserId(),subtract); + userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setMoney(subtract); + userMoneyDetails.setUserId(userEntity.getUserId()); + userMoneyDetails.setContent("接受用户 "+sendUserEntity.getUserName()+" 到打赏,赏金:"+subtract); + userMoneyDetails.setTitle("赏金"); + userMoneyDetails.setType(1); + userMoneyDetails.setCreateTime(format); + userMoneyDetailsService.save(userMoneyDetails); + return Result.success(); + } + + @Override + public Result selectOrderTakingRewardList(Integer page,Integer limit,Long userId,Long orderTakingId){ + Page> pages=new Page<>(page,limit); + return Result.success().put("data",new PageUtils(baseMapper.selectOrderTakingRewardList(pages,userId,orderTakingId))); + } + + +} diff --git a/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingServiceImpl.java b/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingServiceImpl.java new file mode 100644 index 0000000..a65fc5f --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/service/impl/OrderTakingServiceImpl.java @@ -0,0 +1,431 @@ +package com.sqx.modules.taking.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.dao.UserBrowseDao; +import com.sqx.modules.app.dao.UserCertificationDao; +import com.sqx.modules.app.dao.UserDao; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserBrowseService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.dao.OrdersDao; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.search.service.AppSearchService; +import com.sqx.modules.taking.dao.GameDao; +import com.sqx.modules.taking.dao.OrderTakingCommentDao; +import com.sqx.modules.taking.dao.OrderTakingDao; +import com.sqx.modules.taking.entity.GoodsAttr; +import com.sqx.modules.taking.entity.GoodsSku; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.entity.OrderTakingReward; +import com.sqx.modules.taking.service.GoodsAttrService; +import com.sqx.modules.taking.service.GoodsSkuService; +import com.sqx.modules.taking.service.OrderTakingRewardService; +import com.sqx.modules.taking.service.OrderTakingService; +import com.sqx.modules.task.dao.HelpTakeDao; +import jodd.util.StringUtil; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +public class OrderTakingServiceImpl extends ServiceImpl implements OrderTakingService { + + @Autowired + private UserCertificationDao userCertificationDao; + @Autowired + private OrderTakingDao orderTakingDao; + @Autowired + private OrdersDao ordersDao; + @Autowired + private AppSearchService appSearchService; + @Autowired + private GameDao gameDao; + @Autowired + private UserBrowseService userBrowseService; + @Autowired + private UserDao userDao; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private UserService userService; + @Autowired + private MessageService messageService; + @Autowired + private OrderTakingRewardService orderTakingRewardService; + @Autowired + private GoodsSkuService goodsSkuService; + @Autowired + private GoodsAttrService goodsAttrService; + @Autowired + private HelpTakeDao helpTakeDao; + @Autowired + private UserBrowseDao userBrowseDao; + @Autowired + private OrderTakingCommentDao orderTakingCommentDao; + + @Override + public Result queryTaking(String city,String longitude, String latitude, Long userId, String like, String condition, + Long bannerid, Long isRecommend, Long id, Page iPage, Long sex, String by, + Integer classify,Integer isIntegral,Long laundryId) { + Integer con=null; + if(StringUtils.isNotEmpty(condition)){ + con=Integer.parseInt(condition); + } + IPage i = orderTakingDao.queryTaking(iPage,city, longitude, latitude, like, con, bannerid, isRecommend, id, sex, by,classify,isIntegral,laundryId); + return Result.success().put("data", new PageUtils(i)); + } + + @Override + public Result queryLowTaking(Integer page,Integer limit,String longitude,String latitude,Long laundryId) { + if (page == null || limit==null) { + return Result.success().put("data", orderTakingDao.queryLowTaking(longitude,latitude,laundryId)); + } else { + return Result.success().put("data", new PageUtils(orderTakingDao.queryLowTakings(new Page<>(page,limit),longitude,latitude,laundryId))); + } + } + + + @Override + public Result queryTakingDetails(Long id, Long userId,String longitude,String latitude) { + OrderTaking orderTaking = baseMapper.queryTakingDetails(id,longitude,latitude); + if (orderTaking!=null){ + if(userId!=null){ + //添加浏览足迹 + userBrowseService.addAmount(userId,orderTaking.getUserId(), id); + } + + orderTaking.setGoodsSkuList(goodsSkuService.selectGoodsSkuByGoodsId(orderTaking.getId())); + orderTaking.setGoodsAttrList(goodsAttrService.findByGoodsId(orderTaking.getId())); + } + + return Result.success().put("data",orderTaking); + } + + @Override + public Result insertOrderTaking(OrderTaking orderTaking) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //创建时间 + orderTaking.setCreateTime(simpleDateFormat.format(new Date())); + //修改时间 + orderTaking.setUpdateTime(simpleDateFormat.format(new Date())); + orderTaking.setIsdelete((long) 0); + orderTaking.setIsRecommend("1"); + int i = baseMapper.insert(orderTaking); + if(orderTaking.getGoodsAttrList().size()>0){ + List attr = orderTaking.getGoodsAttrList(); + for (GoodsAttr a : attr) { + a.setGoodsId(orderTaking.getId()); + goodsAttrService.saveGoodsAttr(a); + } + } + List sku = orderTaking.getGoodsSkuList(); + if(sku.size()==0){ + GoodsSku goodsSku=new GoodsSku(); + goodsSku.setSkuPrice(orderTaking.getMoney()); + sku.add(goodsSku); + } + for (GoodsSku v : sku) { + v.setGoodsId(orderTaking.getId()); + goodsSkuService.save(v); + } + + + if (i > 0) { + return Result.success("发布成功!"); + } else { + return Result.error("发布失败!"); + } + } + + @Override + public Result selectMyRelease(Long userId, Long page, Long limit, String status) { + Page iPage = new Page<>(page, limit); + PageUtils pageUtils = new PageUtils(baseMapper.selectMyRelease(iPage, userId, status)); + return Result.success().put("data", pageUtils); + + } + + + @Override + public Result deleteOrderTaking(Long id) { + if (id == null) { + return Result.error("删除id为空"); + } else { + int i = baseMapper.deleteById(id); + if (i > 0) { + return Result.success(); + } else { + return Result.error(); + } + } + } + + @Override + public Result queryAllOrderTaking(Integer page, Integer limit, Long gameId, Long status, String userName, Long userId, Integer classify, String longitude, String latitude, Integer isIntegral, String serviceName, Long laundryId, Integer serviceType) { + IPage iPage1 = baseMapper.queryAllOrderTaking(new Page(page,limit), gameId, status, userName,userId,classify,longitude,latitude,isIntegral,serviceName,laundryId,serviceType); + return Result.success().put("data", new PageUtils(iPage1)); + } + + @Override + public Result auditorOrderTaking(Long id, Integer status,String content) { + OrderTaking orderTaking = baseMapper.selectById(id); + if (orderTaking == null) { + return Result.error("接单信息不存在!"); + }else if(orderTaking.getStatus()!=1){ + return Result.error("已经审核过了!"); + }else { + orderTaking.setStatus(status); + orderTaking.setContent(content); + baseMapper.updateById(orderTaking); + + UserEntity userEntity = userService.selectUserById(orderTaking.getUserId()); + MessageInfo messageInfo=new MessageInfo(); + if(status==0){ + messageInfo.setContent("您发布的订单审核通过了"); + }else{ + messageInfo.setContent("您发布的订单审核被拒绝了,原因:"+content); + } + + messageInfo.setTitle("发布信息审核通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + messageInfo.setCreateAt(simpleDateFormat.format(new Date())); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if(StringUtil.isNotBlank(userEntity.getClientid())){ + userService.pushToSingle(messageInfo.getTitle(),messageInfo.getContent(),userEntity.getClientid()); + } + + return Result.success(); + } + } + + @Override + public Result updateTakingStatus(Long id, Integer status,String content) { + OrderTaking orderTaking = new OrderTaking(); + orderTaking.setId(id); + orderTaking.setStatus(status); + orderTaking.setContent(content); + baseMapper.updateById(orderTaking); + return Result.success(); + } + + @Override + public Result deleteTaking(Long id) { + OrderTaking orderTaking = baseMapper.selectById(id); + if (orderTaking != null) { + orderTaking.setIsdelete((long) 1); + baseMapper.update(orderTaking, new QueryWrapper().eq("id", id)); + return Result.success(); + } else { + return Result.error("订单不存在!"); + } + } + + @Override + public Result queryTakingOrder(Long id,Long userId) { + OrderTaking orderTaking = baseMapper.selectById(id); + if (orderTaking != null) { + orderTaking.setGame(gameDao.selectById(orderTaking.getGameId())); + int rewardCount = orderTakingRewardService.count(new QueryWrapper().eq("order_taking_id", id)); + int myRewardCount=0; + if(userId!=null){ + myRewardCount = orderTakingRewardService.count(new QueryWrapper().eq("order_taking_id", id).eq("user_id", userId)); + } + orderTaking.setGoodsSkuList(goodsSkuService.selectGoodsSkuByGoodsId(orderTaking.getId())); + orderTaking.setGoodsAttrList(goodsAttrService.findByGoodsId(orderTaking.getId())); + } + return Result.success().put("data", orderTaking); + } + + @Override + public Result updateTakingOrder(OrderTaking orderTaking) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + BigDecimal money = orderTaking.getMoney(); + //价格 + orderTaking.setOldMoney(money); + //创建时间 + orderTaking.setUpdateTime(simpleDateFormat.format(new Date())); + baseMapper.updateById(orderTaking); + if (orderTaking.getGoodsAttrList() != null && orderTaking.getGoodsAttrList().size() > 0) { + goodsAttrService.deleteAttrAndValue(orderTaking.getId()); + goodsAttrService.updateGoodsAttr(orderTaking.getGoodsAttrList(),orderTaking.getId()); + } else { //修改为单规格,删除所有attr + goodsAttrService.deleteAttrAndValue(orderTaking.getId()); + } + //2.修改所有sku + goodsSkuService.deleteGoodsSkuByGoodsId(orderTaking.getId()); + List sku = orderTaking.getGoodsSkuList(); + if(sku==null){ + sku=new ArrayList<>(); + } + if(sku.size()==0){ + GoodsSku goodsSku=new GoodsSku(); + goodsSku.setSkuPrice(orderTaking.getMoney()); + sku.add(goodsSku); + } + for (GoodsSku goodsSku : sku) { + goodsSku.setGoodsId(orderTaking.getId()); + goodsSkuService.save(goodsSku); + } + return Result.success(); + } + + @Override + public Result updateTakingOrders(OrderTaking orderTaking) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //创建时间 + orderTaking.setUpdateTime(simpleDateFormat.format(new Date())); + baseMapper.updateById(orderTaking); + if (orderTaking.getGoodsAttrList() != null && orderTaking.getGoodsAttrList().size() > 0) { + goodsAttrService.deleteAttrAndValue(orderTaking.getId()); + goodsAttrService.updateGoodsAttr(orderTaking.getGoodsAttrList(),orderTaking.getId()); + } else { //修改为单规格,删除所有attr + goodsAttrService.deleteAttrAndValue(orderTaking.getId()); + } + //2.修改所有sku + goodsSkuService.deleteGoodsSkuByGoodsId(orderTaking.getId()); + List sku = orderTaking.getGoodsSkuList(); + if(sku==null){ + sku=new ArrayList<>(); + } + if(sku.size()==0){ + GoodsSku goodsSku=new GoodsSku(); + goodsSku.setSkuPrice(orderTaking.getMoney()); + sku.add(goodsSku); + } + for (GoodsSku goodsSku : sku) { + goodsSku.setGoodsId(orderTaking.getId()); + goodsSkuService.save(goodsSku); + } + return Result.success(); + } + + + @Override + public Result queryMyTakingOrder(Long userId, Long page, Long limit, Long status) { + Page ipage = new Page<>(page, limit); + IPage iPage = baseMapper.selectPage(ipage, new QueryWrapper().eq("status", 0).or().eq("status", 2)); + List orderTakings = iPage.getRecords(); + for (OrderTaking orderTaking : orderTakings) { + if (orderTaking != null) { + QueryWrapper queryWrapper = new QueryWrapper().eq("order_taking_id", orderTaking.getId()); + if (status != null && status != 0) { + queryWrapper.eq("state", status); + } + List orders = ordersDao.selectList(queryWrapper); + for (Orders order : orders) { + UserEntity user = userDao.selectOne(new QueryWrapper().eq("user_id", order.getUserId())); + order.setUser(user); + } + orderTaking.setOrders(orders); + } + } + return Result.success().put("data", iPage); + } + + + @Override + public Result selectShopData(Long userId,String startTime,String endTime){ + //总收益(服务收入+万能任务收入) + BigDecimal sumOrdersMoney = ordersDao.selectOrdersMoneyByUserId(userId, startTime, endTime); + //总销量 + int sumOrdersCount = ordersDao.selectOrdersCountByUserId(userId,startTime, endTime); + sumOrdersCount += helpTakeDao.selectHelpTakeCount(userId, startTime, endTime); + //师傅订单送水数量 + int rideSumBucketCount = ordersDao.sumOrderBucketCount(userId,startTime,endTime); + //用户评价 + BigDecimal sumOrdersScore = ordersDao.selectOrderScoreByUserId(userId); + //订单收入 + BigDecimal ordersMoney = ordersDao.selectOrdersMoneyByUserId(userId, startTime, endTime); + //总订单数 + int ordersCount = ordersDao.selectOrdersCountByUserId(userId,startTime,endTime); + ordersCount += helpTakeDao.selectHelpTakeCount(userId, startTime, endTime); + //退款金额 + BigDecimal refundMoney = ordersDao.selectOrdersRefundMoneyByUserId(userId, startTime, endTime); + BigDecimal refundMoneys = helpTakeDao.selectHelpTakeRefundMoneyByUserId(userId, startTime, endTime); + refundMoney=refundMoney.add(refundMoneys); + //访客人数 + Integer userBrowseCount = userBrowseDao.selectUserBrowseCountByUserId(userId, startTime, endTime); + //已取消 + Integer ordersRefundCount = ordersDao.selectOrdersRefundCountByUserId(userId, startTime, endTime,3); + ordersRefundCount += helpTakeDao.selectHelpTakeRefundCountByUserId(userId, startTime, endTime,3); + //待完成 + Integer ordersUnderwayCount = ordersDao.selectOrdersRefundCountByUserId(userId, startTime, endTime,5); + ordersUnderwayCount += ordersDao.selectOrdersRefundCountByUserId(userId, startTime, endTime,1); + ordersUnderwayCount += helpTakeDao.selectHelpTakeRefundCountByUserId(userId, startTime, endTime,1); + //已完成 + Integer ordersAccomplishCount = ordersDao.selectOrdersRefundCountByUserId(userId, startTime, endTime,2); + ordersAccomplishCount += helpTakeDao.selectHelpTakeRefundCountByUserId(userId, startTime, endTime,2); + //已评价 + Integer commentCount = orderTakingCommentDao.selectCommntCountByUserId(userId, startTime, endTime); + //上架中 + Integer shangCount = orderTakingDao.selectOrderTakingCountByUserId(userId,0); + //已下架 + Integer xiaCount = orderTakingDao.selectOrderTakingCountByUserId(userId,2); + Map result=new HashMap<>(); + result.put("sumOrdersMoney",sumOrdersMoney); + result.put("sumOrdersCount",sumOrdersCount); + result.put("sumOrdersScore",sumOrdersScore.setScale(2,BigDecimal.ROUND_HALF_DOWN)); + result.put("ordersMoney",ordersMoney); + result.put("ordersCount",ordersCount); + result.put("refundMoney",refundMoney); + result.put("userBrowseCount",userBrowseCount); + result.put("rideSumBucketCount",rideSumBucketCount); + result.put("ordersRefundCount",ordersRefundCount); + result.put("ordersUnderwayCount",ordersUnderwayCount); + result.put("ordersAccomplishCount",ordersAccomplishCount); + result.put("commentCount",commentCount); + result.put("shangCount",shangCount); + result.put("xiaCount",xiaCount); + return Result.success().put("data",result); + } + @Override + public IPage getOrderTakingList(Integer page, Integer limit, Long laundryId) { + + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + + IPage orderTakingIPage = baseMapper.selectPage(pages, new QueryWrapper().eq("status", 0).like("laundry_ids", laundryId).orderByDesc("is_recommend")); + for (OrderTaking record : orderTakingIPage.getRecords()) { + record.setGoodsAttrList(goodsAttrService.findByGoodsId(record.getId())); + record.setGoodsSkuList(goodsSkuService.selectGoodsSkuByGoodsId(record.getId())); + } + + return orderTakingIPage; + + } + + @Override + public Result selectOrderTakingStockList(Integer page,Integer limit,Long laundryId,String serviceName,String detailJson){ + String stock=commonInfoService.findOne(322).getValue(); + return Result.success().put("data",baseMapper.selectOrderTakingStockList(new Page<>(page,limit),laundryId,serviceName,detailJson,stock)); + } + + + +} diff --git a/src/main/java/com/sqx/modules/taking/utils/SkuUtil.java b/src/main/java/com/sqx/modules/taking/utils/SkuUtil.java new file mode 100644 index 0000000..4ce3224 --- /dev/null +++ b/src/main/java/com/sqx/modules/taking/utils/SkuUtil.java @@ -0,0 +1,48 @@ +package com.sqx.modules.taking.utils; + +import java.util.ArrayList; +import java.util.List; + +public class SkuUtil { + + /** + * @param inputList 所有数组的列表 + * */ + public static List> skuSort(List> inputList) { + List> result = new ArrayList<>(); + List combination = new ArrayList(); + int n=inputList.size(); + for (int i = 0; i < n; i++) { + combination.add(0); + } + int i=0; + boolean isContinue=false; + do{ + List temp = new ArrayList<>(); + //打印一次循环生成的组合 + for (int j = 0; j < n; j++) { + temp.add(inputList.get(j).get(combination.get(j))); + } + result.add(temp); + i++; + combination.set(n-1, i); + for (int j = n-1; j >= 0; j--) { + if (combination.get(j)>=inputList.get(j).size()) { + combination.set(j, 0); + i=0; + if (j-1>=0) { + combination.set(j-1, combination.get(j-1)+1); + } + } + } + isContinue=false; + for (Integer integer : combination) { + if (integer != 0) { + isContinue=true; + } + } + }while (isContinue); + return result; + } + +} diff --git a/src/main/java/com/sqx/modules/task/controller/HelpController.java b/src/main/java/com/sqx/modules/task/controller/HelpController.java new file mode 100644 index 0000000..fe10cf8 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/controller/HelpController.java @@ -0,0 +1,159 @@ +package com.sqx.modules.task.controller; + +import com.sqx.common.utils.Result; +import com.sqx.modules.task.entity.HelpOrder; +import com.sqx.modules.task.entity.HelpTake; +import com.sqx.modules.task.service.HelpOrderService; +import com.sqx.modules.task.service.HelpTakeService; +import com.sqx.modules.utils.excel.ExcelData; +import com.sqx.modules.utils.excel.ExportExcelUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; + +/** + * @author fang + * @date 2021/1/8 + */ +@RestController +@Api(value = "跑腿订单", tags = {"跑腿订单"}) +@RequestMapping(value = "/help") +public class HelpController { + + + @Autowired + private HelpOrderService helpOrderService; + @Autowired + private HelpTakeService helpTakeService; + + + @PostMapping("/saveHelpOrder") + @ApiOperation("发布跑腿订单") + @ResponseBody + public Result saveHelpOrder(@RequestBody HelpOrder helpOrder){ + return helpOrderService.saveBodys(helpOrder); + } + + + @PostMapping("/updateHelpOrderByStatus/{ids}/{status}/{content}") + @ApiOperation("审核跑腿订单") + @ResponseBody + public Result updateHelpOrderByStatus(@PathVariable("ids") String ids,@PathVariable("status") Integer status,@PathVariable("content") String content){ + return helpOrderService.updateHelpOrderByStatus(ids, status, content); + } + + @PostMapping("/updateHelpOrder") + @ApiOperation("完善需求") + @ResponseBody + public Result updateHelpOrder(@RequestBody HelpOrder helpOrder){ + return helpOrderService.updateHelpOrderByIds(helpOrder); + } + + @PostMapping("/deleteHelpOrder") + @ApiOperation("删除") + @ResponseBody + public Result deleteHelpOrder(Long helpOrderId){ + return helpOrderService.deleteById(helpOrderId); + } + + @PostMapping("/outHelpOrder") + @ApiOperation("下架任务") + @ResponseBody + public Result outHelpOrder(Long helpOrderId){ + return helpOrderService.outHelpOrder(helpOrderId); + } + + + @PostMapping("/closeOrder") + @ApiOperation("确认送达") + @ResponseBody + public Result closeOrder(Long helpOrderId){ + return helpTakeService.closeOrders(helpOrderId); + } + + @PostMapping("/saveHelpTake") + @ApiOperation("接单") + @ResponseBody + public Result saveHelpTake(@RequestBody HelpTake helpTake){ + return helpTakeService.saveBody(helpTake); + } + + @PostMapping("/endHelpTake") + @ApiOperation("放弃接单") + @ResponseBody + public Result endHelpTake(Long id){ + return helpTakeService.endHelpTake(id); + } + + + @GetMapping("/selectNewHelpOrderList") + @ApiOperation("最新跑腿") + @ResponseBody + public Result selectNewHelpOrderList(Integer page,Integer limit,Long gameId,String latitude,String longitude,Integer sort){ + return helpOrderService.selectNewHelpOrderList(page,limit,gameId,latitude,longitude,sort); + } + + + @GetMapping("/selectHelpOrderByClassifyList") + @ApiOperation("根据分类查找跑腿") + @ResponseBody + public Result selectHelpOrderByClassifyList(Integer page,Integer limit,Long classifyId,Long gameId){ + return helpOrderService.selectHelpOrderByClassifyList(page,limit,classifyId,gameId); + } + + + @GetMapping("/selectHelpOrderByNameList") + @ApiOperation("根据名称模糊查找跑腿") + @ResponseBody + public Result selectHelpOrderByContentList(Integer page,Integer limit,String content,Long gameId){ + return helpOrderService.selectHelpOrderByContentList(page,limit,content,gameId); + } + + @GetMapping("/selectHelpOrderDetails") + @ApiOperation("查看跑腿详细信息") + @ResponseBody + public Result selectHelpOrderDetails(Long helpOrderId){ + HelpOrder helpOrder = helpOrderService.selectHelpOrderById(helpOrderId); + return Result.success().put("data",helpOrder); + } + + @GetMapping("/selectRunHelpOrder") + @ApiOperation("我的订单-跑腿订单") + @ResponseBody + public Result selectRunHelpOrder(Integer page,Integer limit,Integer status,Long userId){ + return helpTakeService.selectRunHelpOrder(page,limit,status,userId); + } + + @GetMapping("/selectCreateHelpOrder") + @ApiOperation("我的订单-发布订单") + @ResponseBody + public Result selectCreateHelpOrder(Integer page,Integer limit,Integer status,Long userId,Long gameId){ + return helpOrderService.selectCreateHelpOrder(page,limit,status,userId,gameId); + + } + + @GetMapping("/selectStatusHelpOrder") + @ApiOperation("查询待审核的订单") + @ResponseBody + public Result selectStatusHelpOrder(Integer page,Integer limit,String phone,String content,Integer status,Long gameId){ + return helpOrderService.selectStatusHelpOrder(page,limit,phone,content,status,gameId); + } + + @GetMapping("/selectHelpTakeList") + @ApiOperation("查询已接单的接单订单") + @ResponseBody + public Result selectHelpTakeList(Integer page,Integer limit,Integer status,String phone,String startTime,String endTime){ + return helpTakeService.selectRunHelpOrder(page,limit,status,phone,startTime,endTime); + } + + @GetMapping("/helpTakeListExcel") + @ApiOperation("订单导出") + public void helpTakeListExcel(Integer status,String phone,String startTime,String endTime, HttpServletResponse response) throws Exception { + ExcelData data = helpTakeService.helpTakeListExcel( status,phone,startTime,endTime); + ExportExcelUtils.exportExcel(response,"接单列表.xlsx",data); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/task/controller/app/AppHelpController.java b/src/main/java/com/sqx/modules/task/controller/app/AppHelpController.java new file mode 100644 index 0000000..dc2cee2 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/controller/app/AppHelpController.java @@ -0,0 +1,164 @@ +package com.sqx.modules.task.controller.app; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.task.entity.HelpOrder; +import com.sqx.modules.task.entity.HelpTake; +import com.sqx.modules.task.service.HelpOrderService; +import com.sqx.modules.task.service.HelpTakeService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * @author fang + * @date 2021/1/8 + */ +@RestController +@Api(value = "跑腿订单", tags = {"跑腿订单"}) +@RequestMapping(value = "/app/help") +public class AppHelpController { + + + @Autowired + private HelpOrderService helpOrderService; + @Autowired + private HelpTakeService helpTakeService; + + + @Login + @PostMapping("/saveHelpOrder") + @ApiOperation("发布跑腿订单") + @ResponseBody + public Result saveHelpOrder(@RequestBody HelpOrder helpOrder,@RequestAttribute Long userId){ + helpOrder.setUserId(userId); + return helpOrderService.saveBody(helpOrder); + } + + @Login + @PostMapping("/updateHelpOrderByStatus/{ids}/{status}/{content}") + @ApiOperation("审核跑腿订单") + @ResponseBody + public Result updateHelpOrderByStatus(@PathVariable("ids") String ids,@PathVariable("status") Integer status,@PathVariable("content") String content){ + return helpOrderService.updateHelpOrderByStatus(ids, status, content); + } + + @Login + @PostMapping("/updateHelpOrder") + @ApiOperation("完善需求") + @ResponseBody + public Result updateHelpOrder(@RequestBody HelpOrder helpOrder){ + return helpOrderService.updateHelpOrderById(helpOrder); + } + + @Login + @PostMapping("/deleteHelpOrder") + @ApiOperation("删除") + @ResponseBody + public Result deleteHelpOrder(Long helpOrderId){ + return helpOrderService.deleteById(helpOrderId); + } + + @Login + @PostMapping("/outHelpOrder") + @ApiOperation("下架任务") + @ResponseBody + public Result outHelpOrder(Long helpOrderId){ + return helpOrderService.outHelpOrder(helpOrderId); + } + + @Login + @PostMapping("/closeOrder") + @ApiOperation("确认送达") + @ResponseBody + public Result closeOrder(Long helpTakeId,Long helpOrderId,String code){ + return helpTakeService.closeOrder(helpTakeId, helpOrderId, code); + } + + @Login + @PostMapping("/saveHelpTake") + @ApiOperation("接单") + @ResponseBody + public Result saveHelpTake(@RequestBody HelpTake helpTake,@RequestAttribute Long userId){ + helpTake.setUserId(userId); + return helpTakeService.saveBody(helpTake); + } + + @Login + @PostMapping("/endHelpTake") + @ApiOperation("放弃接单") + @ResponseBody + public Result endHelpTake(Long id){ + return helpTakeService.endHelpTake(id); + } + + + @GetMapping("selectNewHelpOrderList") + @ApiOperation("最新跑腿") + @ResponseBody + public Result selectNewHelpOrderList(Integer page,Integer limit,Long gameId,String latitude,String longitude,Integer sort){ + return helpOrderService.selectNewHelpOrderList(page,limit,gameId,latitude,longitude,sort); + } + + + @GetMapping("/selectHelpOrderByClassifyList") + @ApiOperation("根据分类查找跑腿") + @ResponseBody + public Result selectHelpOrderByClassifyList(Integer page,Integer limit,Long classifyId,Long gameId){ + return helpOrderService.selectHelpOrderByClassifyList(page,limit,classifyId,gameId); + } + + + @GetMapping("/selectHelpOrderByNameList") + @ApiOperation("根据名称模糊查找跑腿") + @ResponseBody + public Result selectHelpOrderByContentList(Integer page,Integer limit,String content,Long gameId){ + return helpOrderService.selectHelpOrderByContentList(page,limit,content,gameId); + } + + @GetMapping("/selectHelpOrderDetails") + @ApiOperation("查看跑腿详细信息") + @ResponseBody + public Result selectHelpOrderDetails(Long helpOrderId){ + HelpOrder helpOrder = helpOrderService.selectHelpOrderById(helpOrderId); + return Result.success().put("data",helpOrder); + } + + @Login + @GetMapping("/selectRunHelpOrder") + @ApiOperation("我的订单-跑腿订单") + @ResponseBody + public Result selectRunHelpOrder(Integer page,Integer limit,Integer status,@RequestAttribute Long userId){ + return helpTakeService.selectRunHelpOrder(page,limit,status,userId); + } + + @Login + @GetMapping("/selectCreateHelpOrder") + @ApiOperation("我的订单-发布订单") + @ResponseBody + public Result selectCreateHelpOrder(Integer page,Integer limit,Integer status,@RequestAttribute Long userId,Long gameId){ + return helpOrderService.selectCreateHelpOrder(page,limit,status,userId,gameId); + + } + + @Login + @GetMapping("/selectStatusHelpOrder") + @ApiOperation("查询待审核的订单") + @ResponseBody + public Result selectStatusHelpOrder(Integer page,Integer limit,String phone,String content,Integer status,Long gameId){ + return helpOrderService.selectStatusHelpOrder(page,limit,phone,content,status,gameId); + + } + + @Login + @GetMapping("/selectHelpTakeList") + @ApiOperation("查询已接单的接单订单") + @ResponseBody + public Result selectHelpTakeList(Integer page,Integer limit,Integer status,String phone){ + return helpTakeService.selectRunHelpOrder(page,limit,status,phone,null,null); + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/task/dao/HelpOrderDao.java b/src/main/java/com/sqx/modules/task/dao/HelpOrderDao.java new file mode 100644 index 0000000..afb7cb1 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/dao/HelpOrderDao.java @@ -0,0 +1,32 @@ +package com.sqx.modules.task.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.task.entity.HelpOrder; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + * @author fang + * @date 2021/1/6 + */ +@Mapper +public interface HelpOrderDao extends BaseMapper { + + IPage selectNewHelpOrderList(Page page,Long gameId,String latitude,String longitude,Integer sort); + + IPage selectHelpOrderByClassifyList(Page page,@Param("classifyId") Long classifyId,Long gameId); + + IPage selectHelpOrderByContentList(Page page,@Param("content") String content,Long gameId); + + IPage selectStatusHelpOrder(Page page,@Param("phone") String phone,@Param("content") String content,@Param("status") Integer status,Long gameId); + + Integer countHelpOrderByCreateTime(@Param("time") String time,@Param("flag") Integer flag); + + Double sumPrice(@Param("time") String time,@Param("flag") Integer flag); + + + + +} diff --git a/src/main/java/com/sqx/modules/task/dao/HelpTakeDao.java b/src/main/java/com/sqx/modules/task/dao/HelpTakeDao.java new file mode 100644 index 0000000..97bc243 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/dao/HelpTakeDao.java @@ -0,0 +1,39 @@ +package com.sqx.modules.task.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.task.entity.HelpTake; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +/** + * @author fang + * @date 2021/1/7 + */ +@Mapper +public interface HelpTakeDao extends BaseMapper { + + int insertHelpTake(HelpTake helpTake); + + IPage> selectRunHelpOrder(Page> page,@Param("status") Integer status,@Param("userId") Long userId); + + IPage> selectRunHelpOrderList(Page> page, @Param("status") Integer status,@Param("phone") String phone,String startTime,String endTime); + + List> helpTakeListExcel( @Param("status") Integer status, @Param("phone") String phone,String startTime,String endTime); + + Integer countHelpTakeByCreateTime(@Param("time")String time,@Param("flag")Integer flag); + + Double sumMoneyBySend(@Param("time")String time,@Param("flag")Integer flag); + + Integer selectHelpTakeCount(Long userId,String startTime,String endTime); + + BigDecimal selectHelpTakeRefundMoneyByUserId(Long userId,String startTime,String endTime); + + Integer selectHelpTakeRefundCountByUserId(Long userId,String startTime,String endTime,Integer status); + +} diff --git a/src/main/java/com/sqx/modules/task/entity/HelpOrder.java b/src/main/java/com/sqx/modules/task/entity/HelpOrder.java new file mode 100644 index 0000000..c299a21 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/entity/HelpOrder.java @@ -0,0 +1,141 @@ +package com.sqx.modules.task.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.sqx.modules.app.entity.UserEntity; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * help_order + * @author fang 2021-01-06 + */ +@Data +@TableName("help_order") +public class HelpOrder implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 跑腿订单id + */ + @TableId + private Long id; + + /** + * 接单id + */ + private Long helpTakeId; + + + /** + * 订单编号 + */ + private String orderNo; + + /** + * 内容 + */ + private String content; + + @ApiModelProperty("省") + private String province; + @ApiModelProperty("市") + private String city; + @ApiModelProperty("区") + private String district; + @ApiModelProperty("详细地址") + private String detailsAddress; + @ApiModelProperty("纬度") + private String longitude; + @ApiModelProperty("经度") + private String latitude; + @ApiModelProperty("姓名") + private String name; + @ApiModelProperty("电话") + private String phone; + + /** + * 期望送达时间 + */ + private String deliveryTime; + + /** + * 服务类型 + */ + private Long gameId; + + /** + * 发单人id + */ + private Long userId; + + /** + * 佣金 + */ + private BigDecimal commission; + + /** + * 实际发布金额 + */ + private BigDecimal money; + + /** + * 图片 + */ + private String image; + + /** + * 收货码 + */ + private String code; + + /** + * 状态(1待审核 2待接单 3待送达 4已完成 5取消) + */ + private Integer status; + + + /** + * 支付方式 1微信 2支付宝 + */ + private Integer payType; + + /** + * 创建时间 + */ + private String createTime; + + private String cause; + + /** + * 支付方式 1零钱 2微信 3支付宝 + */ + private Integer payWay; + + @TableField(exist = false) + private String userName; + + @TableField(exist = false) + private String avatar; + + @TableField(exist = false) + private UserEntity user; + + @TableField(exist = false) + private HelpTake helpTake; + + @TableField(exist = false) + private String serviceName; + + @TableField(exist = false) + private Double distance; + + @TableField(exist = false) + private Integer classify; + +} diff --git a/src/main/java/com/sqx/modules/task/entity/HelpTake.java b/src/main/java/com/sqx/modules/task/entity/HelpTake.java new file mode 100644 index 0000000..676372e --- /dev/null +++ b/src/main/java/com/sqx/modules/task/entity/HelpTake.java @@ -0,0 +1,62 @@ +package com.sqx.modules.task.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.sqx.modules.app.entity.UserEntity; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * help_take + * @author fang 2021-01-07 + */ +@Data +@TableName("help_take") +public class HelpTake implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 接单id + */ + @TableId + private Long id; + + /** + * 订单id + */ + private Long orderId; + + /** + * 用户id + */ + private Long userId; + + /** + * 实际收益 + */ + private BigDecimal money; + + /** + * 状态 1 已接单 2 已送达 3已下架 + */ + private Integer status; + + /** + * 接单时间 + */ + private String createTime; + + /** + * 送达时间 结束时间 + */ + private String endTime; + + @TableField(exist = false) + private UserEntity user; + + +} diff --git a/src/main/java/com/sqx/modules/task/service/HelpOrderService.java b/src/main/java/com/sqx/modules/task/service/HelpOrderService.java new file mode 100644 index 0000000..abcaa67 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/service/HelpOrderService.java @@ -0,0 +1,48 @@ +package com.sqx.modules.task.service; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.task.entity.HelpOrder; + +public interface HelpOrderService { + + Result selectHelpOrder(int page, int limit); + + Result selectNewHelpOrderList(int page,int limit,Long gameId,String latitude,String longitude,Integer sort); + + Result selectHelpOrderByClassifyList(int page,int limit,Long classifyId,Long gameId); + + Result selectHelpOrderByContentList(int page,int limit,String content,Long gameId); + + HelpOrder selectHelpOrderById(Long helpOrderId ); + + Result selectCreateHelpOrder(int page,int limit,Integer status,Long userId,Long gameId); + + Result selectStatusHelpOrder(int page,int limit,String phone,String content,Integer status,Long gameId); + + Result saveBody(HelpOrder helpOrder); + + Result saveBodys(HelpOrder helpOrder); + + Result updateHelpOrderByStatus(String ids,Integer status,String content); + + Result updateHelpOrderById(HelpOrder helpOrder); + + Result updateHelpOrderByIds(HelpOrder helpOrder); + + boolean updateById(HelpOrder helpOrder); + + Result deleteById(Long id); + + Result deleteByIds(Long id); + + Result outHelpOrder(Long id); + + Integer countHelpOrderByCreateTime( String time, Integer flag); + + Double sumPrice( String time, Integer flag); + + + + +} diff --git a/src/main/java/com/sqx/modules/task/service/HelpTakeService.java b/src/main/java/com/sqx/modules/task/service/HelpTakeService.java new file mode 100644 index 0000000..24926c9 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/service/HelpTakeService.java @@ -0,0 +1,40 @@ +package com.sqx.modules.task.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.sqx.common.utils.Result; +import com.sqx.modules.task.entity.HelpTake; +import com.sqx.modules.utils.excel.ExcelData; + +public interface HelpTakeService extends IService { + + Result selectHelpTake(int page, int limit); + + Result selectRunHelpOrder(int page,int limit,Integer status,Long userId); + + Result selectRunHelpOrder(int page,int limit,Integer status,String phone,String startTime,String endTime); + + ExcelData helpTakeListExcel(Integer status, String phone, String startTime, String endTime); + + HelpTake selectHelpTakeById(Long helpTakeId); + + Integer countHelpTakeByCreateTime(String time,Integer flag); + + Double sumMoneyBySend(String time,Integer flag); + + Result saveBody(HelpTake helpTake); + + Result endHelpTake(Long id); + + Result closeOrder(Long helpTakeId,Long helpOrderId,String code); + + Result closeOrders(Long helpOrderId); + + Result updateHelpTakeById(HelpTake helpTake); + + Result deleteById(Long id); + + + + +} diff --git a/src/main/java/com/sqx/modules/task/service/impl/HelpOrderServiceImpl.java b/src/main/java/com/sqx/modules/task/service/impl/HelpOrderServiceImpl.java new file mode 100644 index 0000000..9aab2f1 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/service/impl/HelpOrderServiceImpl.java @@ -0,0 +1,421 @@ +package com.sqx.modules.task.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.pay.controller.app.AliPayController; +import com.sqx.modules.pay.service.WxService; +import com.sqx.modules.taking.entity.Game; +import com.sqx.modules.taking.service.GameService; +import com.sqx.modules.task.dao.HelpOrderDao; +import com.sqx.modules.task.entity.HelpOrder; +import com.sqx.modules.task.entity.HelpTake; +import com.sqx.modules.task.service.HelpOrderService; +import com.sqx.modules.task.service.HelpTakeService; +import com.sqx.modules.utils.AmountCalUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * 跑腿订单 + */ +@Service +public class HelpOrderServiceImpl extends ServiceImpl implements HelpOrderService { + + /** 跑腿订单 */ + @Autowired + private HelpOrderDao helpOrderDao; + /** 用户金额 */ + @Autowired + private UserMoneyService userMoneyService; + /** 用户金额明细 */ + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private UserService userService; + @Autowired + private HelpTakeService helpTakeService; + + @Autowired + private MessageService messageService; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private GameService gameService; + @Autowired + private WxService wxService; + @Autowired + private AliPayController aliPayController; + + + + @Override + public Result selectHelpOrder(int page,int limit){ + return Result.success().put("data",helpOrderDao.selectList(new QueryWrapper<>())); + } + + @Override + public Result selectCreateHelpOrder(int page,int limit,Integer status,Long userId,Long gameId){ + Page pages=new Page<>(page,limit); + IPage helpOrderIPage = helpOrderDao.selectPage(pages, new QueryWrapper().eq(status != 0, "status", status).eq("user_id", userId).eq(gameId!=null,"game_id",gameId).orderByDesc("create_time")); + List records = helpOrderIPage.getRecords(); + for(HelpOrder helpOrder:records){ + if(helpOrder.getGameId()!=null){ + Game byId = gameService.getById(helpOrder.getGameId()); + if(byId!=null){ + helpOrder.setServiceName(byId.getGameName()); + } + } + if(helpOrder.getHelpTakeId()!=null){ + HelpTake helpTake = helpTakeService.selectHelpTakeById(helpOrder.getHelpTakeId()); + helpOrder.setHelpTake(helpTake); + } + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + helpOrder.setUser(userEntity); + } + return Result.success().put("data",new PageUtils(helpOrderIPage)); + } + + @Override + public Result selectStatusHelpOrder(int page,int limit,String phone,String content,Integer status,Long gameId){ + phone = phone.trim(); + Page pages=new Page<>(page,limit); + IPage helpOrderIPage = helpOrderDao.selectStatusHelpOrder(pages,phone,content,status,gameId); + List records = helpOrderIPage.getRecords(); + for(HelpOrder helpOrder:records){ + if(helpOrder.getHelpTakeId()!=null){ + HelpTake helpTake = helpTakeService.selectHelpTakeById(helpOrder.getHelpTakeId()); + helpOrder.setHelpTake(helpTake); + } + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + helpOrder.setUser(userEntity); + } + return Result.success().put("data",new PageUtils(helpOrderIPage)); + } + + + @Override + public Integer countHelpOrderByCreateTime( String time, Integer flag){ + return helpOrderDao.countHelpOrderByCreateTime(time, flag); + } + + + @Override + public Double sumPrice( String time, Integer flag){ + return helpOrderDao.sumPrice(time, flag); + } + + @Override + public Result selectNewHelpOrderList(int page,int limit,Long gameId,String latitude,String longitude,Integer sort){ + Page pages=new Page<>(page,limit); + IPage helpOrderIPage = helpOrderDao.selectNewHelpOrderList(pages,gameId,latitude,longitude,sort); + return Result.success().put("data",new PageUtils(helpOrderIPage)); + } + + @Override + public Result selectHelpOrderByClassifyList(int page,int limit,Long classifyId,Long gameId){ + Page pages=new Page<>(page,limit); + IPage helpOrderIPage = helpOrderDao.selectHelpOrderByClassifyList(pages,classifyId,gameId); + return Result.success().put("data",new PageUtils(helpOrderIPage)); + } + + @Override + public Result updateHelpOrderByStatus(String ids,Integer status,String content){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + for(String id:ids.split(",")){ + HelpOrder helpOrder = helpOrderDao.selectById(Long.parseLong(id)); + if(helpOrder!=null && helpOrder.getStatus()==1){ + UserEntity userEntity=userService.selectUserById(helpOrder.getUserId()); + if(status==1){ + helpOrder.setStatus(2); + helpOrderDao.updateById(helpOrder); + MessageInfo messageInfo=new MessageInfo(); + messageInfo.setContent("您好,您的万能任务申请已经通过了!"); + messageInfo.setTitle("万能任务结果通知!"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(sdf.format(new Date())); + messageService.saveBody(messageInfo); + }else{ + helpOrder.setStatus(5); + helpOrder.setCause(content); + helpOrderDao.updateById(helpOrder); + MessageInfo messageInfo=new MessageInfo(); + messageInfo.setContent("您好,您的万能任务申请被拒绝了!原因:"+content); + messageInfo.setTitle("万能任务结果通知!"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(sdf.format(new Date())); + messageService.saveBody(messageInfo); + userMoneyService.updateMoney(1,helpOrder.getUserId(),helpOrder.getMoney()); + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setUserId(helpOrder.getUserId()); + userMoneyDetails.setTitle("[万能任务退款]:"+helpOrder.getContent()); + userMoneyDetails.setContent("万能任务退款:"+helpOrder.getMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(helpOrder.getMoney()); + userMoneyDetails.setCreateTime(sdf.format(new Date())); + userMoneyDetailsService.save(userMoneyDetails); + } + } + } + return Result.success(); + } + + @Override + public Result selectHelpOrderByContentList(int page,int limit,String content,Long gameId){ + Page pages=new Page<>(page,limit); + IPage helpOrderIPage = helpOrderDao.selectHelpOrderByContentList(pages,content,gameId); + return Result.success().put("data",new PageUtils(helpOrderIPage)); + } + + + @Override + public Result saveBody(HelpOrder helpOrder){ + if(helpOrder.getCommission().doubleValue()<=0){ + return Result.error("金额必须大于0"); + } + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date=sdf.format(new Date()); + helpOrder.setStatus(2); + helpOrder.setCreateTime(date); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(helpOrder.getUserId()); + if(userMoney.getMoney().doubleValue()>=helpOrder.getCommission().doubleValue()){ + helpOrder.setOrderNo(getGeneralOrder()); + helpOrder.setMoney(helpOrder.getCommission()); + CommonInfo one = commonInfoService.findOne(120); + String value = one.getValue(); + Double mul = AmountCalUtils.mul(helpOrder.getCommission().doubleValue(), Double.parseDouble(value)); + BigDecimal sub = AmountCalUtils.sub(helpOrder.getMoney(), BigDecimal.valueOf(mul)); + helpOrder.setCommission(sub); + helpOrder.setPayWay(1); + helpOrderDao.insert(helpOrder); + userMoneyService.updateMoney(2,helpOrder.getUserId(),helpOrder.getMoney()); + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setUserId(helpOrder.getUserId()); + userMoneyDetails.setTitle("万能任务"); + userMoneyDetails.setContent("万能任务扣款:"+helpOrder.getMoney()); + userMoneyDetails.setType(2); + userMoneyDetails.setMoney(helpOrder.getMoney()); + userMoneyDetails.setCreateTime(date); + userMoneyDetailsService.save(userMoneyDetails); + if (userEntity.getClientid() != null) { + userService.pushToSingle("派发订单","您的订单已经派发成功!" , userEntity.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的订单已经派发成功!"); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageService.saveBody(messageInfo); + }else{ + return Result.error("账户金额不足,请充值!"); + } + return Result.success(); + } + + @Override + public Result saveBodys(HelpOrder helpOrder){ + if(helpOrder.getCommission().doubleValue()<=0){ + return Result.error("金额必须大于0"); + } + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date=sdf.format(new Date()); + helpOrder.setStatus(2); + helpOrder.setCreateTime(date); + helpOrder.setMoney(helpOrder.getCommission()); + helpOrderDao.insert(helpOrder); + return Result.success(); + } + + + @Override + public Result updateHelpOrderById(HelpOrder helpOrder){ + HelpOrder helpOrder1 = helpOrderDao.selectById(helpOrder.getId()); + if(!helpOrder1.getCommission().equals(helpOrder.getCommission())){ + return Result.error("已发布任务不能修改金额!"); + } + if(helpOrder1.getStatus()==3 || helpOrder1.getStatus()==4){ + return Result.error("当前状态不允许修改!"); + } + + helpOrderDao.updateById(helpOrder); + return Result.success(); + } + + @Override + public Result updateHelpOrderByIds(HelpOrder helpOrder){ + helpOrderDao.updateById(helpOrder); + return Result.success(); + } + + @Override + public Result deleteById(Long id){ + HelpOrder helpOrder = helpOrderDao.selectById(id); + if(helpOrder.getStatus()!=4 && helpOrder.getStatus()!=5 ){ + return Result.error("当前状态不允许删除!"); + } + helpOrderDao.deleteById(id); + return Result.success(); + } + + @Override + public Result deleteByIds(Long id){ + HelpOrder helpOrder = helpOrderDao.selectById(id); + if(helpOrder.getStatus()==3 || helpOrder.getStatus()==4){ + helpOrderDao.deleteById(id); + }else{ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date=sdf.format(new Date()); + if(helpOrder.getPayWay()==null || helpOrder.getPayWay()==1){ + userMoneyService.updateMoney(1,helpOrder.getUserId(),helpOrder.getMoney()); + }else if(helpOrder.getPayWay()==2){ + //微信 + boolean refund = wxService.refund(helpOrder.getOrderNo()); + if(!refund){ + return Result.error("退款失败,请联系客服处理!"); + } + }else{ + //支付宝 + String data=aliPayController.alipayRefund(helpOrder.getOrderNo()); + if(StringUtils.isNotBlank(data)){ + log.error(data); + JSONObject jsonObject = JSON.parseObject(data); + JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response"); + String code1 = alipay_trade_refund_response.getString("code"); + if(!"10000".equals(code1)){ + return Result.error("退款失败!"+alipay_trade_refund_response.getString("sub_msg")); + } + }else{ + return Result.error("退款失败!"); + } + } + + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setUserId(helpOrder.getUserId()); + userMoneyDetails.setTitle("[万能任务退款]:"+helpOrder.getContent()); + userMoneyDetails.setContent("万能任务已原路退款:"+helpOrder.getMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(helpOrder.getMoney()); + userMoneyDetails.setCreateTime(date); + userMoneyDetailsService.save(userMoneyDetails); + helpOrderDao.deleteById(id); + } + return Result.success(); + } + + @Override + public Result outHelpOrder(Long id){ + HelpOrder helpOrder = helpOrderDao.selectById(id); + if(helpOrder.getStatus()==5){ + return Result.error("当前状态不允许取消!"); + } + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date=sdf.format(new Date()); + if(helpOrder.getHelpTakeId()!=null){ + HelpTake helpTake = helpTakeService.selectHelpTakeById(helpOrder.getHelpTakeId()); + helpTake.setStatus(3); + helpTakeService.updateHelpTakeById(helpTake); + UserEntity userEntity = userService.selectUserById(helpTake.getUserId()); + Game game = gameService.getById(helpOrder.getGameId()); + if (userEntity.getClientid() != null) { + userService.pushToSingle("万能任务","您的万能任务:"+game.getGameName()+",平台已经取消!" , userEntity.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的万能任务:"+game.getGameName()+",平台已经取消!"); + messageInfo.setTitle("万能任务"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageService.saveBody(messageInfo); + } + if(helpOrder.getPayWay()==null || helpOrder.getPayWay()==1){ + userMoneyService.updateMoney(1,helpOrder.getUserId(),helpOrder.getMoney()); + }else if(helpOrder.getPayWay()==2){ + //微信 + boolean refund = wxService.refund(helpOrder.getOrderNo()); + if(!refund){ + return Result.error("退款失败,请联系客服处理!"); + } + }else{ + //支付宝 + String data=aliPayController.alipayRefund(helpOrder.getOrderNo()); + if(StringUtils.isNotBlank(data)){ + log.error(data); + JSONObject jsonObject = JSON.parseObject(data); + JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response"); + String code1 = alipay_trade_refund_response.getString("code"); + if(!"10000".equals(code1)){ + return Result.error("退款失败!"+alipay_trade_refund_response.getString("sub_msg")); + } + }else{ + return Result.error("退款失败!"); + } + } + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setUserId(helpOrder.getUserId()); + userMoneyDetails.setTitle("[万能任务退款]:"+helpOrder.getContent()); + userMoneyDetails.setContent("万能任务已原路退款:"+helpOrder.getMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(helpOrder.getMoney()); + userMoneyDetails.setCreateTime(date); + userMoneyDetailsService.save(userMoneyDetails); + helpOrder.setStatus(5); + helpOrderDao.updateById(helpOrder); + return Result.success(); + } + + @Override + public HelpOrder selectHelpOrderById(Long helpOrderId){ + HelpOrder helpOrder = helpOrderDao.selectById(helpOrderId); + if(helpOrder.getGameId()!=null){ + Game byId = gameService.getById(helpOrder.getGameId()); + if(byId!=null){ + helpOrder.setServiceName(byId.getGameName()); + } + } + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + helpOrder.setUser(userEntity); + HelpTake helpTake = helpTakeService.selectHelpTakeById(helpOrder.getHelpTakeId()); + if(helpTake!=null){ + helpOrder.setHelpTake(helpTake); + } + return helpOrder; + } + + + private String getGeneralOrder(){ + Date date=new Date(); + String newString = String.format("%0"+4+"d", (int)((Math.random()*9+1)*1000)); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + String format = sdf.format(date); + return format+newString; + } + + +} diff --git a/src/main/java/com/sqx/modules/task/service/impl/HelpTakeServiceImpl.java b/src/main/java/com/sqx/modules/task/service/impl/HelpTakeServiceImpl.java new file mode 100644 index 0000000..39d9450 --- /dev/null +++ b/src/main/java/com/sqx/modules/task/service/impl/HelpTakeServiceImpl.java @@ -0,0 +1,339 @@ +package com.sqx.modules.task.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.common.utils.PageUtils; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.response.OrderAllResponse; +import com.sqx.modules.taking.entity.Game; +import com.sqx.modules.taking.service.GameService; +import com.sqx.modules.task.dao.HelpOrderDao; +import com.sqx.modules.task.dao.HelpTakeDao; +import com.sqx.modules.task.entity.HelpOrder; +import com.sqx.modules.task.entity.HelpTake; +import com.sqx.modules.task.service.HelpTakeService; +import com.sqx.modules.utils.AmountCalUtils; +import com.sqx.modules.utils.excel.ExcelData; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * 接单订单 + * @author fang + * @date 2021/1/8 + */ +@Service +public class HelpTakeServiceImpl extends ServiceImpl implements HelpTakeService { + + @Autowired + private HelpTakeDao helpTakeDao; + @Autowired + private HelpOrderDao helpOrderDao; + @Autowired + private UserService userService; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private UserMoneyDetailsService userMoneyDetailsService; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private MessageService messageService; + @Autowired + private GameService gameService; + private static ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true); + + + @Override + public Result selectHelpTake(int page,int limit){ + return Result.success().put("data",helpTakeDao.selectList(new QueryWrapper<>())); + } + + @Override + public Result selectRunHelpOrder(int page,int limit,Integer status,Long userId){ + Page> pages=new Page<>(page,limit); + IPage> mapIPage = helpTakeDao.selectRunHelpOrder(pages, status, userId); + return Result.success().put("data",new PageUtils(mapIPage)); + } + + @Override + public Result selectRunHelpOrder(int page,int limit,Integer status,String phone,String startTime,String endTime){ + phone = phone.trim(); + Page> pages=new Page<>(page,limit); + IPage> mapIPage = helpTakeDao.selectRunHelpOrderList(pages, status, phone,startTime,endTime); + return Result.success().put("data",new PageUtils(mapIPage)); + } + + @Override + public ExcelData helpTakeListExcel(Integer status, String phone,String startTime,String endTime){ + phone = phone.trim(); + List> mapIPage = helpTakeDao.helpTakeListExcel( status, phone,startTime,endTime); + ExcelData data = new ExcelData(); + data.setName("接单列表"); + List titles = new ArrayList(); + titles.add("编号");titles.add("发单用户");titles.add("接单用户");titles.add("姓名"); + titles.add("手机号");titles.add("地址");titles.add("提交内容");titles.add("接单价格");titles.add("期望送达时间"); + titles.add("状态");titles.add("创建时间"); + data.setTitles(titles); + List> rows = new ArrayList(); + for(Map map:mapIPage){ + List row = new ArrayList(); + row.add(map.get("helpTakeId")); + row.add(map.get("userName")); + row.add(map.get("helpTakeUserName")); + row.add(map.get("name")); + row.add(map.get("phone")); + row.add(String.valueOf(map.get("province"))+String.valueOf(map.get("city"))+String.valueOf(map.get("district"))+String.valueOf(map.get("detailsAddress"))); + row.add(map.get("serviceName")); + row.add(map.get("money")); + row.add(map.get("deliveryTime")); + String status1 = String.valueOf(map.get("status")); + //1 已接单 2 已送达 3已下架 + if("1".equals(status1)){ + row.add("已接单"); + }else if("2".equals(status1)){ + row.add("已送达"); + }else if("3".equals(status1)){ + row.add("已放弃"); + }else{ + row.add("未知"); + } + row.add(map.get("createTime")); + rows.add(row); + } + data.setRows(rows); + return data; + + + + } + + @Override + public HelpTake selectHelpTakeById(Long helpTakeId){ + HelpTake helpTake = helpTakeDao.selectById(helpTakeId); + if(helpTake!=null){ + UserEntity userEntity = userService.selectUserById(helpTake.getUserId()); + helpTake.setUser(userEntity); + } + return helpTake; + } + + @Override + public Integer countHelpTakeByCreateTime(String time,Integer flag){ + return helpTakeDao.countHelpTakeByCreateTime(time, flag); + } + + @Override + public Double sumMoneyBySend(String time,Integer flag){ + return helpTakeDao.sumMoneyBySend(time, flag); + } + + + /** + * 接单 + * @param helpTake 接单实体类 + * @return 是否接单成功 + */ + @Override + public Result saveBody(HelpTake helpTake){ + reentrantReadWriteLock.writeLock().lock(); + try{ + HelpOrder helpOrder = helpOrderDao.selectById(helpTake.getOrderId()); + if(helpOrder.getStatus()!=2){ + return Result.error("系统繁忙,请刷新后重试!"); + } + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + helpTake.setStatus(1); + helpTake.setCreateTime(sdf.format(new Date())); + helpTake.setMoney(helpOrder.getCommission()); + helpTakeDao.insertHelpTake(helpTake); + helpOrder.setHelpTakeId(helpTake.getId()); + helpOrder.setStatus(3); + int code = (int) ((Math.random() * 9 + 1) * 1000); + helpOrder.setCode(String.valueOf(code)); + helpOrderDao.updateById(helpOrder); + UserEntity user = userService.selectUserById(helpOrder.getUserId()); + if (user.getClientid() != null) { + userService.pushToSingle("任务通知","您的任务已被接单!" , user.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的任务已被接单!"); + messageInfo.setTitle("任务通知"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(user.getUserName()); + messageInfo.setUserId(String.valueOf(user.getUserId())); + messageService.saveBody(messageInfo); + return Result.success(); + }catch (Exception e){ + e.printStackTrace(); + }finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请刷新后重试!"); + } + + + @Override + public Result endHelpTake(Long id){ + reentrantReadWriteLock.writeLock().lock(); + try{ + HelpTake helpTake = helpTakeDao.selectById(id); + if(!helpTake.getStatus().equals(1)){ + return Result.error("系统繁忙,请稍后再试!"); + } + helpTake.setStatus(3); + helpTakeDao.deleteById(helpTake.getId()); + HelpOrder helpOrder = helpOrderDao.selectById(helpTake.getOrderId()); + helpOrder.setHelpTakeId(-1L); + helpOrder.setStatus(2); + helpOrderDao.updateById(helpOrder); + UserEntity user = userService.selectUserById(helpOrder.getUserId()); + if (user.getClientid() != null) { + userService.pushToSingle("订单通知","您的订单已被取消,系统已经帮你重新发布!" , user.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的订单已被取消,系统已经帮你重新发布!"); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(user.getUserName()); + messageInfo.setUserId(String.valueOf(user.getUserId())); + messageService.saveBody(messageInfo); + return Result.success(); + }catch (Exception e){ + e.printStackTrace(); + }finally { + reentrantReadWriteLock.writeLock().unlock(); + } + return Result.error("系统繁忙,请刷新后重试!"); + } + + + + + + /** + * 确认送达 + * @param helpTakeId 接单id + * @param helpOrderId 派单id + * @param code 收货码 + * @return 是否送达成功 + */ + @Override + public Result closeOrder(Long helpTakeId,Long helpOrderId,String code){ + HelpOrder helpOrder = helpOrderDao.selectById(helpOrderId); + if(helpOrder.getStatus()!=3){ + return Result.error("请刷新后重试!"); + } + if(!helpOrder.getCode().equals(code)){ + return Result.error("收货码不正确!"); + } + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(new Date()); + HelpTake helpTake = helpTakeDao.selectById(helpTakeId); + helpOrder.setStatus(4); + helpTake.setStatus(2); + helpTake.setEndTime(date); + helpOrderDao.updateById(helpOrder); + helpTakeDao.updateById(helpTake); + userMoneyService.updateMoney(1,helpTake.getUserId(),helpTake.getMoney()); + Game game = gameService.getById(helpOrder.getGameId()); + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setUserId(helpTake.getUserId()); + userMoneyDetails.setTitle("[接单完成]:"+game.getGameName()); + userMoneyDetails.setContent("增加金额:"+helpTake.getMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(helpTake.getMoney()); + userMoneyDetails.setCreateTime(date); + userMoneyDetailsService.save(userMoneyDetails); + BigDecimal sub = AmountCalUtils.sub(helpOrder.getMoney(), helpTake.getMoney()); + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + if (userEntity.getClientid() != null) { + userService.pushToSingle("订单通知","您的订单已经完成!" , userEntity.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的订单已经完成!"); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageService.saveBody(messageInfo); + return Result.success(); + } + + + @Override + public Result closeOrders(Long helpOrderId){ + HelpOrder helpOrder = helpOrderDao.selectById(helpOrderId); + if(helpOrder.getStatus()!=3){ + return Result.error("请刷新后重试!"); + } + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(new Date()); + HelpTake helpTake = helpTakeDao.selectById(helpOrder.getHelpTakeId()); + helpOrder.setStatus(4); + helpTake.setStatus(2); + helpTake.setEndTime(date); + helpOrderDao.updateById(helpOrder); + helpTakeDao.updateById(helpTake); + userMoneyService.updateMoney(1,helpTake.getUserId(),helpTake.getMoney()); + Game game = gameService.getById(helpOrder.getGameId()); + UserMoneyDetails userMoneyDetails=new UserMoneyDetails(); + userMoneyDetails.setUserId(helpTake.getUserId()); + userMoneyDetails.setTitle("[接单完成]:"+game.getGameName()); + userMoneyDetails.setContent("增加金额:"+helpTake.getMoney()); + userMoneyDetails.setType(1); + userMoneyDetails.setMoney(helpTake.getMoney()); + userMoneyDetails.setCreateTime(date); + userMoneyDetailsService.save(userMoneyDetails); + UserEntity userEntity = userService.selectUserById(helpOrder.getUserId()); + if (userEntity.getClientid() != null) { + userService.pushToSingle("订单通知","您的订单已经完成!" , userEntity.getClientid()); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("您的订单已经完成!"); + messageInfo.setTitle("订单通知"); + messageInfo.setState(String.valueOf(4)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageService.saveBody(messageInfo); + return Result.success(); + } + + + + @Override + public Result updateHelpTakeById(HelpTake helpTake){ + helpTakeDao.updateById(helpTake); + return Result.success(); + } + + @Override + public Result deleteById(Long id){ + helpTakeDao.deleteById(id); + return Result.success(); + } + + + + + +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/controller/coupon/AdminTbCouponController.java b/src/main/java/com/sqx/modules/tbCoupon/controller/coupon/AdminTbCouponController.java new file mode 100644 index 0000000..968cc1e --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/controller/coupon/AdminTbCouponController.java @@ -0,0 +1,57 @@ +package com.sqx.modules.tbCoupon.controller.coupon; + +import com.sqx.common.utils.Result; +import com.sqx.modules.sys.controller.AbstractController; +import com.sqx.modules.tbCoupon.dao.TbCouponUserDao; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; +import java.util.List; + +@RestController +@Api(value = "管理端-优惠券", tags = {"管理端-优惠券"}) +@RequestMapping(value = "/admin/coupon/") +public class AdminTbCouponController extends AbstractController { + + @Autowired + private TbCouponService tbCouponService; + + @ApiOperation("发布优惠券") + @PostMapping(value = "addCoupon") + public Result addCoupon(TbCoupon tbCoupon) { + + return tbCouponService.addCoupon(tbCoupon); + } + + @ApiOperation("获取优惠券列表") + @GetMapping(value = "getCouponPageList") + public Result getCouponPageList(Integer page, Integer limit, TbCoupon tbCoupon) { + return Result.success().put("data", tbCouponService.getCouponPageList(page, limit, tbCoupon)); + } + + @ApiOperation("删除发布的优惠券") + @PostMapping(value = "deleteCoupon") + public Result deleteCoupon(Long couponId) { + return tbCouponService.deleteCoupon(couponId); + } + + @ApiOperation("修改优惠券信息") + @PostMapping(value = "updateCoupon") + public Result updateCoupon(TbCoupon tbCoupon) { + + return tbCouponService.updateCoupon(tbCoupon); + } + @ApiOperation("管理端赠送用户优惠券") + @GetMapping(value = "/giveCoupon") + public Result giveCoupon(Long couponId, String userIds) { + String[] userId = userIds.split(","); + List userIdList = Arrays.asList(userId); + return tbCouponService.giveCoupon(couponId, userIdList); + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/tbCoupon/controller/coupon/AppTbCouponController.java b/src/main/java/com/sqx/modules/tbCoupon/controller/coupon/AppTbCouponController.java new file mode 100644 index 0000000..a01aaea --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/controller/coupon/AppTbCouponController.java @@ -0,0 +1,31 @@ +package com.sqx.modules.tbCoupon.controller.coupon; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.sys.controller.AbstractController; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Api(value = "管理端-优惠券", tags = {"管理端-优惠券"}) +@RequestMapping(value = "/app/coupon/") +public class AppTbCouponController extends AbstractController { + + @Autowired + private TbCouponService tbCouponService; + + @ApiOperation("获取可购买的优惠券列表") + @GetMapping(value = "getCouponPageList") + public Result getCouponPageList(Integer page, Integer limit, TbCoupon tbCoupon) { + tbCoupon.setIsEnable(1); + tbCoupon.setDeleteFlag(0); + return Result.success().put("data", tbCouponService.getCouponPageList(page, limit, tbCoupon)); + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/tbCoupon/controller/couponUser/AdminTbCouponUserController.java b/src/main/java/com/sqx/modules/tbCoupon/controller/couponUser/AdminTbCouponUserController.java new file mode 100644 index 0000000..6925b60 --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/controller/couponUser/AdminTbCouponUserController.java @@ -0,0 +1,28 @@ +package com.sqx.modules.tbCoupon.controller.couponUser; + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.sys.controller.AbstractController; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + + +@RestController +@Api(value = "管理端-优惠券", tags = {"管理端-用户优惠券"}) +@RequestMapping(value = "/admin/couponUser/") +public class AdminTbCouponUserController extends AbstractController { + + @Autowired + private TbCouponUserService couponUserService; + + + @ApiOperation("查看指定用户优惠券列表") + @GetMapping(value = "getMyCouponList") + public Result getMyCouponList(Integer page, Integer limit, TbCouponUser couponUser) { + return Result.success().put("data", couponUserService.getMyCouponList( page, limit, couponUser)); + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/tbCoupon/controller/couponUser/AppTbCouponUserController.java b/src/main/java/com/sqx/modules/tbCoupon/controller/couponUser/AppTbCouponUserController.java new file mode 100644 index 0000000..53a408f --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/controller/couponUser/AppTbCouponUserController.java @@ -0,0 +1,74 @@ +package com.sqx.modules.tbCoupon.controller.couponUser; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; + +import com.sqx.modules.sys.controller.AbstractController; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; +import java.util.List; + + +@RestController +@Api(value = "用户端-优惠券", tags = {"用户端-优惠券"}) +@RequestMapping(value = "/app/couponUser/") +public class AppTbCouponUserController extends AbstractController { + + @Autowired + private TbCouponUserService couponUserService; + + @Login + @ApiOperation("水贝购买优惠券") + @PostMapping(value = "buyCoupon") + public Result buyCoupon(@RequestAttribute Long userId, Long couponId, Integer buyNum) { + return couponUserService.buyCoupon(userId, couponId, buyNum); + } + + @Login + @ApiOperation("查看我的优惠券列表") + @GetMapping(value = "getMyCouponList") + public Result getMyCouponList(@RequestAttribute Long userId, Integer page, Integer limit, TbCouponUser couponUser) { + couponUser.setUserId(userId); + return Result.success().put("data", couponUserService.getMyCouponList(page, limit, couponUser)); + } + + @Login + @ApiOperation("领取新人优惠券") + @GetMapping("receiveEnvelope") + public Result receiveEnvelope(@RequestAttribute("userId") Long userId, Long couponId, Integer num) { + + return couponUserService.receiveEnvelope(userId, couponId, num); + } + + + @Login + @ApiOperation("领取活动优惠券") + @GetMapping("receiveActivity") + public Result receiveActivity(@RequestAttribute("userId") Long userId, Long couponId) { + return couponUserService.receiveActivity(userId, couponId); + } + + + /** + * 检测使优惠券过期 + */ + @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai") + public void couponOverdue() { + List couponUserList = couponUserService.list(new QueryWrapper().eq("status", 0).isNotNull("expiration_time")); + for (TbCouponUser tbCouponUser : couponUserList) { + if (tbCouponUser.getExpirationTime().before(new Date())) { + tbCouponUser.setStatus(2); + couponUserService.updateById(tbCouponUser); + } + } + + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/tbCoupon/dao/TbCouponDao.java b/src/main/java/com/sqx/modules/tbCoupon/dao/TbCouponDao.java new file mode 100644 index 0000000..cb41b78 --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/dao/TbCouponDao.java @@ -0,0 +1,18 @@ +package com.sqx.modules.tbCoupon.dao; + +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; + +/** + *

+ * Mapper 接口 + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +@Mapper +public interface TbCouponDao extends BaseMapper { + +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/dao/TbCouponUserDao.java b/src/main/java/com/sqx/modules/tbCoupon/dao/TbCouponUserDao.java new file mode 100644 index 0000000..0865ef6 --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/dao/TbCouponUserDao.java @@ -0,0 +1,18 @@ +package com.sqx.modules.tbCoupon.dao; + +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; + +/** + *

+ * Mapper 接口 + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +@Mapper +public interface TbCouponUserDao extends BaseMapper { + +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/entity/TbCoupon.java b/src/main/java/com/sqx/modules/tbCoupon/entity/TbCoupon.java new file mode 100644 index 0000000..c3cf74b --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/entity/TbCoupon.java @@ -0,0 +1,81 @@ +package com.sqx.modules.tbCoupon.entity; + +import java.math.BigDecimal; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.SqlCondition; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +@Data +public class TbCoupon implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "coupon_id", type = IdType.AUTO) + private Long couponId; + + /** + * 优惠券名称 + */ + @TableField(condition = SqlCondition.LIKE) + private String couponName; + + /** + * 优惠券图片 + */ + private String couponPicture; + + /** + * 有效期天数 + */ + private Integer validDays; + + /** + * 优惠券可使用订单最低金额 + */ + private BigDecimal minMoney; + + /** + * 优惠券抵扣金额 + */ + private BigDecimal money; + /** + * 购买优惠券的价格 + */ + private BigDecimal buyMoney; + + /** + * 是否删除 0未删除 1已删除 + */ + private Integer deleteFlag; + /** + * 是否启用 0未启用 1已启用 + */ + private Integer isEnable; + /** + * 优惠券类型 1新手赠送 2出售 3免费领取 + */ + private Integer couponType; + /** + * 最多领取或购买数量(0为不限制数量) + */ + private Integer maxReceive; + /** + * 优惠券数量 + */ + private Integer couponNum; + + +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/entity/TbCouponUser.java b/src/main/java/com/sqx/modules/tbCoupon/entity/TbCouponUser.java new file mode 100644 index 0000000..5923998 --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/entity/TbCouponUser.java @@ -0,0 +1,86 @@ +package com.sqx.modules.tbCoupon.entity; + +import java.math.BigDecimal; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.SqlCondition; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.models.auth.In; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + *

+ * + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +@Data +public class TbCouponUser implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + /** + * 用户id + */ + private Long userId; + + /** + * 优惠券名称 + */ + @TableField(condition = SqlCondition.LIKE) + private String couponName; + + /** + * 优惠券图片 + */ + private String couponPicture; + + /** + * 优惠券领取时间 + */ + private Date createTime; + + /** + * 优惠券使用时间 + */ + private Date employTime; + + /** + * 优惠券过期时间 + */ + private Date expirationTime; + + /** + * 优惠券可使用订单最低金额 + */ + private BigDecimal minMoney; + + /** + * 优惠券金额 + */ + private BigDecimal money; + + /** + * 优惠券状态 0正常 1已使用 2已失效 + */ + private Integer status; + + /** + * 有效天数 + */ + private Integer validDays; + /** + * 优惠券id + */ + private Long couponId; + +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/service/TbCouponService.java b/src/main/java/com/sqx/modules/tbCoupon/service/TbCouponService.java new file mode 100644 index 0000000..054549b --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/service/TbCouponService.java @@ -0,0 +1,31 @@ +package com.sqx.modules.tbCoupon.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.Result; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.math.BigDecimal; +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +public interface TbCouponService extends IService { + + Result addCoupon(TbCoupon tbCoupon); + + IPage getCouponPageList(Integer page, Integer limit, TbCoupon tbCoupon); + + Result deleteCoupon(Long couponId); + + Result updateCoupon(TbCoupon tbCoupon); + + + Result giveCoupon(Long couponId, List userIdList); +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/service/TbCouponUserService.java b/src/main/java/com/sqx/modules/tbCoupon/service/TbCouponUserService.java new file mode 100644 index 0000000..dc84aba --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/service/TbCouponUserService.java @@ -0,0 +1,30 @@ +package com.sqx.modules.tbCoupon.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.Result; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.math.BigDecimal; + +/** + *

+ * 服务类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +public interface TbCouponUserService extends IService { + + Result businessCallback(Integer payType, Long userId, Long couponId, Integer buyNum, BigDecimal totalPrice); + + Result buyCoupon(Long userId, Long couponId, Integer buyNum); + + IPage getMyCouponList(Integer page, Integer limit, TbCouponUser couponUser); + + Result receiveEnvelope(Long userId, Long couponId,Integer num); + + Result receiveActivity(Long userId, Long couponId); +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/service/impl/TbCouponServiceImpl.java b/src/main/java/com/sqx/modules/tbCoupon/service/impl/TbCouponServiceImpl.java new file mode 100644 index 0000000..f5458eb --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/service/impl/TbCouponServiceImpl.java @@ -0,0 +1,99 @@ +package com.sqx.modules.tbCoupon.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.dao.TbCouponDao; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import jodd.util.StringUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +/** + *

+ * 服务实现类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +@Service +public class TbCouponServiceImpl extends ServiceImpl implements TbCouponService { + + @Autowired + private TbCouponDao tbCouponDao; + @Autowired + private TbCouponUserService couponUserDao; + + @Override + public Result addCoupon(TbCoupon tbCoupon) { + tbCoupon.setDeleteFlag(0); + tbCouponDao.insert(tbCoupon); + return Result.success(); + } + + @Override + public IPage getCouponPageList(Integer page, Integer limit, TbCoupon tbCoupon) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + return tbCouponDao.selectPage(pages, new QueryWrapper<>(tbCoupon)); + } + + @Override + public Result deleteCoupon(Long couponId) { + return Result.upStatus(tbCouponDao.deleteById(couponId)); + } + + @Override + public Result updateCoupon(TbCoupon tbCoupon) { + return Result.upStatus(tbCouponDao.updateById(tbCoupon)); + } + + public Result giveCoupon(Long couponId, List userIdList) { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + TbCoupon tbCoupon = tbCouponDao.selectById(couponId); + for (String userId : userIdList) { + TbCouponUser couponUser = new TbCouponUser(); + BeanUtils.copyProperties(tbCoupon, couponUser); + couponUser.setCreateTime(new Date()); + LocalDateTime dateTime = LocalDateTime.now().plusDays(tbCoupon.getValidDays()); + couponUser.setExpirationTime(Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant())); + couponUser.setUserId(Long.valueOf(userId)); + couponUser.setStatus(0); + couponUser.setValidDays(tbCoupon.getValidDays()); + couponUserDao.save(couponUser); + } + + return Result.success(); + } + + +} diff --git a/src/main/java/com/sqx/modules/tbCoupon/service/impl/TbCouponUserServiceImpl.java b/src/main/java/com/sqx/modules/tbCoupon/service/impl/TbCouponUserServiceImpl.java new file mode 100644 index 0000000..2f7e922 --- /dev/null +++ b/src/main/java/com/sqx/modules/tbCoupon/service/impl/TbCouponUserServiceImpl.java @@ -0,0 +1,241 @@ +package com.sqx.modules.tbCoupon.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.tbCoupon.entity.TbCoupon; +import com.sqx.modules.tbCoupon.entity.TbCouponUser; +import com.sqx.modules.tbCoupon.dao.TbCouponUserDao; +import com.sqx.modules.tbCoupon.service.TbCouponService; +import com.sqx.modules.tbCoupon.service.TbCouponUserService; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import jodd.util.StringUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + *

+ * 服务实现类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-18 + */ +@Service +public class TbCouponUserServiceImpl extends ServiceImpl implements TbCouponUserService { + @Autowired + private TbCouponService tbCouponService; + @Autowired + private TbCouponUserDao couponUserDao; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private UserMoneyDetailsService moneyDetailsService; + @Autowired + private UserService userService; + @Autowired + private MessageService messageService; + @Autowired + private CommonInfoService commonInfoService; + + /** + * 统一支付回调 + * + * @param payType 支付类型1水贝 2微信 3支付宝 + * @param couponId 购买的优惠券id + * @param userId 用户id + * @param buyNum 购买数量 + * @param totalPrice 总价 + * @return + */ + @Override + public Result businessCallback(Integer payType, Long userId, Long couponId, Integer buyNum, BigDecimal totalPrice) { + TbCoupon tbCoupon = tbCouponService.getById(couponId); + if (payType == 1) { + userMoneyService.updateMoney(2, userId, totalPrice); + } + UserMoneyDetails details = new UserMoneyDetails(); + details.setUserId(userId); + + details.setClassify(6); + details.setType(2); + details.setMoney(totalPrice); + details.setPayType(payType); + String content; + if (payType == 1) { + content = "水贝"; + } else if (payType == 2) { + content = "微信"; + } else if (payType == 3) { + content = "支付宝"; + } else { + return Result.error("支付参数错误"); + } + details.setTitle(content + "支付" + totalPrice + "购买优惠券" + tbCoupon.getCouponName() + "共" + buyNum * tbCoupon.getCouponNum() + "个"); + details.setContent(content + "支付" + totalPrice + "购买优惠券" + tbCoupon.getCouponName() + "共" + buyNum * tbCoupon.getCouponNum() + "个"); + details.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + moneyDetailsService.save(details); + TbCouponUser couponUser = new TbCouponUser(); + for (int i = 0; i < buyNum * tbCoupon.getCouponNum(); i++) { + //copy对象 + BeanUtils.copyProperties(tbCoupon, couponUser); + couponUser.setUserId(userId); + couponUser.setCreateTime(new Date()); + //是否是永久有效 + if (tbCoupon.getValidDays() != null && tbCoupon.getValidDays() != 0) { + //如果不是永久 + Calendar instance = Calendar.getInstance(); + instance.setTime(new Date()); + instance.add(Calendar.DATE, tbCoupon.getValidDays()); + couponUser.setExpirationTime(instance.getTime()); + couponUser.setValidDays(tbCoupon.getValidDays()); + } else { + couponUser.setValidDays(0); + } + couponUser.setStatus(0); + couponUserDao.insert(couponUser); + } + UserEntity userEntity = userService.getById(userId); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setTitle("优惠券购买成功"); + messageInfo.setContent("优惠券购买成功"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(String.valueOf(userEntity.getUserId())); + messageInfo.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + + return Result.success(); + } + + @Override + public Result buyCoupon(Long userId, Long couponId, Integer buyNum) { + TbCoupon tbCoupon = tbCouponService.getById(couponId); + if (tbCoupon == null || tbCoupon.getIsEnable() == 0 || tbCoupon.getDeleteFlag() == 1) { + return Result.error("优惠券暂未出售或不存在"); + } + if (tbCoupon.getCouponType() != 2) { + return Result.error("当前优惠券不支持购买"); + } + //查看当前用户已购买或领取数量 + Integer num = couponUserDao.selectCount(new QueryWrapper().eq("user_id", userId).eq("coupon_id", couponId)); + if (tbCoupon.getMaxReceive() != 0) { + if ((tbCoupon.getMaxReceive() - num) < buyNum) { + return Result.error("当前可购买或领取的数量已到达上限"); + } + } + BigDecimal totalPrice = tbCoupon.getBuyMoney().multiply(new BigDecimal(buyNum)); + + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + if (userMoney.getMoney().compareTo(totalPrice) >= 0) { + return businessCallback(1, userId, couponId, buyNum, totalPrice); + } else { + return Result.error("余额不足"); + } + } + + @Override + public IPage getMyCouponList(Integer page, Integer limit, TbCouponUser couponUser) { + + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + return couponUserDao.selectPage(pages, new QueryWrapper<>(couponUser)); + } + + @Override + public Result receiveEnvelope(Long userId, Long couponId, Integer num) { + UserEntity userEntity = userService.getById(userId); + if (userEntity.getIsNewPeople() != 1) { + return Result.error("你不是新人,暂时无法领取"); + } + CommonInfo commonInfo = commonInfoService.findOne(316); + if(commonInfo!=null && commonInfo.getValue().equals("0")){ + return Result.error("新人优惠券暂未开启"); + } + TbCoupon tbCoupon = tbCouponService.getById(couponId); + TbCouponUser couponUser = new TbCouponUser(); + for (int i = 0; i < num; i++) { + //copy对象 + BeanUtils.copyProperties(tbCoupon, couponUser); + couponUser.setUserId(userId); + couponUser.setCreateTime(new Date()); + //是否是永久有效 + if (tbCoupon.getValidDays() != null && tbCoupon.getValidDays() != 0) { + //如果不是永久 + Calendar instance = Calendar.getInstance(); + instance.setTime(new Date()); + instance.add(Calendar.DATE, tbCoupon.getValidDays()); + couponUser.setExpirationTime(instance.getTime()); + couponUser.setValidDays(tbCoupon.getValidDays()); + } else { + couponUser.setValidDays(0); + } + couponUser.setStatus(0); + couponUserDao.insert(couponUser); + } + userEntity.setIsNewPeople(0); + userService.updateById(userEntity); + return Result.success(); + } + + @Override + public Result receiveActivity(Long userId, Long couponId) { + TbCoupon tbCoupon = tbCouponService.getById(couponId); + if (tbCoupon.getIsEnable() != 1) { + return Result.error("当期活动已关闭"); + } + Integer num = couponUserDao.selectCount(new QueryWrapper().eq("user_id", userId).eq("coupon_id", tbCoupon.getCouponId())); + if (tbCoupon.getMaxReceive() != 0) { + if (tbCoupon.getMaxReceive() <= num) { + return Result.error("当前可领取的数量已到达上限"); + } + } + TbCouponUser couponUser = new TbCouponUser(); + for (int i = 0; i < tbCoupon.getCouponNum(); i++) { + //copy对象 + BeanUtils.copyProperties(tbCoupon, couponUser); + couponUser.setUserId(userId); + couponUser.setCreateTime(new Date()); + //是否是永久有效 + if (tbCoupon.getValidDays() != null && tbCoupon.getValidDays() != 0) { + //如果不是永久 + Calendar instance = Calendar.getInstance(); + instance.setTime(new Date()); + instance.add(Calendar.DATE, tbCoupon.getValidDays()); + couponUser.setExpirationTime(instance.getTime()); + couponUser.setValidDays(tbCoupon.getValidDays()); + } else { + couponUser.setValidDays(0); + } + couponUser.setStatus(0); + couponUserDao.insert(couponUser); + } + return Result.success(); + } +} diff --git a/src/main/java/com/sqx/modules/tickets/controller/AdminTicketsController.java b/src/main/java/com/sqx/modules/tickets/controller/AdminTicketsController.java new file mode 100644 index 0000000..11aa5f6 --- /dev/null +++ b/src/main/java/com/sqx/modules/tickets/controller/AdminTicketsController.java @@ -0,0 +1,59 @@ +package com.sqx.modules.tickets.controller; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.tickets.service.TicketsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + *

+ * 前端控制器 + *

+ * + * @author wuchang + * @since 2022-11-16 + */ +@RestController +@RequestMapping("/admin/tickets/") +@Api(value = "水票", tags = {"水票-管理端"}) +public class AdminTicketsController { + @Autowired + private TicketsService ticketsService; + + @ApiOperation("新增水票") + @PostMapping("addTickets") + public Result addTickets(Tickets tickets) { + return ticketsService.addTickets(tickets); + } + + @ApiOperation("修改水票") + @PostMapping("updateTickets") + public Result updateTickets(Tickets tickets) { + return ticketsService.updateTickets(tickets); + } + + @ApiOperation("获取分页水票列表") + @GetMapping("getTicketsList") + public Result getTicketsList(Integer page, Integer limit, Tickets tickets) { + return Result.success().put("data", ticketsService.getTicketsList(page, limit, tickets)); + } + + @ApiOperation("删除水票") + @GetMapping("deleteTickets") + public Result deleteTickets(Long ticketsId) { + ticketsService.removeById(ticketsId); + return Result.success(); + } + @ApiOperation("获取水票详细信息") + @GetMapping("getTicketsInfoById") + public Result getTicketsInfoById(Long ticketsId){ + return Result.success().put("data", ticketsService.getById(ticketsId)); + } +} + diff --git a/src/main/java/com/sqx/modules/tickets/controller/AppTicketsController.java b/src/main/java/com/sqx/modules/tickets/controller/AppTicketsController.java new file mode 100644 index 0000000..ea8acfa --- /dev/null +++ b/src/main/java/com/sqx/modules/tickets/controller/AppTicketsController.java @@ -0,0 +1,58 @@ +package com.sqx.modules.tickets.controller; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.tickets.service.TicketsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.java.Log; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + *

+ * 前端控制器 + *

+ * + * @author wuchang + * @since 2022-11-16 + */ +@RestController +@RequestMapping("/app/tickets/") +@Api(value = "水票", tags = {"水票-管理端"}) +public class AppTicketsController { + @Autowired + private TicketsService ticketsService; + + @ApiOperation("获取分页水票列表") + @GetMapping("getTicketsList") + public Result getTicketsList(Integer page, Integer limit, Tickets tickets) { + tickets.setIsEnable(1); + return Result.success().put("data", ticketsService.getAppTicketsList(page, limit, tickets)); + } + + @ApiOperation("获取水票详细信息") + @GetMapping("getTicketsInfoById") + public Result getTicketsInfoById(Long ticketsId) { + return Result.success().put("data", ticketsService.getById(ticketsId)); + } + + @Login + @ApiOperation("水贝购买水票") + @PostMapping("buyTickets") + public Result buyTickets(@RequestAttribute("userId") Long userId, Long ticketsId, Integer buyNum) { + return ticketsService.buyTickets(userId, ticketsId, buyNum); + } + + @Login + @ApiOperation("获取登录用户可用水票数量") + @GetMapping("getUserTicketNum") + public Result getUserTicketNum(@RequestAttribute("userId") Long userId,Long relationId) { + return ticketsService.getUserTicketNum(userId,relationId); + } +} + diff --git a/src/main/java/com/sqx/modules/tickets/dao/TicketsDao.java b/src/main/java/com/sqx/modules/tickets/dao/TicketsDao.java new file mode 100644 index 0000000..b9a896f --- /dev/null +++ b/src/main/java/com/sqx/modules/tickets/dao/TicketsDao.java @@ -0,0 +1,27 @@ +package com.sqx.modules.tickets.dao; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.tickets.entity.Tickets; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + *

+ * Mapper 接口 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@Mapper +public interface TicketsDao extends BaseMapper { + + IPage getTicketsList(@Param("pages") Page pages, @Param("tickets") Tickets tickets); + + IPage getAppTicketsList(@Param("pages") Page pages, @Param("tickets") Tickets tickets); + + + Integer getUserTicketCount(@Param("userId") Long userId, Long relationId); +} diff --git a/src/main/java/com/sqx/modules/tickets/entity/Tickets.java b/src/main/java/com/sqx/modules/tickets/entity/Tickets.java new file mode 100644 index 0000000..20d5060 --- /dev/null +++ b/src/main/java/com/sqx/modules/tickets/entity/Tickets.java @@ -0,0 +1,87 @@ +package com.sqx.modules.tickets.entity; + +import java.math.BigDecimal; + +import com.baomidou.mybatisplus.annotation.*; +import com.sqx.modules.taking.entity.OrderTaking; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.time.LocalDateTime; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + *

+ * + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@Data +public class Tickets implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 水票id + */ + @TableId(value = "tickets_id", type = IdType.AUTO) + private Long ticketsId; + + /** + * 购买价格 + */ + private BigDecimal buyMoney; + + /** + * 水票标题 + */ + @TableField(condition = SqlCondition.LIKE) + private String title; + /** + * 水票图片 + */ + private String ticketsImg; + /** + * 关联的商品id + */ + private Long relationId; + /** + * 是否启用 1启用 0 不启用 + */ + private Integer isEnable; + /** + * 数量 + */ + private Integer num; + /** + * 排序 + */ + private Integer sort; + /** + * 是否删除 -1已删除 + */ + @TableLogic + private Integer isDelete; + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + /** + * 关联的商品 + */ + @TableField(exist = false) + private OrderTaking orderTaking; + /** + * 关联的商品名称 + */ + @TableField(exist = false) + + private String relationName; +} diff --git a/src/main/java/com/sqx/modules/tickets/service/TicketsService.java b/src/main/java/com/sqx/modules/tickets/service/TicketsService.java new file mode 100644 index 0000000..cbf0a95 --- /dev/null +++ b/src/main/java/com/sqx/modules/tickets/service/TicketsService.java @@ -0,0 +1,42 @@ +package com.sqx.modules.tickets.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.Result; +import com.sqx.modules.tickets.entity.Tickets; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.math.BigDecimal; + +/** + *

+ * 服务类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +public interface TicketsService extends IService { + + Result addTickets(Tickets tickets); + + Result updateTickets(Tickets tickets); + + IPage getTicketsList(Integer page, Integer limit, Tickets tickets); + + /** + * + * @param userId + * @param ticketsId + * @param buyNum + * @return + */ + Result buyTickets(Long userId, Long ticketsId, Integer buyNum); + + + Result businessCallback(Integer payType, Long userId, BigDecimal payMoney, Long ticketsId, Integer buyNum, String tradeNo); + + Result getUserTicketNum(Long userId, Long relationId); + + IPage getAppTicketsList(Integer page, Integer limit, Tickets tickets); + +} diff --git a/src/main/java/com/sqx/modules/tickets/service/impl/TicketsServiceImpl.java b/src/main/java/com/sqx/modules/tickets/service/impl/TicketsServiceImpl.java new file mode 100644 index 0000000..8d862b8 --- /dev/null +++ b/src/main/java/com/sqx/modules/tickets/service/impl/TicketsServiceImpl.java @@ -0,0 +1,187 @@ +package com.sqx.modules.tickets.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserMoney; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserMoneyService; +import com.sqx.modules.pay.entity.PayDetails; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.OrderTakingService; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.tickets.dao.TicketsDao; +import com.sqx.modules.tickets.service.TicketsService; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import com.sqx.modules.ticketsUserRole.service.TicketsUserRoleService; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + *

+ * 服务实现类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@Service +public class TicketsServiceImpl extends ServiceImpl implements TicketsService { + @Autowired + private TicketsDao ticketsDao; + @Autowired + private OrderTakingService takingService; + @Autowired + private UserMoneyService userMoneyService; + @Autowired + private UserMoneyDetailsService detailsService; + @Autowired + private TicketsUserRoleService userRoleService; + + @Override + public Result addTickets(Tickets tickets) { + if (tickets.getRelationId() == null) { + return Result.error("必须关联商品"); + } + OrderTaking orderTaking = takingService.getById(tickets.getRelationId()); + if (orderTaking == null) { + return Result.error("选择的商品不存在"); + } + return Result.upStatus(ticketsDao.insert(tickets)); + + + } + + @Override + public Result updateTickets(Tickets tickets) { + if (tickets.getTicketsId() == null) { + return Result.error("水票id不能为空"); + } + if (tickets.getRelationId()!=null){ + OrderTaking orderTaking = takingService.getById(tickets.getRelationId()); + if (orderTaking == null) { + return Result.error("选择的商品不存在"); + } + } + + return Result.upStatus(ticketsDao.updateById(tickets)); + } + + @Override + public IPage getTicketsList(Integer page, Integer limit, Tickets tickets) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + return baseMapper.getTicketsList(pages, tickets); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public Result buyTickets(Long userId, Long ticketsId, Integer buyNum) { + Tickets tickets = ticketsDao.selectById(ticketsId); + if (tickets == null) { + return Result.error("选择的水票不存在"); + } + if (tickets.getIsEnable() != 1) { + return Result.error("当前水票已暂停购买"); + } + BigDecimal payMoney = tickets.getBuyMoney().multiply(new BigDecimal(buyNum)); + UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId); + if (userMoney.getMoney().compareTo(payMoney) >= 0) { + return businessCallback(1, userId, payMoney, ticketsId, buyNum,null); + } else { + return Result.error("水贝不足"); + } + + } + + /** + * 购买水票支付回调 + * + * @param payType 支付类型 1水贝 2微信 3支付宝 + * @param userId 购买用户id + * @param payMoney 支付金额 + * @param ticketsId 水票id + * @param buyNum 购买数量 + * @return + */ + @Override + public Result businessCallback(Integer payType, Long userId, BigDecimal payMoney, Long ticketsId, Integer buyNum,String tradeNo) { + if (payType == 1) { + userMoneyService.updateMoney(2, userId, payMoney); + } + Tickets tickets = ticketsDao.selectById(ticketsId); + UserMoneyDetails details = new UserMoneyDetails(); + details.setUserId(userId); + details.setClassify(5); + details.setOrdersNo(tradeNo); + details.setPayType(payType); + details.setMoney(payMoney); + details.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); + details.setType(2); + String content = null; + if (payType == 1) { + content = "水贝"; + } else if (payType == 2) { + content = "微信"; + } else if (payType == 3) { + content = "支付宝"; + } + details.setTitle(content+"购买水票成功"); + details.setContent(content + "支付" + payMoney + "购买水票【" + tickets.getTitle() + "】共" + buyNum * tickets.getNum() + "个"); + details.setState(1); + detailsService.save(details); + TicketsUserRole ticketsUserRole = userRoleService.getOne(new QueryWrapper().eq("user_id", userId).eq("tickets_id", ticketsId)); + if (ticketsUserRole == null) { + TicketsUserRole userRole = new TicketsUserRole(); + userRole.setUserId(userId); + userRole.setTicketsId(ticketsId); + userRole.setCreateTime(new Date()); + userRole.setStock(buyNum * tickets.getNum()); + userRole.setNum(0); + userRoleService.save(userRole); + } else { + ticketsUserRole.setStock(ticketsUserRole.getStock() + buyNum * tickets.getNum()); + userRoleService.updateById(ticketsUserRole); + } + + + return Result.success(); + } + + + @Override + public Result getUserTicketNum(Long userId, Long relationId) { + return Result.success().put("data", ticketsDao.getUserTicketCount(userId,relationId)); + + } + + @Override + public IPage getAppTicketsList(Integer page, Integer limit, Tickets tickets) { + + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + return baseMapper.getAppTicketsList(pages, tickets); + + + } + +} diff --git a/src/main/java/com/sqx/modules/ticketsGiveRecord/controller/TicketsGiveRecordController.java b/src/main/java/com/sqx/modules/ticketsGiveRecord/controller/TicketsGiveRecordController.java new file mode 100644 index 0000000..e763e49 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsGiveRecord/controller/TicketsGiveRecordController.java @@ -0,0 +1,35 @@ +package com.sqx.modules.ticketsGiveRecord.controller; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.ticketsGiveRecord.entity.TicketsGiveRecord; +import com.sqx.modules.ticketsGiveRecord.service.TicketsGiveRecordService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import org.springframework.web.bind.annotation.RestController; + +/** + *

+ * 前端控制器 + *

+ * + * @author wuchang + * @since 2022-11-23 + */ +@RestController +@RequestMapping("/admin/ticketsGiveRecord/") +@Api(value = "水票赠送记录", tags = {"水票赠送记录-管理端"}) +public class TicketsGiveRecordController { + @Autowired + private TicketsGiveRecordService giveRecordService; + @ApiOperation("赠送记录") + @GetMapping("getGiveRecordList") + public Result getGiveRecordList(Integer page, Integer limit,String startTime,String endTime, TicketsGiveRecord giveRecord){ + return Result.success().put("data", giveRecordService.getGiveRecordList(page,limit,startTime,endTime,giveRecord)); + } +} + diff --git a/src/main/java/com/sqx/modules/ticketsGiveRecord/dao/TicketsGiveRecordDao.java b/src/main/java/com/sqx/modules/ticketsGiveRecord/dao/TicketsGiveRecordDao.java new file mode 100644 index 0000000..d537299 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsGiveRecord/dao/TicketsGiveRecordDao.java @@ -0,0 +1,22 @@ +package com.sqx.modules.ticketsGiveRecord.dao; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.ticketsGiveRecord.entity.TicketsGiveRecord; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + *

+ * Mapper 接口 + *

+ * + * @author www.javacoder.top + * @since 2022-11-23 + */ +@Mapper +public interface TicketsGiveRecordDao extends BaseMapper { + + IPage getGiveRecordList(@Param("pages") Page pages, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("giveRecord") TicketsGiveRecord giveRecord); +} diff --git a/src/main/java/com/sqx/modules/ticketsGiveRecord/entity/TicketsGiveRecord.java b/src/main/java/com/sqx/modules/ticketsGiveRecord/entity/TicketsGiveRecord.java new file mode 100644 index 0000000..235c57f --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsGiveRecord/entity/TicketsGiveRecord.java @@ -0,0 +1,58 @@ +package com.sqx.modules.ticketsGiveRecord.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.time.LocalDateTime; +import java.io.Serializable; +import java.util.Date; + +/** + *

+ * + *

+ * + * @author www.javacoder.top + * @since 2022-11-23 + */ +@Data +public class TicketsGiveRecord implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 记录id + */ + @TableId(value = "record_id", type = IdType.AUTO) + private Long recordId; + + /** + * 用户id + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userName; + + /** + * 水票id + */ + private Long ticketsId; + /** + * 水票标题 + */ + private String ticketsTitle; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 赠送数量 + */ + private Integer giveNum; +} diff --git a/src/main/java/com/sqx/modules/ticketsGiveRecord/service/TicketsGiveRecordService.java b/src/main/java/com/sqx/modules/ticketsGiveRecord/service/TicketsGiveRecordService.java new file mode 100644 index 0000000..e8ea5c0 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsGiveRecord/service/TicketsGiveRecordService.java @@ -0,0 +1,18 @@ +package com.sqx.modules.ticketsGiveRecord.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.modules.ticketsGiveRecord.entity.TicketsGiveRecord; +import com.baomidou.mybatisplus.extension.service.IService; + +/** + *

+ * 服务类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-23 + */ +public interface TicketsGiveRecordService extends IService { + + IPage getGiveRecordList(Integer page, Integer limit,String startTime,String endTime, TicketsGiveRecord giveRecord); +} diff --git a/src/main/java/com/sqx/modules/ticketsGiveRecord/service/impl/TicketsGiveRecordServiceImpl.java b/src/main/java/com/sqx/modules/ticketsGiveRecord/service/impl/TicketsGiveRecordServiceImpl.java new file mode 100644 index 0000000..1ad3943 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsGiveRecord/service/impl/TicketsGiveRecordServiceImpl.java @@ -0,0 +1,39 @@ +package com.sqx.modules.ticketsGiveRecord.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.ticketsGiveRecord.entity.TicketsGiveRecord; +import com.sqx.modules.ticketsGiveRecord.dao.TicketsGiveRecordDao; +import com.sqx.modules.ticketsGiveRecord.service.TicketsGiveRecordService; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + *

+ * 服务实现类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-23 + */ +@Service +public class TicketsGiveRecordServiceImpl extends ServiceImpl implements TicketsGiveRecordService { + + @Autowired + private TicketsGiveRecordDao giveRecordDao; + + @Override + public IPage getGiveRecordList(Integer page, Integer limit,String startTime,String endTime, TicketsGiveRecord giveRecord) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + + return giveRecordDao.getGiveRecordList(pages,startTime,endTime,giveRecord); + } +} diff --git a/src/main/java/com/sqx/modules/ticketsUserRole/controller/AdminTicketsUserRoleController.java b/src/main/java/com/sqx/modules/ticketsUserRole/controller/AdminTicketsUserRoleController.java new file mode 100644 index 0000000..de7b748 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsUserRole/controller/AdminTicketsUserRoleController.java @@ -0,0 +1,51 @@ +package com.sqx.modules.ticketsUserRole.controller; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import com.sqx.modules.ticketsUserRole.service.TicketsUserRoleService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + *

+ * 前端控制器 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@RestController +@Api(value = "水票用户关联", tags = {"水票用户关联-用户端"}) +@RequestMapping("/admin/ticketsUserRole/") +public class AdminTicketsUserRoleController { + @Autowired + private TicketsUserRoleService userRoleService; + + @ApiOperation("获取指定用户的水票列表") + @GetMapping("getMyTicketsList") + public Result getMyTicketsList( Long userId, Integer page, Integer limit, TicketsUserRole userRole) { + userRole.setUserId(userId); + return Result.success().put("data", userRoleService.getMyTicketsList(page, limit, userRole)); + } + + @ApiOperation("赠送用户水票") + @PostMapping("giveUserTickets") + public Result giveUserTickets(String userIds,Long ticketsId,Integer num){ + return userRoleService.giveUserTickets(userIds,ticketsId,num); + } + @ApiOperation("修改用户水票") + @PostMapping("updateUserTicket") + public Result updateUserTicket(Long userId,Integer num,Integer type,Long roleId){ + return userRoleService.updateUserTicket(userId,num,type,roleId); + } + @ApiOperation("水票统计") + @GetMapping("getTicketSum") + public Result getTicketSum(){ + return Result.success().put("data", userRoleService.getTicketSum()); + } +} + diff --git a/src/main/java/com/sqx/modules/ticketsUserRole/controller/TicketsUserRoleController.java b/src/main/java/com/sqx/modules/ticketsUserRole/controller/TicketsUserRoleController.java new file mode 100644 index 0000000..c0e5852 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsUserRole/controller/TicketsUserRoleController.java @@ -0,0 +1,41 @@ +package com.sqx.modules.ticketsUserRole.controller; + + +import com.sqx.common.utils.Result; +import com.sqx.modules.app.annotation.Login; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import com.sqx.modules.ticketsUserRole.service.TicketsUserRoleService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; + +import org.springframework.web.bind.annotation.RestController; + +/** + *

+ * 前端控制器 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@RestController +@Api(value = "水票用户关联", tags = {"水票用户关联-用户端"}) +@RequestMapping("/app/ticketsUserRole/") +public class TicketsUserRoleController { + @Autowired + private TicketsUserRoleService userRoleService; + + @Login + @ApiOperation("获取我的水票列表") + @GetMapping("getMyTicketsList") + public Result getMyTicketsList(@RequestAttribute("userId") Long userId, Integer page, Integer limit, TicketsUserRole userRole) { + userRole.setUserId(userId); + return Result.success().put("data", userRoleService.getMyTicketsList(page, limit, userRole)); + } +} + diff --git a/src/main/java/com/sqx/modules/ticketsUserRole/dao/TicketsUserRoleDao.java b/src/main/java/com/sqx/modules/ticketsUserRole/dao/TicketsUserRoleDao.java new file mode 100644 index 0000000..2827681 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsUserRole/dao/TicketsUserRoleDao.java @@ -0,0 +1,25 @@ +package com.sqx.modules.ticketsUserRole.dao; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +/** + *

+ * Mapper 接口 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@Mapper +public interface TicketsUserRoleDao extends BaseMapper { + + IPage getMyTicketsList(@Param("pages") Page pages, @Param("userRole") TicketsUserRole userRole); + + Integer getTicketSum(int type); +} diff --git a/src/main/java/com/sqx/modules/ticketsUserRole/entity/TicketsUserRole.java b/src/main/java/com/sqx/modules/ticketsUserRole/entity/TicketsUserRole.java new file mode 100644 index 0000000..ca977da --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsUserRole/entity/TicketsUserRole.java @@ -0,0 +1,76 @@ +package com.sqx.modules.ticketsUserRole.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.sqx.modules.tickets.entity.Tickets; +import lombok.Data; + +import java.time.LocalDateTime; +import java.io.Serializable; +import java.util.Date; + +/** + *

+ * + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@Data +public class TicketsUserRole implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 关联id + */ + @TableId(value = "role_id", type = IdType.AUTO) + private Long roleId; + + /** + * 用户id + */ + private Long userId; + + /** + * 水票id + */ + private Long ticketsId; + + /** + * 创建时间 + */ + private Date createTime; + /** + * 购买数量 + */ + private Integer stock; + /** + * 已用数量 + */ + private Integer num; + + /** + * 水票标题 + */ + @TableField(exist = false) + private String title; + /** + * 关联的商品id + */ + @TableField(exist = false) + private Long relationId; + /** + * 水票图片 + */ + @TableField(exist = false) + private String ticketsImg; + + /** + * 关联的商品名称 + */ + @TableField(exist = false) + private String relationName; +} diff --git a/src/main/java/com/sqx/modules/ticketsUserRole/service/TicketsUserRoleService.java b/src/main/java/com/sqx/modules/ticketsUserRole/service/TicketsUserRoleService.java new file mode 100644 index 0000000..07c6c94 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsUserRole/service/TicketsUserRoleService.java @@ -0,0 +1,28 @@ +package com.sqx.modules.ticketsUserRole.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.sqx.common.utils.Result; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import com.baomidou.mybatisplus.extension.service.IService; +import org.apache.shiro.crypto.hash.Hash; + +import java.util.HashMap; + +/** + *

+ * 服务类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +public interface TicketsUserRoleService extends IService { + + IPage getMyTicketsList(Integer page, Integer limit, TicketsUserRole userRole); + + Result giveUserTickets(String userIds, Long ticketsId, Integer num); + + Result updateUserTicket(Long userId, Integer num, Integer type, Long roleId); + + HashMap getTicketSum(); +} diff --git a/src/main/java/com/sqx/modules/ticketsUserRole/service/impl/TicketsUserRoleServiceImpl.java b/src/main/java/com/sqx/modules/ticketsUserRole/service/impl/TicketsUserRoleServiceImpl.java new file mode 100644 index 0000000..6062673 --- /dev/null +++ b/src/main/java/com/sqx/modules/ticketsUserRole/service/impl/TicketsUserRoleServiceImpl.java @@ -0,0 +1,166 @@ +package com.sqx.modules.ticketsUserRole.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.sqx.common.utils.Result; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserMoneyDetails; +import com.sqx.modules.app.service.UserMoneyDetailsService; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.tickets.entity.Tickets; +import com.sqx.modules.tickets.service.TicketsService; +import com.sqx.modules.ticketsGiveRecord.entity.TicketsGiveRecord; +import com.sqx.modules.ticketsGiveRecord.service.TicketsGiveRecordService; +import com.sqx.modules.ticketsUserRole.entity.TicketsUserRole; +import com.sqx.modules.ticketsUserRole.dao.TicketsUserRoleDao; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.sqx.modules.ticketsUserRole.service.TicketsUserRoleService; +import jodd.util.StringUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; + +/** + *

+ * 服务实现类 + *

+ * + * @author www.javacoder.top + * @since 2022-11-16 + */ +@Service +public class TicketsUserRoleServiceImpl extends ServiceImpl implements TicketsUserRoleService { + @Autowired + private TicketsUserRoleDao userRoleDao; + @Autowired + private TicketsService ticketsService; + @Autowired + private MessageService messageService; + @Autowired + private UserService userService; + @Autowired + private TicketsGiveRecordService giveRecordService; + @Autowired + private UserMoneyDetailsService detailsService; + + @Override + public IPage getMyTicketsList(Integer page, Integer limit, TicketsUserRole userRole) { + Page pages; + if (page != null && limit != null) { + pages = new Page<>(page, limit); + } else { + pages = new Page<>(); + pages.setSize(-1); + } + + return userRoleDao.getMyTicketsList(pages, userRole); + } + + @Override + public Result giveUserTickets(String userIds, Long ticketsId, Integer num) { + Tickets tickets = ticketsService.getById(ticketsId); + if (tickets == null) { + return Result.error("选中的水票不存在"); + } + String[] split = userIds.split(","); + for (String userId : split) { + UserEntity userEntity = userService.getById(userId); + if (userEntity == null) { + return Result.error("请先选择用户"); + } + TicketsUserRole ticketsUserRole = userRoleDao.selectOne(new QueryWrapper().eq("user_id", userId).eq("tickets_id", ticketsId)); + TicketsUserRole userRole = new TicketsUserRole(); + userRole.setUserId(Long.valueOf(userId)); + if (ticketsUserRole == null) { + userRole.setTicketsId(ticketsId); + userRole.setStock(tickets.getNum() * num); + userRole.setCreateTime(new Date()); + userRole.setNum(0); + userRoleDao.insert(userRole); + } else { + userRole.setStock(ticketsUserRole.getStock() + tickets.getNum() * num); + userRole.setRoleId(ticketsUserRole.getRoleId()); + userRoleDao.updateById(userRole); + } + + + //添加赠送记录 + + TicketsGiveRecord record = new TicketsGiveRecord(); + record.setGiveNum(tickets.getNum() * num); + record.setUserId(Long.valueOf(userId)); + record.setUserName(userEntity.getUserName()); + record.setTicketsId(ticketsId); + record.setCreateTime(new Date()); + record.setTicketsTitle(tickets.getTitle()); + giveRecordService.save(record); + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setContent("系统赠送您水票【" + tickets.getTitle() + "】共" + tickets.getNum() * num + "张"); + messageInfo.setTitle("系统赠送水票通知"); + messageInfo.setState(String.valueOf(5)); + messageInfo.setUserName(userEntity.getUserName()); + messageInfo.setUserId(userId); + messageInfo.setCreateAt(new SimpleDateFormat().format(new Date())); + messageInfo.setIsSee("0"); + messageService.saveBody(messageInfo); + if (StringUtil.isNotBlank(userEntity.getClientid())) { + userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid()); + } + } + return Result.success(); + + } + + @Override + public Result updateUserTicket(Long userId, Integer num, Integer type, Long roleId) { + TicketsUserRole ticketsUserRole = baseMapper.selectById(roleId); + if (ticketsUserRole == null) { + return Result.error("用户没有当前水票的库存记录"); + } + Tickets tickets = ticketsService.getById(ticketsUserRole.getTicketsId()); + if (tickets.getIsEnable() == 0) { + return Result.error("当前水票未启用"); + } + UserEntity userEntity = userService.getById(userId); + if (userEntity == null) { + return Result.error("用户不存在"); + } + Integer stock = ticketsUserRole.getStock(); + if (type == 1) { + ticketsUserRole.setStock(stock + num); + } else { + if (stock < num) { + return Result.error("当前用户数量不足!"); + } + ticketsUserRole.setStock(stock - num); + } + baseMapper.updateById(ticketsUserRole); + return Result.success(); + + + } + + @Override + public HashMap getTicketSum() { + + HashMap hashMap = new HashMap<>(); + //全部出售数量 + Integer allNum = baseMapper.getTicketSum(1); + //已使用 + Integer useNum = baseMapper.getTicketSum(2); + //未使用 + Integer notUseNum = baseMapper.getTicketSum(3); + hashMap.put("allNum",allNum); + hashMap.put("useNum",useNum); + hashMap.put("notUseNum",notUseNum); + return hashMap; + } + +} diff --git a/src/main/java/com/sqx/modules/timedtask/AutoSendOrder.java b/src/main/java/com/sqx/modules/timedtask/AutoSendOrder.java new file mode 100644 index 0000000..57700d3 --- /dev/null +++ b/src/main/java/com/sqx/modules/timedtask/AutoSendOrder.java @@ -0,0 +1,102 @@ +package com.sqx.modules.timedtask; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.sqx.common.utils.DateUtils; +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.entity.UserVip; +import com.sqx.modules.app.service.UserService; +import com.sqx.modules.app.service.UserVipService; +import com.sqx.modules.common.entity.CommonInfo; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.message.entity.MessageInfo; +import com.sqx.modules.message.service.MessageService; +import com.sqx.modules.orders.entity.Orders; +import com.sqx.modules.orders.service.OrdersService; +import com.sqx.modules.taking.entity.OrderTaking; +import com.sqx.modules.taking.service.OrderTakingService; +import com.sqx.modules.utils.SenInfoCheckUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Component +@Slf4j +public class AutoSendOrder { + @Autowired + private UserVipService userVipService; + @Autowired + private OrdersService ordersService; + @Autowired + private CommonInfoService commonInfoService; + @Autowired + private OrderTakingService orderTakingService; + @Autowired + private UserService userService; + @Autowired + private MessageService messageService; + + @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai") + public void userVipCheck() { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + List userVipList = userVipService.list(new QueryWrapper().eq("is_vip", 1)); + for (UserVip userVip : userVipList) { + if (LocalDateTime.now().isAfter(LocalDateTime.parse(userVip.getEndTime(), fmt))) { + userVip.setIsVip(2); + userVipService.updateById(userVip); + } + } + } + + /** + * 新订单消息推送 + */ + @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai") + public void orderSendMsg() { + List list = ordersService.list(new QueryWrapper().eq("is_push_meg", 0).eq("state", 4)); + for (Orders orders : list) { + List userEntityList = userService.selectShopUserByDistance(orders.getLaundryId()); + for (UserEntity user : userEntityList) { + OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId()); + //小程序订阅号消息推送 + CommonInfo one = commonInfoService.findOne(312); + List msgList = new ArrayList<>(); + msgList.add(orders.getOrdersNo());//订单号 + if (orderTaking.getServiceName().length() > 15) { + orderTaking.setServiceName(orderTaking.getServiceName().substring(0, 15) + "..."); + } + msgList.add(orderTaking.getServiceName());//商品名称 + String address = orders.getProvince() + orders.getCity() + orders.getDistrict() + orders.getDetailsAddress(); + if (address.length() > 15) { + address = address.substring(0, 15) + "..."; + } + msgList.add(address); + msgList.add(orders.getCreateTime());//下单时间 + msgList.add("生意来了,立即去接单>"); + if (StringUtils.isNotEmpty(user.getShopOpenId())) { + SenInfoCheckUtil.sendShopMsg(user.getShopOpenId(), one.getValue(), null, msgList, 2); + } + MessageInfo messageInfo = new MessageInfo(); + messageInfo.setUserId(user.getUserId().toString()); + messageInfo.setIsSee("0"); + messageInfo.setState("6"); + messageInfo.setContent("新订单通知"); + messageInfo.setCreateAt(DateUtils.format(new Date())); + messageService.save(messageInfo); + + + } + Orders order = new Orders(); + order.setOrdersId(orders.getOrdersId()); + order.setIsPushMeg(1); + ordersService.updateById(order); + } + } +} diff --git a/src/main/java/com/sqx/modules/utils/AliPayOrderUtil.java b/src/main/java/com/sqx/modules/utils/AliPayOrderUtil.java new file mode 100644 index 0000000..b912695 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/AliPayOrderUtil.java @@ -0,0 +1,133 @@ +package com.sqx.modules.utils; + +import javax.servlet.http.HttpServletRequest; +import java.text.SimpleDateFormat; +import java.util.*; + +public class AliPayOrderUtil { + + /** + * 将request中的参数转换成Map + * + * @param request + * @return + */ + public static Map convertRequestParamsToMap(HttpServletRequest request) { + Map retMap = new HashMap<>(); + Set> entrySet = request.getParameterMap().entrySet(); + for (Map.Entry entry : entrySet) { + String name = entry.getKey(); + String[] values = entry.getValue(); + int valLen = values.length; + if (valLen == 1) { + retMap.put(name, values[0]); + } else if (valLen > 1) { + StringBuilder sb = new StringBuilder(); + for (String val : values) { + sb.append(",").append(val); + } + retMap.put(name, sb.toString().substring(1)); + } else { + retMap.put(name, ""); + } + } + return retMap; + } + + + + /** + * 计算两个经纬度之间的距离 + * @param lat1 + * @param lng1 + * @param lat2 + * @param lng2 + * @return + */ + + + private static double EARTH_RADIUS = 6371.393; + private static double rad(double d) + { + return d * Math.PI / 180.0; + } + + + /** + * 生成随机订单编号 + * @return + */ + public static String createOrderId() { + int machineId = 1;//最大支持1-9个集群机器部署 + int hashCodeV = UUID.randomUUID().toString().hashCode(); + if(hashCodeV < 0) {//有可能是负数 + hashCodeV = - hashCodeV; + } + // 0 代表前面补充0 + // 4 代表长度为4 + // d 代表参数为正数型 + return machineId+String.format("%015d", hashCodeV); + } + + + + /** + * 获取当前日期是星期几
+ * + * @param date + * @return 当前日期是星期几 + */ + public static String getWeekOfDate(Date date) { + String[] weekDays = { "日", "一", "二", "三", "四", "五", "六" }; + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int w = cal.get(Calendar.DAY_OF_WEEK) - 1; + if (w < 0) + w = 0; + return weekDays[w]; + } + + /** + * 获取当前日期是星期几
+ * + * @param date + * @return 当前日期是星期几 + */ + public static String getWeekOfDates(Date date) { + String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int w = cal.get(Calendar.DAY_OF_WEEK) - 1; + if (w < 0) + w = 0; + return weekDays[w]; + } + + + /** + * 获取最近一周的时间 + * + * @param date + * @return 返回起始时间 + */ + public static String getStartTime(Date date) { + String weekOfDate = getWeekOfDate(date); + Integer day=0; + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + switch (weekOfDate){ + case "日": day=6;break; + case "一": day=0;break; + case "二": day=1;break; + case "三": day=2;break; + case "四": day=3;break; + case "五": day=4;break; + case "六": day=5;break; + } + Calendar cal=Calendar.getInstance(); + if(!day.equals(0)){ + cal.add(Calendar.DATE,-day); + } + return sdf.format(cal.getTime()); + } + +} diff --git a/src/main/java/com/sqx/modules/utils/AmountCalUtils.java b/src/main/java/com/sqx/modules/utils/AmountCalUtils.java new file mode 100644 index 0000000..e6ec16c --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/AmountCalUtils.java @@ -0,0 +1,76 @@ +package com.sqx.modules.utils; + + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; + +/** + * 金额计算工具类 + * @author fang + * @date 2020-04-17 + */ +public class AmountCalUtils { + + + //金额计算 加法 + public static BigDecimal add(BigDecimal b1,BigDecimal b2){ + return b1.add(b2); + } + + //金额计算 减法 + public static BigDecimal sub(BigDecimal n1, BigDecimal n2) { + formater.setMaximumFractionDigits(2); + formater.setGroupingSize(0); + formater.setRoundingMode(RoundingMode.FLOOR); + double v = n1.subtract(n2).doubleValue(); + return new BigDecimal(formater.format(v)); + } + + //金额计算 乘法 + public static Double mul(double v1, double v2) { + BigDecimal n1 = new BigDecimal(Double.toString(v1)); + BigDecimal n2 = new BigDecimal(Double.toString(v2)); + return n1.multiply(n2).doubleValue(); + } + + //金额计算 乘法 + public static BigDecimal mulMoney(BigDecimal n1, BigDecimal n2) { + formater.setMaximumFractionDigits(2); + formater.setGroupingSize(0); + formater.setRoundingMode(RoundingMode.FLOOR); + BigDecimal multiply = n1.multiply(n2); + return new BigDecimal(formater.format(multiply)); + } + + //金额计算 除法 + public static Double divide(double v1, double v2) { + BigDecimal n1 = new BigDecimal(Double.toString(v1)); + BigDecimal n2 = new BigDecimal(Double.toString(v2)); + return n1.divide(n2, 10, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + private final static DecimalFormat formater = new DecimalFormat(); + + //金额计算除法,保留小数点后两位 + public static Double moneyDivide(BigDecimal n1, BigDecimal n2){ + BigDecimal v = n1.divide(n2, 10, BigDecimal.ROUND_HALF_UP); + System.out.println(v); + formater.setMaximumFractionDigits(2); + formater.setGroupingSize(0); + formater.setRoundingMode(RoundingMode.FLOOR); + return Double.parseDouble(formater.format(v)); + } + + public static Double moneyDivides(BigDecimal n1, BigDecimal n2){ + BigDecimal v = n1.divide(n2, 10, BigDecimal.ROUND_HALF_UP); + System.out.println(v); + formater.setMaximumFractionDigits(2); + formater.setGroupingSize(0); + formater.setRoundingMode(RoundingMode.FLOOR); + return Double.parseDouble(formater.format(v)); + } + + + +} diff --git a/src/main/java/com/sqx/modules/utils/Base64Utils.java b/src/main/java/com/sqx/modules/utils/Base64Utils.java new file mode 100644 index 0000000..db5cd80 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/Base64Utils.java @@ -0,0 +1,313 @@ +package com.sqx.modules.utils; + + +import java.io.*; + +public class Base64Utils { + public Base64Utils() { + } + + /** + * 功能:编码字符串 + * + * @author jiangshuai + * @date 2016年10月03日 + * @param data + * 源字符串 + * @return String + */ + public static String encode(String data) { + return encode(data.getBytes()); + } + + /** + * 功能:解码字符串 + * + * @author jiangshuai + * @date 2016年10月03日 + * @param data + * 源字符串 + * @return String + */ + public static String decode(String data) { + return new String(decode(data.toCharArray())); + } + + + + /** + * 功能:编码byte[] + * + * @author jiangshuai + * @date 2016年10月03日 + * @param data + * 源 + * @return char[] + */ + public static String encode(byte[] data) { + char[] out = new char[((data.length + 2) / 3) * 4]; + for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { + boolean quad = false; + boolean trip = false; + + int val = (0xFF & (int) data[i]); + val <<= 8; + if ((i + 1) < data.length) { + val |= (0xFF & (int) data[i + 1]); + trip = true; + } + val <<= 8; + if ((i + 2) < data.length) { + val |= (0xFF & (int) data[i + 2]); + quad = true; + } + out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; + val >>= 6; + out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; + val >>= 6; + out[index + 1] = alphabet[val & 0x3F]; + val >>= 6; + out[index + 0] = alphabet[val & 0x3F]; + } + return new String(out); + } + + /** + * 功能:解码 + * + * @author jiangshuai + * @date 2016年10月03日 + * @param data + * 编码后的字符数组 + * @return byte[] + */ + public static byte[] decode(char[] data) { + + int tempLen = data.length; + for (int ix = 0; ix < data.length; ix++) { + if ((data[ix] > 255) || codes[data[ix]] < 0) { + --tempLen; // ignore non-valid chars and padding + } + } + // calculate required length: + // -- 3 bytes for every 4 valid base64 chars + // -- plus 2 bytes if there are 3 extra base64 chars, + // or plus 1 byte if there are 2 extra. + + int len = (tempLen / 4) * 3; + if ((tempLen % 4) == 3) { + len += 2; + } + if ((tempLen % 4) == 2) { + len += 1; + + } + byte[] out = new byte[len]; + + int shift = 0; // # of excess bits stored in accum + int accum = 0; // excess bits + int index = 0; + + // we now go through the entire array (NOT using the 'tempLen' value) + for (int ix = 0; ix < data.length; ix++) { + int value = (data[ix] > 255) ? -1 : codes[data[ix]]; + + if (value >= 0) { // skip over non-code + accum <<= 6; // bits shift up by 6 each time thru + shift += 6; // loop, with new bits being put in + accum |= value; // at the bottom. + if (shift >= 8) { // whenever there are 8 or more shifted in, + shift -= 8; // write them out (from the top, leaving any + out[index++] = // excess at the bottom for next iteration. + (byte) ((accum >> shift) & 0xff); + } + } + } + + // if there is STILL something wrong we just have to throw up now! + if (index != out.length) { + throw new Error("Miscalculated data length (wrote " + index + + " instead of " + out.length + ")"); + } + + return out; + } + + /** + * 功能:编码文件 + * + * @author jiangshuai + * @date 2016年10月03日 + * @param file + * 源文件 + */ + public static void encode(File file) throws IOException { + if (!file.exists()) { + System.exit(0); + } + + else { + byte[] decoded = readBytes(file); + String encoded = encode(decoded); + writeChars(file, encoded.toCharArray()); + } + file = null; + } + + /** + * 功能:解码文件。 + * + * @author jiangshuai + * @date 2016年10月03日 + * @param file + * 源文件 + * @throws IOException + */ + public static void decode(File file) throws IOException { + if (!file.exists()) { + System.exit(0); + } else { + char[] encoded = readChars(file); + byte[] decoded = decode(encoded); + writeBytes(file, decoded); + } + file = null; + } + + // + // code characters for values 0..63 + // + private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" + .toCharArray(); + + // + // lookup table for converting base64 characters to value in range 0..63 + // + private static byte[] codes = new byte[256]; + static { + for (int i = 0; i < 256; i++) { + codes[i] = -1; + // LoggerUtil.debug(i + "&" + codes[i] + " "); + } + for (int i = 'A'; i <= 'Z'; i++) { + codes[i] = (byte) (i - 'A'); + // LoggerUtil.debug(i + "&" + codes[i] + " "); + } + + for (int i = 'a'; i <= 'z'; i++) { + codes[i] = (byte) (26 + i - 'a'); + // LoggerUtil.debug(i + "&" + codes[i] + " "); + } + for (int i = '0'; i <= '9'; i++) { + codes[i] = (byte) (52 + i - '0'); + // LoggerUtil.debug(i + "&" + codes[i] + " "); + } + codes['+'] = 62; + codes['/'] = 63; + } + + private static byte[] readBytes(File file) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] b = null; + InputStream fis = null; + InputStream is = null; + try { + fis = new FileInputStream(file); + is = new BufferedInputStream(fis); + int count = 0; + byte[] buf = new byte[16384]; + while ((count = is.read(buf)) != -1) { + if (count > 0) { + baos.write(buf, 0, count); + } + } + b = baos.toByteArray(); + + } finally { + try { + if (fis != null) + fis.close(); + if (is != null) + is.close(); + if (baos != null) + baos.close(); + } catch (Exception e) { + System.out.println(e); + } + } + + return b; + } + + private static char[] readChars(File file) throws IOException { + CharArrayWriter caw = new CharArrayWriter(); + Reader fr = null; + Reader in = null; + try { + fr = new FileReader(file); + in = new BufferedReader(fr); + int count = 0; + char[] buf = new char[16384]; + while ((count = in.read(buf)) != -1) { + if (count > 0) { + caw.write(buf, 0, count); + } + } + + } finally { + try { + if (caw != null) + caw.close(); + if (in != null) + in.close(); + if (fr != null) + fr.close(); + } catch (Exception e) { + System.out.println(e); + } + } + + return caw.toCharArray(); + } + + private static void writeBytes(File file, byte[] data) throws IOException { + OutputStream fos = null; + OutputStream os = null; + try { + fos = new FileOutputStream(file); + os = new BufferedOutputStream(fos); + os.write(data); + + } finally { + try { + if (os != null) + os.close(); + if (fos != null) + fos.close(); + } catch (Exception e) { + System.out.println(e); + } + } + } + + private static void writeChars(File file, char[] data) throws IOException { + Writer fos = null; + Writer os = null; + try { + fos = new FileWriter(file); + os = new BufferedWriter(fos); + os.write(data); + + } finally { + try { + if (os != null) + os.close(); + if (fos != null) + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + +} diff --git a/src/main/java/com/sqx/modules/utils/CertificateUtils.java b/src/main/java/com/sqx/modules/utils/CertificateUtils.java new file mode 100644 index 0000000..48474e3 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/CertificateUtils.java @@ -0,0 +1,892 @@ +package com.sqx.modules.utils; + +import org.springframework.core.io.ClassPathResource; + +import javax.crypto.Cipher; +import java.io.*; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.Date; + +/** + *

+ * 数字签名/加密解密工具包 + *

+ */ +public class CertificateUtils { + + /** + * Java密钥库(Java 密钥库,JKS)KEY_STORE + */ + public static final String KEY_STORE = "JKS"; + + public static final String X509 = "X.509"; + + /** + * 文件读取缓冲区大小 + */ + private static final int CACHE_SIZE = 2048; + + /** + * 最大文件加密块 + */ + private static final int MAX_ENCRYPT_BLOCK = 117; + + /** + * 最大文件解密块 + */ + private static final int MAX_DECRYPT_BLOCK = 128; + + /** + *

+ * 根据密钥库获得私钥 + *

+ * + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + static PrivateKey getPrivateKey(String keyStorePath, String alias, String password) + throws Exception { + KeyStore keyStore = getKeyStore(keyStorePath, password); + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); + return privateKey; + } + + /** + *

+ * 获得密钥库 + *

+ * + * @param keyStorePath 密钥库存储路径 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + private static KeyStore getKeyStore(String keyStorePath, String password) + throws Exception { + //FileInputStream in = new FileInputStream(keyStorePath); + ClassPathResource classPathResource = new ClassPathResource("keystore/PTTEST17.keystore"); + InputStream certStream = classPathResource.getInputStream(); + KeyStore keyStore = KeyStore.getInstance(KEY_STORE); + keyStore.load(certStream, password.toCharArray()); + certStream.close(); + return keyStore; + } + + /** + *

+ * 根据证书获得公钥 + *

+ * + * @param certificatePath 证书存储路径 + * @return + * @throws Exception + */ + static PublicKey getPublicKey(String certificatePath) throws CertificateException, IOException { + Certificate certificate = getCertificate(certificatePath); + PublicKey publicKey = certificate.getPublicKey(); + return publicKey; + } + + /** + *

+ * 根据证书获得公钥 + *

+ * + * @param certificateInStream 证书输入流 + * @return + * @throws Exception + */ + static PublicKey getPublicKey(InputStream certificateInStream) throws CertificateException, IOException { + Certificate certificate = getCertificate(certificateInStream); + PublicKey publicKey = certificate.getPublicKey(); + return publicKey; + } + + /** + *

+ * 获得证书 + *

+ * + * @param certificatePath 证书存储路径 + * @return + * @throws Exception + */ + private static Certificate getCertificate(String certificatePath) throws CertificateException, IOException { + CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); + FileInputStream in = new FileInputStream(certificatePath); + Certificate certificate = certificateFactory.generateCertificate(in); + in.close(); + return certificate; + } + + /** + *

+ * 获得证书 + *

+ * + * @param certificateInStream 证书输入流 + * @return + * @throws Exception + */ + private static Certificate getCertificate(InputStream certificateInStream) throws CertificateException, IOException { + CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); + Certificate certificate = certificateFactory.generateCertificate(certificateInStream); + certificateInStream.close(); + return certificate; + } + + /** + *

+ * 根据密钥库获得证书 + *

+ * + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + private static Certificate getCertificate(String keyStorePath, String alias, String password) + throws Exception { + KeyStore keyStore = getKeyStore(keyStorePath, password); + Certificate certificate = keyStore.getCertificate(alias); + return certificate; + } + + /** + *

+ * 私钥加密 + *

+ * + * @param data 源数据 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + public static byte[] encryptByPrivateKey(byte[] data, String keyStorePath, String alias, String password) + throws Exception { + // 取得私钥 + PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password); + Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); + System.out.print("\n=========="+privateKey.getAlgorithm()+"\n=========="); + cipher.init(Cipher.ENCRYPT_MODE, privateKey); + int inputLen = data.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段加密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + byte[] encryptedData = out.toByteArray(); + out.close(); + return encryptedData; + } + + /** + *

+ * 文件私钥加密 + *

+ *

+ * 过大的文件可能会导致内存溢出 + * + * + * @param filePath 文件路径 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + public static byte[] encryptFileByPrivateKey(String filePath, String keyStorePath, String alias, String password) + throws Exception { + byte[] data = fileToByte(filePath); + return encryptByPrivateKey(data, keyStorePath, alias, password); + } + + /** + *

+ * 文件加密 + *

+ * + * @param srcFilePath 源文件 + * @param destFilePath 加密后文件 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @throws Exception + */ + public static void encryptFileByPrivateKey(String srcFilePath, String destFilePath, String keyStorePath, String alias, String password) + throws Exception { + // 取得私钥 + PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password); + Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); + cipher.init(Cipher.ENCRYPT_MODE, privateKey); + File srcFile = new File(srcFilePath); + FileInputStream in = new FileInputStream(srcFile); + File destFile = new File(destFilePath); + if (!destFile.getParentFile().exists()) { + destFile.getParentFile().mkdirs(); + } + destFile.createNewFile(); + OutputStream out = new FileOutputStream(destFile); + byte[] data = new byte[MAX_ENCRYPT_BLOCK]; + byte[] encryptedData; // 加密块 + while (in.read(data) != -1) { + encryptedData = cipher.doFinal(data); + out.write(encryptedData, 0, encryptedData.length); + out.flush(); + } + out.close(); + in.close(); + } + + /** + *

+ * 文件加密成BASE64编码的字符串 + *

+ * + * @param filePath 文件路径 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ +// public static String encryptFileToBase64ByPrivateKey(String filePath, String keyStorePath, String alias, String password) +// throws Exception { +// byte[] encryptedData = encryptFileByPrivateKey(filePath, keyStorePath, alias, password); +// return Base64Utils.encode(encryptedData); +// } + + /** + *

+ * 私钥解密 + *

+ * + * @param encryptedData 已加密数据 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + public static byte[] decryptByPrivateKey(byte[] encryptedData, String keyStorePath, String alias, String password) + throws Exception { + // 取得私钥 + PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password); + Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); + cipher.init(Cipher.DECRYPT_MODE, privateKey); + // 解密byte数组最大长度限制: 128 + int inputLen = encryptedData.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段解密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_DECRYPT_BLOCK) { + cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); + } else { + cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_DECRYPT_BLOCK; + } + byte[] decryptedData = out.toByteArray(); + out.close(); + return decryptedData; + } + + /** + *

+ * 公钥加密 + *

+ * + * @param data 源数据 + * @param certificatePath 证书存储路径 + * @return + * @throws Exception + */ + public static byte[] encryptByPublicKey(byte[] data, String certificatePath) + throws Exception { + // 取得公钥 + PublicKey publicKey = getPublicKey(certificatePath); + Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + int inputLen = data.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段加密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + byte[] encryptedData = out.toByteArray(); + out.close(); + return encryptedData; + } + + /** + *

+ * 公钥解密 + *

+ * + * @param encryptedData 已加密数据 + * @param certificatePath 证书存储路径 + * @return + * @throws Exception + */ + public static byte[] decryptByPublicKey(byte[] encryptedData, String certificatePath) + throws Exception { + PublicKey publicKey = getPublicKey(certificatePath); + Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); + cipher.init(Cipher.DECRYPT_MODE, publicKey); + int inputLen = encryptedData.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段解密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_DECRYPT_BLOCK) { + cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); + } else { + cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_DECRYPT_BLOCK; + } + byte[] decryptedData = out.toByteArray(); + out.close(); + return decryptedData; + } + + /** + *

+ * 文件解密 + *

+ * + * @param srcFilePath 源文件 + * @param destFilePath 目标文件 + * @param certificatePath 证书存储路径 + * @throws Exception + */ + public static void decryptFileByPublicKey(String srcFilePath, String destFilePath, String certificatePath) + throws Exception { + PublicKey publicKey = getPublicKey(certificatePath); + Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); + cipher.init(Cipher.DECRYPT_MODE, publicKey); + File srcFile = new File(srcFilePath); + FileInputStream in = new FileInputStream(srcFile); + File destFile = new File(destFilePath); + if (!destFile.getParentFile().exists()) { + destFile.getParentFile().mkdirs(); + } + destFile.createNewFile(); + OutputStream out = new FileOutputStream(destFile); + byte[] data = new byte[MAX_DECRYPT_BLOCK]; + byte[] decryptedData; // 解密块 + while (in.read(data) != -1) { + decryptedData = cipher.doFinal(data); + out.write(decryptedData, 0, decryptedData.length); + out.flush(); + } + out.close(); + in.close(); + } + + /** + *

+ * 生成数据签名 + *

+ * + * @param data 源数据 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + public static byte[] sign(byte[] data, String keyStorePath, String alias, String password) + throws Exception { + // 获得证书 + X509Certificate x509Certificate = (X509Certificate) getCertificate(keyStorePath, alias, password); + // 获取私钥 + KeyStore keyStore = getKeyStore(keyStorePath, password); + // 取得私钥 + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); + // 构建签名 + Signature signature = Signature.getInstance(x509Certificate.getSigAlgName()); + signature.initSign(privateKey); + signature.update(data); + return signature.sign(); + } + + /** + *

+ * 生成数据签名并以BASE64编码 + *

+ * + * @param data 源数据 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + public static String signToBase64(byte[] data, String keyStorePath, String alias, String password) + throws Exception { + return Base64.getEncoder().encodeToString(sign(data, keyStorePath, alias, password)); + } + + /** + *

+ * 生成文件数据签名(BASE64) + *

+ *

+ * 需要先将文件私钥加密,再根据加密后的数据生成签名(BASE64),适用于小文件 + *

+ * + * @param filePath 源文件 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + public static String signFileToBase64WithEncrypt(String filePath, String keyStorePath, String alias, String password) + throws Exception { + byte[] encryptedData = encryptFileByPrivateKey(filePath, keyStorePath, alias, password); + return signToBase64(encryptedData, keyStorePath, alias, password); + } + + /** + *

+ * 生成文件签名 + *

+ *

+ * 注意:
+ * 方法中使用了FileChannel,其巨大Bug就是不会释放文件句柄,导致签名的文件无法操作(移动或删除等)
+ * 该方法已被generateFileSign取代 + *

+ * + * @param filePath 文件路径 + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + * @throws Exception + */ + @Deprecated + public static byte[] signFile(String filePath, String keyStorePath, String alias, String password) + throws Exception { + byte[] sign = new byte[0]; + // 获得证书 + X509Certificate x509Certificate = (X509Certificate) getCertificate(keyStorePath, alias, password); + // 获取私钥 + KeyStore keyStore = getKeyStore(keyStorePath, password); + // 取得私钥 + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); + // 构建签名 + Signature signature = Signature.getInstance(x509Certificate.getSigAlgName()); + signature.initSign(privateKey); + File file = new File(filePath); + if (file.exists()) { + FileInputStream in = new FileInputStream(file); + FileChannel fileChannel = in.getChannel(); + MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); + signature.update(byteBuffer); + fileChannel.close(); + in.close(); + sign = signature.sign(); + } + return sign; + } + + /** + *

+ * 生成文件数字签名 + *

+ * + * @param filePath + * @param keyStorePath + * @param alias + * @param password + * @return + * @throws Exception + */ + public static byte[] generateFileSign(String filePath, String keyStorePath, String alias, String password) + throws Exception { + byte[] sign = new byte[0]; + // 获得证书 + X509Certificate x509Certificate = (X509Certificate) getCertificate(keyStorePath, alias, password); + // 获取私钥 + KeyStore keyStore = getKeyStore(keyStorePath, password); + // 取得私钥 + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); + // 构建签名 + Signature signature = Signature.getInstance(x509Certificate.getSigAlgName()); + signature.initSign(privateKey); + File file = new File(filePath); + if (file.exists()) { + FileInputStream in = new FileInputStream(file); + byte[] cache = new byte[CACHE_SIZE]; + int nRead = 0; + while ((nRead = in.read(cache)) != -1) { + signature.update(cache, 0, nRead); + } + in.close(); + sign = signature.sign(); + } + return sign; + + } + + /** + *

+ * 文件签名成BASE64编码字符串 + *

+ * + * @param filePath + * @param keyStorePath + * @param alias + * @param password + * @return + * @throws Exception + */ + public static String signFileToBase64(String filePath, String keyStorePath, String alias, String password) + throws Exception { + return Base64.getEncoder().encodeToString(generateFileSign(filePath, keyStorePath, alias, password)); + } + + /** + *

+ * 验证签名 + *

+ * + * @param data 已加密数据 + * @param sign 数据签名[BASE64] + * @param certificatePath 证书存储路径 + * @return + * @throws Exception + */ + public static boolean verifySign(byte[] data, String sign, String certificatePath) + throws Exception { + // 获得证书 + X509Certificate x509Certificate = (X509Certificate) getCertificate(certificatePath); + // 获得公钥 + PublicKey publicKey = x509Certificate.getPublicKey(); + // 构建签名 + Signature signature = Signature.getInstance(x509Certificate.getSigAlgName()); + signature.initVerify(publicKey); + signature.update(data); + return signature.verify(Base64.getDecoder().decode(sign)); + } + + /** + *

+ * 验证签名 + *

+ * + * @param data 已加密数据 + * @param sign 数据签名[BASE64] + * @param certificate 证书 + * @return + * @throws Exception + */ + public static boolean verifySign(byte[] data, String sign, byte[] certificate) + throws Exception { + // 获得证书 + X509Certificate x509Certificate = (X509Certificate) getCertificate(new ByteArrayInputStream(certificate)); + // 获得公钥 + PublicKey publicKey = x509Certificate.getPublicKey(); + // 构建签名 + Signature signature = Signature.getInstance(x509Certificate.getSigAlgName()); + signature.initVerify(publicKey); + signature.update(data); + return signature.verify(Base64.getDecoder().decode(sign)); + } + + /** + *

+ * 校验文件签名 + *

+ * + * @param filePath + * @param sign + * @param certificatePath + * @return + * @throws Exception + */ +// public static boolean validateFileSign(String filePath, String sign, String certificatePath) +// throws Exception { +// boolean result = false; +// // 获得证书 +// X509Certificate x509Certificate = (X509Certificate) getCertificate(certificatePath); +// // 获得公钥 +// PublicKey publicKey = x509Certificate.getPublicKey(); +//// System.out.print("测试私钥"); +//// System.out.print(publicKey); +//// System.out.print("测试私钥"); +//// System.out.print("\n"); +// +// // 构建签名 +// Signature signature = Signature.getInstance(x509Certificate.getSigAlgName()); +// signature.initVerify(publicKey); +// File file = new File(filePath); +// if (file.exists()) { +// byte[] decodedSign = Base64Utils.decode(sign); +// FileInputStream in = new FileInputStream(file); +// byte[] cache = new byte[CACHE_SIZE]; +// int nRead = 0; +// while ((nRead = in.read(cache)) != -1) { +// signature.update(cache, 0, nRead); +// } +// in.close(); +// result = signature.verify(decodedSign); +// } +// return result; +// } + + /** + *

+ * BASE64解码->签名校验 + *

+ * + * @param base64String BASE64编码字符串 + * @param sign 数据签名[BASE64] + * @param certificatePath 证书存储路径 + * @return + * @throws Exception + */ +// public static boolean verifyBase64Sign(String base64String, String sign, String certificatePath) +// throws Exception { +// byte[] data = Base64Utils.decode(base64String); +// return verifySign(data, sign, certificatePath); +// } + + /** + *

+ * BASE64解码->公钥解密-签名校验 + *

+ * + * + * @param base64String BASE64编码字符串 + * @param sign 数据签名[BASE64] + * @param certificatePath 证书存储路径 + * @return + * @throws Exception + */ +// public static boolean verifyBase64SignWithDecrypt(String base64String, String sign, String certificatePath) +// throws Exception { +// byte[] encryptedData = Base64Utils.decode(base64String); +// byte[] data = decryptByPublicKey(encryptedData, certificatePath); +// return verifySign(data, sign, certificatePath); +// } + + /** + *

+ * 文件公钥解密->签名校验 + *

+ * + * @param encryptedFilePath 加密文件路径 + * @param sign 数字证书[BASE64] + * @param certificatePath + * @return + * @throws Exception + */ +// public static boolean verifyFileSignWithDecrypt(String encryptedFilePath, String sign, String certificatePath) +// throws Exception { +// byte[] encryptedData = fileToByte(encryptedFilePath); +// byte[] data = decryptByPublicKey(encryptedData, certificatePath); +// return verifySign(data, sign, certificatePath); +// } + + /** + *

+ * 校验证书当前是否有效 + *

+ * + * @param certificate 证书 + * @return + */ + public static boolean verifyCertificate(Certificate certificate) { + return verifyCertificate(new Date(), certificate); + } + + /** + *

+ * 验证证书是否过期或无效 + *

+ * + * @param date 日期 + * @param certificate 证书 + * @return + */ + public static boolean verifyCertificate(Date date, Certificate certificate) { + boolean isValid = true; + try { + X509Certificate x509Certificate = (X509Certificate) certificate; + x509Certificate.checkValidity(date); + } catch (Exception e) { + isValid = false; + } + return isValid; + } + + /** + *

+ * 验证数字证书是在给定的日期是否有效 + *

+ * + * @param date 日期 + * @param certificatePath 证书存储路径 + * @return + */ + public static boolean verifyCertificate(Date date, String certificatePath) { + Certificate certificate; + try { + certificate = getCertificate(certificatePath); + return verifyCertificate(certificate); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + *

+ * 验证数字证书是在给定的日期是否有效 + *

+ * + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + */ + public static boolean verifyCertificate(Date date, String keyStorePath, String alias, String password) { + Certificate certificate; + try { + certificate = getCertificate(keyStorePath, alias, password); + return verifyCertificate(certificate); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + *

+ * 验证数字证书当前是否有效 + *

+ * + * @param keyStorePath 密钥库存储路径 + * @param alias 密钥库别名 + * @param password 密钥库密码 + * @return + */ + public static boolean verifyCertificate(String keyStorePath, String alias, String password) { + return verifyCertificate(new Date(), keyStorePath, alias, password); + } + + /** + *

+ * 验证数字证书当前是否有效 + *

+ * + * @param certificatePath 证书存储路径 + * @return + */ + public static boolean verifyCertificate(String certificatePath) { + return verifyCertificate(new Date(), certificatePath); + } + + /** + *

+ * 文件转换为byte数组 + *

+ * + * @param filePath 文件路径 + * @return + * @throws Exception + */ + public static byte[] fileToByte(String filePath) throws Exception { + byte[] data = new byte[0]; + File file = new File(filePath); + if (file.exists()) { + FileInputStream in = new FileInputStream(file); + ByteArrayOutputStream out = new ByteArrayOutputStream(2048); + byte[] cache = new byte[CACHE_SIZE]; + int nRead = 0; + while ((nRead = in.read(cache)) != -1) { + out.write(cache, 0, nRead); + out.flush(); + } + out.close(); + in.close(); + data = out.toByteArray(); + } + return data; + } + + /** + *

+ * 二进制数据写文件 + *

+ * + * @param bytes 二进制数据 + * @param filePath 文件生成目录 + */ + public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { + InputStream in = new ByteArrayInputStream(bytes); + File destFile = new File(filePath); + if (!destFile.getParentFile().exists()) { + destFile.getParentFile().mkdirs(); + } + destFile.createNewFile(); + OutputStream out = new FileOutputStream(destFile); + byte[] cache = new byte[CACHE_SIZE]; + int nRead = 0; + while ((nRead = in.read(cache)) != -1) { + out.write(cache, 0, nRead); + out.flush(); + } + out.close(); + in.close(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/CusAccessObjectUtil.java b/src/main/java/com/sqx/modules/utils/CusAccessObjectUtil.java new file mode 100644 index 0000000..b0bcb55 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/CusAccessObjectUtil.java @@ -0,0 +1,88 @@ +package com.sqx.modules.utils; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import org.apache.commons.lang3.StringUtils; + +import javax.servlet.http.HttpServletRequest; + +/** + * 获取对象的IP地址等信息 + * @author fang + * @date 2020/9/23 + */ +public class CusAccessObjectUtil { + + /** + * 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址, + * + * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢? + * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 + * + * 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, + * 192.168.1.100 + * + * 用户真实IP为: 192.168.1.110 + * + * @param request + * @return + */ + public static String getIpAddrs( HttpServletRequest request) + throws Exception { + if (request == null) { + throw (new Exception("getIpAddr method HttpServletRequest Object is null")); + } + String ipString = request.getHeader("x-forwarded-for"); + if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) { + ipString = request.getHeader("Proxy-Client-IP"); + } + if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) { + ipString = request.getHeader("WL-Proxy-Client-IP"); + } + if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) { + ipString = request.getRemoteAddr(); + } + + // 多个路由时,取第一个非unknown的ip + String[] arr = ipString.split(","); + for (String str : arr) { + if (!"unknown".equalsIgnoreCase(str)) { + ipString = str; + break; + } + } + + return ipString; + } + + public static String getAddress(String ip) { + String url = "http://ip.ws.126.net/ipquery?ip=" + ip; + String str = HttpClientUtil.doGet(url); + if(!StrUtil.hasBlank(str)){ + String substring = str.substring(str.indexOf("{"), str.indexOf("}")+1); + System.out.println(substring); + JSONObject jsonObject = JSONUtil.parseObj(substring); + String province = jsonObject.getStr("province"); + String city = jsonObject.getStr("city"); + return province+city; + } + return "未知"; + } + + + + +// // 测试 + public static void main(String[] args) { + String ip = "111.121.72.101"; + String address = getAddress(ip); + System.out.println(address); + } + + + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/EasyPoi/ExcelStyleUtil.java b/src/main/java/com/sqx/modules/utils/EasyPoi/ExcelStyleUtil.java new file mode 100644 index 0000000..0480ca7 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/EasyPoi/ExcelStyleUtil.java @@ -0,0 +1,180 @@ +package com.sqx.modules.utils.EasyPoi; + +import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity; +import cn.afterturn.easypoi.excel.entity.params.ExcelForEachParams; +import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler; +import org.apache.poi.ss.usermodel.*; + +public class ExcelStyleUtil implements IExcelExportStyler { + private static final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT"); + private static final short FONT_SIZE_TEN = 9; //字体大小 + private static final short FONT_SIZE_ELEVEN = 12;//列大小 + private static final short FONT_SIZE_TWELVE = 15;//大标题 + /** + * 大标题样式 + */ + private CellStyle headerStyle; + /** + * 每列标题样式 + */ + private CellStyle titleStyle; + /** + * 数据行样式 + */ + private CellStyle styles; + + public ExcelStyleUtil(Workbook workbook) { + this.init(workbook); + } + + /** + * 初始化样式 + * + * @param workbook + */ + private void init(Workbook workbook) { + this.headerStyle = initHeaderStyle(workbook); + this.titleStyle = initTitleStyle(workbook); + this.styles = initStyles(workbook); + } + + /** + * 大标题样式 + * + * @param color + * @return + */ + @Override + public CellStyle getHeaderStyle(short color) { + return headerStyle; + } + + /** + * 每列标题样式 + * + * @param color + * @return + */ + @Override + public CellStyle getTitleStyle(short color) { + return titleStyle; + } + + /** + * 数据行样式 (控制全部行的样式) + * + * @param parity 表示奇偶行 + * @param entity 数据内容 + * @return 样式 + */ + @Override + public CellStyle getStyles(boolean parity, ExcelExportEntity entity) { + return styles; + } + + /** + * 获取样式方法 + * + * @param dataRow 数据行 + * @param obj 对象 + * @param data 数据 + */ + @Override + public CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) { + return getStyles(true, entity); + } + + /** + * 模板使用的样式设置 + */ + @Override + public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) { + return null; + } + + /** + * 初始化--大标题样式 + * + * @param workbook + * @return + */ + private CellStyle initHeaderStyle(Workbook workbook) { + CellStyle style = getBaseCellStyle(workbook); + style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true)); + return style; + } + + /** + * 初始化--每列标题样式 + * + * @param workbook + * @return + */ + private CellStyle initTitleStyle(Workbook workbook) { + CellStyle style = getBaseCellStyle(workbook); + style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false)); + //背景色 +// style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); //灰色 +// style.setFillForegroundColor(IndexedColors.AQUA.getIndex()); //浅蓝色 + style.setFillForegroundColor(IndexedColors.SEA_GREEN.getIndex()); //海藻绿 + + + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + return style; + } + + /** + * 初始化--数据行样式 + * + * @param workbook + * @return + */ + private CellStyle initStyles(Workbook workbook) { + CellStyle style = getBaseCellStyle(workbook); + style.setFont(getFont(workbook, FONT_SIZE_TEN, false)); + style.setDataFormat(STRING_FORMAT); + return style; + } + + /** + * 基础样式 + * + * @return + */ + private CellStyle getBaseCellStyle(Workbook workbook) { + CellStyle style = workbook.createCellStyle(); + //下边框 + style.setBorderBottom(BorderStyle.THIN); + //左边框 + style.setBorderLeft(BorderStyle.THIN); + //上边框 + style.setBorderTop(BorderStyle.THIN); + //右边框 + style.setBorderRight(BorderStyle.THIN); + //水平居中 + style.setAlignment(HorizontalAlignment.CENTER); + //上下居中 + style.setVerticalAlignment(VerticalAlignment.CENTER); + //设置自动换行 + style.setWrapText(true); + return style; + } + + /** + * 字体样式 + * + * @param size 字体大小 + * @param isBold 是否加粗 + * @return + */ + private Font getFont(Workbook workbook, short size, boolean isBold) { + Font font = workbook.createFont(); + //字体样式 + font.setFontName("宋体"); + //是否加粗 + font.setBold(isBold); + //字体大小 + font.setFontHeightInPoints(size); + return font; + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/EasyPoi/ExcelUtils.java b/src/main/java/com/sqx/modules/utils/EasyPoi/ExcelUtils.java new file mode 100644 index 0000000..b4f2d01 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/EasyPoi/ExcelUtils.java @@ -0,0 +1,259 @@ +package com.sqx.modules.utils.EasyPoi; +import cn.afterturn.easypoi.excel.ExcelExportUtil; +import cn.afterturn.easypoi.excel.ExcelImportUtil; +import cn.afterturn.easypoi.excel.entity.ExportParams; +import cn.afterturn.easypoi.excel.entity.ImportParams; +import cn.afterturn.easypoi.excel.entity.TemplateExportParams; +import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; +import com.sqx.modules.app.entity.UserEntity; +import org.apache.commons.lang.StringUtils; +import org.apache.poi.ss.usermodel.Workbook; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.*; + +public class ExcelUtils { + + /** + * 允许导出的最大条数 + */ + private static final Integer EXPORT_EXCEL_MAX_NUM = 10000; + + + + /** + * excel 导出 (本地) + * @param list 数据列表 + * @param excelType HSSF, XSSF + * + */ + public static void exportExcel(File file, List list, ExcelType excelType) throws IOException { + FileOutputStream fos = new FileOutputStream(file); + Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null,file.getName(), excelType), + UserEntity.class, list); + + workbook.write(fos); + workbook.close(); + } + /** + * excel 导出 + * + * @param list 数据列表 + * @param fileName 导出时的excel名称 + * @param response + */ + public static void exportExcel(List> list, String fileName, ExcelType excelType, HttpServletResponse response) throws IOException { + defaultExport(list, fileName,excelType, response); + } + + /** + * 默认的 excel 导出 + * + * @param list 数据列表 + * @param fileName 导出时的excel名称 + * @param response + */ + private static void defaultExport(List> list, String fileName,ExcelType excelType, HttpServletResponse response) throws IOException { + + //把数据添加到excel表格中 + Workbook workbook = ExcelExportUtil.exportExcel(list, excelType); + downLoadExcel(fileName, response, workbook); + } + + /** + * excel 导出 + * + * @param list 数据列表 + * @param pojoClass pojo类型 + * @param fileName 导出时的excel名称 + * @param response + * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型) + */ + private static void defaultExport(List list, Class pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException { + //把数据添加到excel表格中 + Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); + downLoadExcel(fileName, response, workbook); + } + + /** + * excel 导出 + * + * @param list 数据列表 + * @param pojoClass pojo类型 + * @param fileName 导出时的excel名称 + * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型) + * @param response + */ + public static void exportExcel(List list, Class pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException { + defaultExport(list, pojoClass, fileName, response, exportParams); + } + + /** + * excel 导出 + * + * @param list 数据列表 + * @param title 表格内数据标题 + * @param sheetName sheet名称 + * @param pojoClass pojo类型 + * @param fileName 导出时的excel名称 + * @param response + */ + public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName, HttpServletResponse response) throws IOException { + //给文件名拼接上日期 + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = formatter.format(new Date()); + fileName = fileName + dateString; + //判断导出数据是否为空 + if (list == null) { + list = new ArrayList<>(); + } + //判断导出数据数量是否超过限定值 + if (list.size() > EXPORT_EXCEL_MAX_NUM) { + title = "导出数据行数超过:" + EXPORT_EXCEL_MAX_NUM + "条,无法导出、请添加导出条件!"; + list = new ArrayList<>(); + } + //获取导出参数 + ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF); + //设置导出样式 + exportParams.setStyle(ExcelStyleUtil.class); + //设置行高 + exportParams.setHeight((short) 6); + + + defaultExport(list, pojoClass, fileName, response, exportParams); + } + + + /** + * 根据模板生成excel后导出 + * + * @param templatePath 模板路径 + * @param map 数据集合 + * @param fileName 文件名 + * @param response + * @throws IOException + */ + public static void exportExcel(TemplateExportParams templatePath, Map map, String fileName, HttpServletResponse response) throws IOException { + Workbook workbook = ExcelExportUtil.exportExcel(templatePath, map); + downLoadExcel(fileName, response, workbook); + } + + + /** + * excel下载 + * + * @param fileName 下载时的文件名称 + * @param response + * @param workbook excel数据 + */ + private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException { + try { + response.setCharacterEncoding("UTF-8"); + response.setHeader("content-Type", "application/vnd.ms-excel"); + response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8")); + workbook.setForceFormulaRecalculation(true); //强制开启excel公式计算 + workbook.write(response.getOutputStream()); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + } + + + /** + * excel 导入 + * + * @param file excel文件 + * @param pojoClass pojo类型 + * @param + * @return + */ + public static List importExcel(MultipartFile file, Class pojoClass) throws IOException { + return importExcel(file, 1, 1, pojoClass); + } + + /** + * excel 导入 + * + * @param filePath excel文件路径 + * @param titleRows 表格内数据标题行 + * @param headerRows 表头行 + * @param pojoClass pojo类型 + * @param + * @return + */ + public static List importExcel(String filePath, Integer titleRows, Integer headerRows, Class pojoClass) throws IOException { + if (StringUtils.isBlank(filePath)) { + return null; + } + ImportParams params = new ImportParams(); + params.setTitleRows(titleRows); + params.setHeadRows(headerRows); + params.setNeedSave(true); + params.setSaveUrl("/excel/"); + try { + return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); + } catch (NoSuchElementException e) { + throw new IOException("模板不能为空"); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + } + + + /** + * excel 导入 + * + * @param file 上传的文件 + * @param titleRows 表格内数据标题行 + * @param headerRows 表头行 + * @param pojoClass pojo类型 + * @param + * @return + */ + public static List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass) throws IOException { + if (file == null) { + return null; + } + try { + return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + } + + /** + * excel 导入 + * + * @param inputStream 文件输入流 + * @param titleRows 表格内数据标题行 + * @param headerRows 表头行 + * @param pojoClass pojo类型 + * @param + * @return + */ + public static List importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class pojoClass) throws IOException { + if (inputStream == null) { + return null; + } + ImportParams params = new ImportParams(); + params.setTitleRows(titleRows); + params.setHeadRows(headerRows); + params.setSaveUrl("/excel/"); + params.setNeedSave(true); + try { + return ExcelImportUtil.importExcel(inputStream, pojoClass, params); + } catch (NoSuchElementException e) { + throw new IOException("excel文件不能为空"); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + } + +} diff --git a/src/main/java/com/sqx/modules/utils/FileUtils.java b/src/main/java/com/sqx/modules/utils/FileUtils.java new file mode 100644 index 0000000..0e5ea41 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/FileUtils.java @@ -0,0 +1,63 @@ +package com.sqx.modules.utils; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.http.entity.ContentType; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + + +/** + * 文件工具类 + * @author fang + * @date 2021-03-4 + */ +public class FileUtils { + + /** + * 根据文件地址下载文件 + * @param url 文件地址 + * @param fileName 文件名 + * @return + */ + public static MultipartFile createFileItem(String url, String fileName) { + FileItem item = null; + try { + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); + conn.setReadTimeout(30000); + conn.setConnectTimeout(30000); + //设置应用程序要从网络连接读取数据 + conn.setDoInput(true); + conn.setRequestMethod("GET"); + if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { + InputStream is = conn.getInputStream(); + + FileItemFactory factory = new DiskFileItemFactory(16, null); + String textFieldName = "uploadfile"; + item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName); + OutputStream os = item.getOutputStream(); + + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { + os.write(buffer, 0, bytesRead); + } + os.close(); + is.close(); + } + } catch (IOException e) { + throw new RuntimeException("文件下载失败", e); + } + + return new CommonsMultipartFile(item); + } + + +} diff --git a/src/main/java/com/sqx/modules/utils/HttpClientUtil.java b/src/main/java/com/sqx/modules/utils/HttpClientUtil.java new file mode 100644 index 0000000..102f2c3 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/HttpClientUtil.java @@ -0,0 +1,264 @@ +package com.sqx.modules.utils; + +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.nio.Buffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Slf4j +public class HttpClientUtil { + + public static String doGet(String url, Map param) { + + // 创建Httpclient对象 + CloseableHttpClient httpclient = HttpClients.createDefault(); + + String resultString = ""; + CloseableHttpResponse response = null; + try { + // 创建uri + URIBuilder builder = new URIBuilder(url); + if (param != null) { + for (String key : param.keySet()) { + builder.addParameter(key, param.get(key)); + } + } + URI uri = builder.build(); + + // 创建http GET请求 + HttpGet httpGet = new HttpGet(uri); + // 执行请求 + response = httpclient.execute(httpGet); + // 判断返回状态是否为200 + if (response.getStatusLine().getStatusCode() == 200) { + resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (response != null) { + response.close(); + } + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return resultString; + } + + public static String doGet(String url) { + return doGet(url, null); + } + + public static String doPost(String url, Map param) { + // 创建Httpclient对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = null; + String resultString = ""; + try { + // 创建Http Post请求 + HttpPost httpPost = new HttpPost(url); + // 创建参数列表 + if (param != null) { + List paramList = new ArrayList<>(); + for (String key : param.keySet()) { + paramList.add(new BasicNameValuePair(key, param.get(key))); + } + // 模拟表单 + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); + httpPost.setEntity(entity); + } + // 执行http请求 + response = httpClient.execute(httpPost); + resultString = EntityUtils.toString(response.getEntity(), "utf-8"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return resultString; + } + + public static String doPost(String url) { + return doPost(url, null); + } + + public static String doPostJson(String url, String json) { + // 创建Httpclient对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = null; + String resultString = ""; + try { + // 创建Http Post请求 + HttpPost httpPost = new HttpPost(url); + // 创建请求内容 + StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); + httpPost.setEntity(entity); + // 执行http请求 + response = httpClient.execute(httpPost); + resultString = EntityUtils.toString(response.getEntity(), "utf-8"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return resultString; + } + + /* 发送 post请求 用HTTPclient 发送请求*/ + public static byte[] post(String URL, String json) { + String obj = null; + InputStream inputStream = null; + Buffer reader = null; + byte[] data = null; + // 创建默认的httpClient实例. + CloseableHttpClient httpclient = HttpClients.createDefault(); + // 创建httppost + HttpPost httppost = new HttpPost(URL); + httppost.addHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Accept", "application/json"); + try { + StringEntity s = new StringEntity(json, Charset.forName("UTF-8")); + s.setContentEncoding("UTF-8"); + httppost.setEntity(s); + CloseableHttpResponse response = httpclient.execute(httppost); + try { + // 获取相应实体 + HttpEntity entity = response.getEntity(); + if (entity != null) { + inputStream = entity.getContent(); + data = readInputStream(inputStream); + } + return data; + } finally { + response.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 关闭连接,释放资源 + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return data; + } + + + /** 将流 保存为数据数组 + * @param inStream + * @return + * @throws Exception + */ + public static byte[] readInputStream(InputStream inStream) throws Exception { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + // 创建一个Buffer字符串 + byte[] buffer = new byte[1024]; + // 每次读取的字符串长度,如果为-1,代表全部读取完毕 + int len = 0; + // 使用一个输入流从buffer里把数据读取出来 + while ((len = inStream.read(buffer)) != -1) { + // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 + outStream.write(buffer, 0, len); + } + // 关闭输入流 + inStream.close(); + // 把outStream里的数据写入内存 + return outStream.toByteArray(); + } + + + /** + * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; + * + * @param request + * @return + * @throws IOException + */ + public static String getIpAddress(HttpServletRequest request) throws IOException { + // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 + String ip = request.getHeader("X-Forwarded-For"); + if (log.isInfoEnabled()) { + log.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + if (log.isInfoEnabled()) { + log.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip); + } + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + if (log.isInfoEnabled()) { + log.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip); + } + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + if (log.isInfoEnabled()) { + log.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip); + } + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + if (log.isInfoEnabled()) { + log.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip); + } + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + if (log.isInfoEnabled()) { + log.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip); + } + } + } else if (ip.length() > 15) { + String[] ips = ip.split(","); + for (int index = 0; index < ips.length; index++) { + String strIp = (String) ips[index]; + if (!("unknown".equalsIgnoreCase(strIp))) { + ip = strIp; + break; + } + } + } + return ip; + } + + +} diff --git a/src/main/java/com/sqx/modules/utils/HttpUtil.java b/src/main/java/com/sqx/modules/utils/HttpUtil.java new file mode 100644 index 0000000..88d41fa --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/HttpUtil.java @@ -0,0 +1,223 @@ +package com.sqx.modules.utils; + +import javax.net.ssl.*; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Map; +import java.util.Map.Entry; + +/** + * 进行http访问的基本类 + */ +public class HttpUtil { + + private static final String DEFAULT_CHARSET = "UTF-8"; + + private static final String METHOD_POST = "POST"; + + private static final String METHOD_GET = "GET"; + + private static final int CONNECTTIMEOUT = 5000; + + private static final int READTIMEOUT = 5000; + + private static class DefaultTrustManager implements X509TrustManager { + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] cert, String oauthType) + throws java.security.cert.CertificateException { + } + + public void checkServerTrusted(X509Certificate[] cert, String oauthType) + throws java.security.cert.CertificateException { + } + } + + private static HttpURLConnection getConnection(URL url, String method) + throws IOException { + + HttpURLConnection conn; + if ("https".equals(url.getProtocol())) { + SSLContext ctx; + try { + ctx = SSLContext.getInstance("TLS"); + ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, + new SecureRandom()); + } catch (Exception e) { + throw new IOException(e); + } + HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection(); + connHttps.setSSLSocketFactory(ctx.getSocketFactory()); + connHttps.setHostnameVerifier(new HostnameVerifier() { + + public boolean verify(String hostname, SSLSession session) { + return true;// 默认都认证通过 + } + }); + conn = connHttps; + } else { + conn = (HttpURLConnection) url.openConnection(); + } + conn.setRequestMethod(method); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); + conn.setRequestProperty("Connection", "Keep-Alive"); + return conn; + + } + + /** + * 通过get方法访问 + * + * @param url 访问的url地址 + * @param urlParams 请求需要的参数 + * @return 返回请求响应的数据 + * @throws IOException + */ + public static String doGet(String url, Map urlParams) + throws IOException { + if (isEmpty(url)) { + throw new IllegalArgumentException("The parameter 'url' can not be null or blank."); + } + url += buildQuery(urlParams, DEFAULT_CHARSET); + HttpURLConnection conn = getConnection(new URL(url), METHOD_GET); + String s = getResponseAsString(conn); + return s; + } + + /** + * + * @param url api请求的权路径url地址 + * @param urlParams 请求的参数 + * @param requestJson 请求报文 + * @return 请求响应 + * @throws IOException + */ + public static String doPost(String url, Map urlParams, String requestJson) throws IOException { + return doPost(url, urlParams, requestJson, CONNECTTIMEOUT, READTIMEOUT); + } + + /** + * + * 通过post方法请求数据 + * + * @param url 请求的url地址 + * @param urlParams 请求的参数 + * @param requestJson 请求报文 + * @param connectTimeOut 请求连接过期时间 + * @param readTimeOut 请求读取过期时间 + * @return 请求响应 + * @throws IOException + */ + public static String doPost(String url, Map urlParams, String requestJson, + int connectTimeOut, int readTimeOut) throws IOException { + if (isEmpty(url)) { + throw new IllegalArgumentException("The parameter 'url' can not be null or blank."); + } + url += buildQuery(urlParams, DEFAULT_CHARSET); + HttpURLConnection conn = getConnection(new URL(url), METHOD_POST); + conn.setConnectTimeout(connectTimeOut); + conn.setReadTimeout(readTimeOut); + conn.getOutputStream().write(requestJson.getBytes(DEFAULT_CHARSET)); + String s = getResponseAsString(conn); + return s; + } + + /** + * + * @param params 请求参数 + * @return 构建query + */ + public static String buildQuery(Map params, String charset) throws UnsupportedEncodingException { + if (params == null || params.isEmpty()) { + return ""; + } + StringBuilder sb = new StringBuilder(); + boolean first = true; + for (Entry entry : params.entrySet()) { + if (first) { + sb.append("?"); + first = false; + } else { + sb.append("&"); + } + String key = entry.getKey(); + String value = entry.getValue(); + if (areNotEmpty(key, value)) { + sb.append(key).append("=").append(URLEncoder.encode(value, charset)); + } + } + return sb.toString(); + + } + + private static String getResponseAsString(HttpURLConnection conn) throws IOException { + InputStream es = conn.getErrorStream(); + if (es == null) { + return getStreamAsString(conn.getInputStream(), DEFAULT_CHARSET); + } else { + String msg = getStreamAsString(es, DEFAULT_CHARSET); + if (isEmpty(msg)) { + throw new IOException(conn.getResponseCode() + " : " + conn.getResponseMessage()); + } else { + throw new IOException(msg); + } + } + + } + + private static String getStreamAsString(InputStream input, String charset) throws IOException { + StringBuilder sb = new StringBuilder(); + BufferedReader bf = null; + try { + bf = new BufferedReader(new InputStreamReader(input, charset)); + String str; + while ((str = bf.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (bf != null) { + bf.close(); + } + } + + } + + /** + * 判断字符串为空 + * + * @param str 字符串信息 + * @return true or false + */ + private static boolean isEmpty(String str) { + return str == null || str.trim().length() == 0; + } + + /** + * 判断字符数组,不为空 + * + * @param values 字符数组 + * @return true or false + */ + public static boolean areNotEmpty(String... values) { + if (values == null || values.length == 0) { + return false; + } + + for (String value : values) { + if (isEmpty(value)) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/com/sqx/modules/utils/InvitationCodeUtil.java b/src/main/java/com/sqx/modules/utils/InvitationCodeUtil.java new file mode 100644 index 0000000..bf14457 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/InvitationCodeUtil.java @@ -0,0 +1,59 @@ +package com.sqx.modules.utils; + +import com.sqx.modules.app.entity.UserEntity; +import com.sqx.modules.app.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Random; + +/** + * 邀请码生成解密工具类 + * @author fang + * @date 2020/7/8 + */ +@Component +public class InvitationCodeUtil { + + private static UserService userService; + + @Autowired + public void setUserService(UserService userService) { + InvitationCodeUtil.userService = userService; + } + + public static String toSerialCode() { + //元素 + + int[] array = {0,1,2,3,4,5,6,7,8,9}; + Random rand = new Random(); + while (true){ + for (int i = 10; i > 1; i--) { + int index = rand.nextInt(i); + int tmp = array[index]; + array[index] = array[i - 1]; + array[i - 1] = tmp; + } + int result = 0; + for(int i = 0; i < 6; i++){ + result = result * 10 + array[i]; + } + + String sixString = Integer.toString(result); + if (sixString.length() == 5) { + sixString = "0" + sixString; + + } + String str = sixString; + UserEntity userEntity = userService.queryByInvitationCode(str); + if(userEntity==null){ + return str; + } + } + } + + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/LonLatUtil.java b/src/main/java/com/sqx/modules/utils/LonLatUtil.java new file mode 100644 index 0000000..549d780 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/LonLatUtil.java @@ -0,0 +1,25 @@ +package com.sqx.modules.utils; + +import org.gavaghan.geodesy.Ellipsoid; +import org.gavaghan.geodesy.GeodeticCalculator; +import org.gavaghan.geodesy.GeodeticCurve; +import org.gavaghan.geodesy.GlobalCoordinates; + +/** + * @description: 经纬度计算工具类 + */ +public class LonLatUtil { + + /** + * 创建GeodeticCalculator,调用计算方法,传入坐标系、经纬度用于计算距离 + * @param gpsFrom 当前位置 + * @param gpsTo 目标位置 + * @param ellipsoid 坐标系 + * @return + */ + public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, + Ellipsoid ellipsoid){ + GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo); + return geoCurve.getEllipsoidalDistance(); + } +} diff --git a/src/main/java/com/sqx/modules/utils/MD5Util.java b/src/main/java/com/sqx/modules/utils/MD5Util.java new file mode 100644 index 0000000..ea314d7 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/MD5Util.java @@ -0,0 +1,162 @@ +package com.sqx.modules.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class MD5Util { + private static final Logger logger = LoggerFactory.getLogger(MD5Util.class); + static MessageDigest messageDigest = null; + + /** + * 判断新密码和旧密码是否正确 返回true 和 false + * + * @param newStr + * @param oldMD5Str + * @return + */ + public final static boolean checkMD5(String newStr, String oldMD5Str) { + String temp = encoderByMd5(newStr); + return (temp != null && temp.equals(oldMD5Str)) ? true : false; + } + + /** + * 对给定的字符串进行加密 + * + * @param source + * @return 加密后的16进制的字符串 + */ + public final static String encoderByMd5(String source) { + String tmp = source.substring(0, 1) + + source.subSequence(source.length() - 1, source.length()); + tmp = md5(tmp); + return md5(source + tmp); + } + + private static String md5(String source) { + + char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', + 'e', 'f'}; + try { + + byte[] strTemp = source.getBytes(); + // 使用MD5创建MessageDigest对象 + MessageDigest mdTemp = MessageDigest.getInstance("MD5"); + mdTemp.update(strTemp); + byte[] md = mdTemp.digest(); + int j = md.length; + char str[] = new char[j * 2]; + int k = 0; + for (byte b : md) { + str[k++] = hexDigits[b >> 4 & 0xf]; + str[k++] = hexDigits[b & 0xf]; + } + + if (logger.isDebugEnabled()) { + logger.debug("加密后的字符串:" + new String(str)); + } + return new String(str); + } catch (Exception e) { + logger.error("md5加密出错:" + source, e); + return null; + } + + } + + + public static String encodeByMD5(String str) { + try { + if (messageDigest == null) { + messageDigest = MessageDigest.getInstance("MD5"); + } + messageDigest.reset(); + messageDigest.update(str.getBytes("UTF-8")); + } catch (NoSuchAlgorithmException e) { + logger.error("NoSuchAlgorithmException caught!", e); + + } catch (UnsupportedEncodingException e) { + logger.error("UnsupportedEncodingException error!", e); + } + if (messageDigest == null) { + return ""; + } + byte[] byteArray = messageDigest.digest(); + + StringBuffer md5StrBuff = new StringBuffer(); + + for (int i = 0; i < byteArray.length; i++) { + if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) { + md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); + } else { + md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); + } + } + + return md5StrBuff.toString(); + } + + /** + * MD5加密字符串(32位大写) + * + * @param string 需要进行MD5加密的字符串 + * @return 加密后的字符串(大写) + */ + public static String md5Encrypt32Upper(String string) { + byte[] hash; + try { + //创建一个MD5算法对象,并获得MD5字节数组,16*8=128位 + hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8")); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Huh, MD5 should be supported?", e); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("Huh, UTF-8 should be supported?", e); + } + //转换为十六进制字符串 + StringBuilder hex = new StringBuilder(hash.length * 2); + for (byte b : hash) { + if ((b & 0xFF) < 0x10) { + hex.append("0"); + } + hex.append(Integer.toHexString(b & 0xFF)); + } + return hex.toString().toUpperCase(); + } + + + public static String encryption(String plain) { + String re_md5 = new String(); + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(plain.getBytes("utf-8")); + byte b[] = md.digest(); + + int i; + + StringBuffer buf = new StringBuffer(""); + for (int offset = 0; offset < b.length; offset++) { + i = b[offset]; + if (i < 0) { + i += 256; + } + if (i < 16) { + buf.append("0"); + } + buf.append(Integer.toHexString(i)); + } + + re_md5 = buf.toString(); + + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return re_md5; + } + + + +} diff --git a/src/main/java/com/sqx/modules/utils/SenInfoCheckUtil.java b/src/main/java/com/sqx/modules/utils/SenInfoCheckUtil.java new file mode 100644 index 0000000..1c79332 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/SenInfoCheckUtil.java @@ -0,0 +1,342 @@ +package com.sqx.modules.utils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.google.common.collect.Maps; +import com.sqx.modules.common.service.CommonInfoService; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import javax.imageio.ImageIO; +import javax.servlet.http.HttpServletResponse; +import java.awt.image.BufferedImage; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +@Component +public class SenInfoCheckUtil { + + private static Logger logger = LoggerFactory.getLogger(SenInfoCheckUtil.class); + + private static String MpAccessToken; + + // 这里使用静态,让 service 属于类 + private static CommonInfoService commonInfoService; + + // 注入的时候,给类的 service 注入 + @Autowired + public void setWxChatContentService(CommonInfoService commonInfoService) { + SenInfoCheckUtil.commonInfoService = commonInfoService; + } + + + /** + * 获取Token 小程序 + * @param + * @param + * @return AccessToken + */ + public static String getMpToken(){ + return getMpAccessToken(); + } + + public static String getShopToken(){ + return getShopAccessToken(); + } + + + public static void getImg(String relation,String goodsId,String type, String page,HttpServletResponse response){ + String mpToken = getMpToken(); + //获取二维码数据 + String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+mpToken; + Map map = Maps.newHashMap(); + map.put("scene",relation+"&"+goodsId+"&"+type); + String value = commonInfoService.findOne(105).getValue(); + if("是".equals(value)){ + map.put("page",page); + } + map.put("width", 280); + String jsonString = JSON.toJSONString(map); + InputStream inputStream = sendPostBackStream(url, jsonString); + //生成二维码图片 + response.setContentType("image/png"); + try{ + BufferedImage bi = ImageIO.read(inputStream); + ImageIO.write(bi, "JPG", response.getOutputStream()); + inputStream.close(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + + /** + * 获取二维码图片 + */ + public static void getPoster(String invitationCode, HttpServletResponse response){ + String mpToken = getMpToken(); + //获取二维码数据 + String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+mpToken; + Map map = Maps.newHashMap(); + map.put("scene",invitationCode); + map.put("width", 280); + String jsonString = JSON.toJSONString(map); + InputStream inputStream = sendPostBackStream(url, jsonString); + //生成二维码图片 + response.setContentType("image/png"); + try{ + BufferedImage bi = ImageIO.read(inputStream); + ImageIO.write(bi, "JPG", response.getOutputStream()); + inputStream.close(); + }catch (Exception e){ + logger.error(e.getMessage()); + } + } + + private static InputStream sendPostBackStream(String url, String param) { + PrintWriter out = null; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection conn = realUrl.openConnection(); + // 设置通用的请求属性 + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + conn.setDoOutput(true); + conn.setDoInput(true); + //解决乱码问题 + OutputStreamWriter outWriter =new OutputStreamWriter(conn.getOutputStream(), "utf-8"); + out =new PrintWriter(outWriter); + // 发送请求参数 + if(StringUtils.isNotBlank(param)) { + out.print(param); + } + // flush输出流的缓冲 + out.flush(); + return conn.getInputStream(); + } catch (Exception e) { + logger.error("发送 POST 请求出现异常!"+e); + } finally{ + IOUtils.closeQuietly(out); + } + return null; + } + + + /** + * 获取access_token + * 每个两个小时自动刷新AcessTocken + */ + + public static String getMpAccessToken(){ + String appid = commonInfoService.findOne(45).getValue(); + String secret = commonInfoService.findOne(46).getValue(); + String jsonResult = HttpClientUtil.doPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret); + JSONObject parseObject = JSON.parseObject(jsonResult); + logger.info("=========accessTokenOut========="+parseObject.toJSONString()); + + String errcode = parseObject.getString("errcode"); + String accessToken = parseObject.getString("access_token"); + String expiresIn = parseObject.getString("expires_in"); + return accessToken; + } + + + public static String getShopAccessToken(){ + String appid = commonInfoService.findOne(239).getValue(); + String secret = commonInfoService.findOne(240).getValue(); + String jsonResult = HttpClientUtil.doPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret); + JSONObject parseObject = JSON.parseObject(jsonResult); + logger.info("=========accessTokenOut========="+parseObject.toJSONString()); + + String errcode = parseObject.getString("errcode"); + String accessToken = parseObject.getString("access_token"); + String expiresIn = parseObject.getString("expires_in"); + return accessToken; + } + + + public static void sendMsg(String wxId, String templateId, String page, List msgList, Integer type){ + String mpToken = getMpToken(); + RestTemplate restTemplate = new RestTemplate(); + String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" +mpToken; + //拼接推送的模版 + WxMssVo wxMssVo = new WxMssVo(); + wxMssVo.setTouser(wxId);//用户的openid(要发送给那个用户,通常这里应该动态传进来的) + wxMssVo.setTemplate_id(templateId);//订阅消息模板id + /*if(type==1){ + wxMssVo.setPage("/my/takeOrder/index"); + }else{ + wxMssVo.setPage("/my/order/index"); + }*/ + wxMssVo.setPage("/pages/order/index"); + wxMssVo.setData(getParam(type,msgList)); + ResponseEntity responseEntity = + restTemplate.postForEntity(url, wxMssVo, String.class); + String body = responseEntity.getBody(); + System.err.println(body); + + } + + public static void sendShopMsg(String wxId, String templateId, String page, List msgList, Integer type){ + String mpToken = getShopToken(); + RestTemplate restTemplate = new RestTemplate(); + String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" +mpToken; + //拼接推送的模版 + WxMssVo wxMssVo = new WxMssVo(); + wxMssVo.setTouser(wxId);//用户的openid(要发送给那个用户,通常这里应该动态传进来的) + wxMssVo.setTemplate_id(templateId);//订阅消息模板id +// if(type==1){ +// wxMssVo.setPage("/my/takeOrder/index"); +// }else{ +// wxMssVo.setPage("/my/order/index"); +// } + wxMssVo.setData(getParam(type,msgList)); + ResponseEntity responseEntity = + restTemplate.postForEntity(url, wxMssVo, String.class); + String body = responseEntity.getBody(); + System.err.println(body); + + } + + + + public static Map getParam(Integer type, List msgList){ + if(type==1){ + Map paras = new HashMap<>(); + paras.put("thing1",new TemplateParam( msgList.get(0))); + paras.put("phrase5",new TemplateParam( msgList.get(1))); + paras.put("time3",new TemplateParam( msgList.get(2))); + return paras; + }else if(type==2){ + Map paras = new HashMap<>(); + paras.put("character_string12",new TemplateParam(msgList.get(0))); + paras.put("thing6",new TemplateParam( msgList.get(1))); + paras.put("thing11",new TemplateParam( msgList.get(2))); + paras.put("date4",new TemplateParam( msgList.get(3))); + paras.put("thing5",new TemplateParam( msgList.get(4))); + return paras; + }else{ + Map paras = new HashMap<>(); + paras.put("character_string9",new TemplateParam( msgList.get(0))); + paras.put("thing10",new TemplateParam( msgList.get(1))); + paras.put("character_string6",new TemplateParam( msgList.get(2))); + paras.put("thing7",new TemplateParam( msgList.get(3))); + return paras; + } + + + + + + } + + + public static String addressCutting(String address) { + if (address.startsWith("北京市") || address.startsWith("天津市") || address.startsWith("上海市") || address.startsWith("重庆市")) { + address = address.substring(0, 3) + "市辖区" + address.substring(3); + } + String regex = "(?[^省]+自治区|.*?省|.*?行政区|.*?市)(?[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?[^区]+区|.+镇)?(?.*)"; + Matcher m = Pattern.compile(regex).matcher(address); + String province = null, city = null, county = null, town = null, village = null; + while(m.find()){ + province = m.group("province"); + + if (province.equals("北京市") || province.equals("天津市") || province.equals("上海市") || province.equals("重庆市")) { + city = province; + + county = m.group("city"); + if (county.split("区").length > 1) { + town = county.substring(county.indexOf("区") + 1); + county = county.substring(0, county.indexOf("区") + 1); + if (town.contains("区")) { + town = town.substring(county.indexOf("区") + 1); + } + } else { + county = m.group("county"); + if (county.split("区").length > 1) { + town = county.substring(county.indexOf("区") + 1); + county = county.substring(0, county.indexOf("区") + 1); + } + } + } else { + city = m.group("city"); + + county = m.group("county"); + if (county != null && !"".equals(county)) { + if (county.split("市").length > 1 && county.indexOf("市") < 5) { + town = county; + county = county.substring(0, county.indexOf("市") + 1); + town = town.substring(county.indexOf("市") + 1); + } + if (county.split("旗").length > 1) { + town = county; + county = county.substring(0, county.indexOf("旗") + 1); + town = town.substring(county.indexOf("旗") + 1); + } + if (county.split("海域").length > 1) { + town = county; + county = county.substring(0, county.indexOf("海域") + 2); + town = town.substring(county.indexOf("海域") + 2); + } + if (county.split("区").length > 1) { + town = county; + county = county.substring(0, county.indexOf("区") + 1); + town = town.substring(county.indexOf("区") + 1); + } + } + + } + + if (province != null && !"".equals(province)) { + province = province + "-"; + } + + if (city != null && !"".equals(city)) { + city = city + "-"; + } + + if (county != null && !"".equals(county)) { + county = county + "-"; + } + + town+=m.group("town"); + if ((county == null || "".equals(county)) && town != null && !"".equals(town)) { + town = town + "-"; + } + village=m.group("village"); + + } + + String newMachineAdress = province + city + county + town + village; + if (newMachineAdress != null && !"".equals(newMachineAdress)) { + newMachineAdress = newMachineAdress.replaceAll("null", ""); + } + + if (newMachineAdress == null || "".equals(newMachineAdress)) { + newMachineAdress = address; + } + + return newMachineAdress; + } + + +} diff --git a/src/main/java/com/sqx/modules/utils/Template.java b/src/main/java/com/sqx/modules/utils/Template.java new file mode 100644 index 0000000..b0cc289 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/Template.java @@ -0,0 +1,20 @@ +package com.sqx.modules.utils; + +import lombok.Data; + +import java.util.List; + +@Data +public class Template { + + private String template_id; + + private String touser; + + private String page; + + private String data; + + private List templateParamList; + +} diff --git a/src/main/java/com/sqx/modules/utils/TemplateParam.java b/src/main/java/com/sqx/modules/utils/TemplateParam.java new file mode 100644 index 0000000..51f0628 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/TemplateParam.java @@ -0,0 +1,21 @@ +package com.sqx.modules.utils; + +public class TemplateParam { + + + private String value; + + public TemplateParam( String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/WXConfigUtil.java b/src/main/java/com/sqx/modules/utils/WXConfigUtil.java new file mode 100644 index 0000000..70493e9 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/WXConfigUtil.java @@ -0,0 +1,70 @@ +package com.sqx.modules.utils; + +import com.github.wxpay.sdk.WXPayConfig; +import lombok.Data; +import org.apache.commons.io.IOUtils; +import org.springframework.core.io.ClassPathResource; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.nio.file.Files; + +/** + * @author fang + * @date 2020/2/26 + */ +@Data +public class WXConfigUtil implements WXPayConfig { + private byte[] certData; + private String appId = ""; + private String key = ""; + private String mchId = ""; + + + //初始化加载证书 + public WXConfigUtil(String filePath) throws Exception { + + File file = new File(filePath); + InputStream fis = null; + try { + fis = Files.newInputStream(file.toPath()); + this.certData = IOUtils.toByteArray(fis); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (fis != null) { + fis.close(); + } + } + } + + + @Override + public String getAppID() { + return this.appId; + } + + @Override + public String getMchID() { + return this.mchId; + } + + @Override + public InputStream getCertStream() { + ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData); + return certBis; + } + + @Override + public int getHttpConnectTimeoutMs() { + return 8000; + } + + @Override + public int getHttpReadTimeoutMs() { + return 10000; + } + + +} diff --git a/src/main/java/com/sqx/modules/utils/WxMssVo.java b/src/main/java/com/sqx/modules/utils/WxMssVo.java new file mode 100644 index 0000000..78d85a6 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/WxMssVo.java @@ -0,0 +1,42 @@ +package com.sqx.modules.utils; + +import java.util.Map; + +public class WxMssVo { + private String touser;//用户openid + private String template_id;//订阅消息模版id + private String page = "/pages/index/index";//默认跳到小程序首页 + private Map data;//推送文字 + + public String getTouser() { + return touser; + } + + public void setTouser(String touser) { + this.touser = touser; + } + + public String getTemplate_id() { + return template_id; + } + + public void setTemplate_id(String template_id) { + this.template_id = template_id; + } + + public String getPage() { + return page; + } + + public void setPage(String page) { + this.page = page; + } + + public Map getData() { + return data; + } + + public void setData(Map data) { + this.data = data; + } +} diff --git a/src/main/java/com/sqx/modules/utils/excel/ExcelData.java b/src/main/java/com/sqx/modules/utils/excel/ExcelData.java new file mode 100644 index 0000000..692e79d --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/excel/ExcelData.java @@ -0,0 +1,34 @@ +package com.sqx.modules.utils.excel; + +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * @author fang + * @date 2020/9/24 + */ + +@Data +public class ExcelData implements Serializable { + + private static final long serialVersionUID = 4454016249210520899L; + + /** + * 表头 + */ + private List titles; + + /** + * 数据 + */ + private List> rows; + + /** + * 页签名称 + */ + private String name; + + +} diff --git a/src/main/java/com/sqx/modules/utils/excel/ExcelUtils.java b/src/main/java/com/sqx/modules/utils/excel/ExcelUtils.java new file mode 100644 index 0000000..6ce7174 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/excel/ExcelUtils.java @@ -0,0 +1,171 @@ +package com.sqx.modules.utils.excel; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.http.entity.ContentType; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * @author fang + * @date 2021/1/27 + */ +@Slf4j +public class ExcelUtils { + + /*public static List get(String fileUrl){ + MultipartFile fileItem = createFileItem(fileUrl, null); + String substring = fileUrl.substring(fileUrl.lastIndexOf(".")); + List list=new ArrayList<>(); + try { +// String fileName = fileItem.getOriginalFilename(); + String xls=".xlsx"; + InputStream inputStream = fileItem.getInputStream(); + log.info("文件名:{}", substring); + int serviceStationNo=0; + int serviceStationName=0; + int oilName=0; + int activity=0; + int downPrice=0; + //区分两种excel表格 + if(substring.indexOf(xls)!=-1){ + XSSFWorkbook workbook=new XSSFWorkbook(inputStream); + //获取第一个工作表 + org.apache.poi.xssf.usermodel.XSSFSheet hs=workbook.getSheetAt(0); + //获取Sheet的第一个行号和最后一个行号 + int last=hs.getLastRowNum(); + int first=hs.getFirstRowNum(); + //遍历获取单元格里的信息 + for (int i = first; i <=last; i++) { + XSSFRow row=hs.getRow(i); + int firstCellNum=row.getFirstCellNum();//获取所在行的第一个行号 + int lastCellNum=row.getLastCellNum();//获取所在行的最后一个行号 + OilStation oilStation=new OilStation(); + for (int j = firstCellNum; j titles) { + int rowIndex = 0; + int colIndex = 0; + Font titleFont = wb.createFont();//获取字体 + titleFont.setFontName("simsun");//设置字体名称(宋体) + titleFont.setBold(true);//设置字体加粗 + titleFont.setColor(IndexedColors.BLACK.index);//设置字体颜色 黑色 + XSSFCellStyle titleStyle = wb.createCellStyle();//获取单元格样式 + titleStyle.setAlignment(HorizontalAlignment.CENTER);//设置单元格的水平对齐类型(这里是水平居中) + titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置单元格的垂直对齐类型(这里是居中) + titleStyle.setFillForegroundColor(createXssfColor("#FFFFFF"));//设置单元格前景色(白色) + titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//指定图案和纯色单元格填充的单元格填充信息(实心前景) + titleStyle.setFont(titleFont);//设置字体样式 + setBorder(titleStyle, BorderStyle.THIN, createXssfColor("#000000"));//设置边框样式(细线、黑色) + Row titleRow = sheet.createRow(rowIndex);//在该工作簿中创建第一行. + colIndex = 0; + for (String field : titles) {//循环创建列 + Cell cell = titleRow.createCell(colIndex); + cell.setCellValue(field); + cell.setCellStyle(titleStyle); + colIndex++; + } + rowIndex++;//将行数++ 返回用于下面添加数据 + return rowIndex; + } + + /** + * 将数据写入 + * @param wb + * @param sheet + * @param rows + * @param rowIndex + * @return + */ + private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List> rows, int rowIndex) { + int colIndex = 0; + Font dataFont = wb.createFont();//获取字体 + dataFont.setFontName("simsun");//设置字体名称(宋体) + dataFont.setColor(IndexedColors.BLACK.index);//设置字体颜色 黑色 + XSSFCellStyle dataStyle = wb.createCellStyle();//获取单元格样式 + dataStyle.setAlignment(HorizontalAlignment.CENTER);//设置单元格的水平对齐类型(这里是水平居中) + dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置单元格的垂直对齐类型(这里是居中) + dataStyle.setFont(dataFont);//设置字体样式 + setBorder(dataStyle, BorderStyle.THIN, createXssfColor("#000000"));//设置边框样式(细线、黑色) + for (List rowData : rows) {//循环写入数据 + Row dataRow = sheet.createRow(rowIndex); + colIndex = 0; + for (Object cellData : rowData) { + Cell cell = dataRow.createCell(colIndex); + if (cellData != null) { + cell.setCellValue(cellData.toString()); + } else { + cell.setCellValue(""); + } + + cell.setCellStyle(dataStyle); + colIndex++; + } + rowIndex++; + } + return rowIndex; + } + + /** + * 自动调整大小 + * @param sheet + * @param columnNumber + */ + private static void autoSizeColumns(Sheet sheet, int columnNumber) { + for (int i = 0; i < columnNumber; i++) { + int orgWidth = sheet.getColumnWidth(i); + sheet.autoSizeColumn(i, true); + int newWidth = (int) (sheet.getColumnWidth(i) + 100); + if (newWidth > orgWidth) { + sheet.setColumnWidth(i, newWidth); + } else { + sheet.setColumnWidth(i, orgWidth); + } + } + } + + /** + * 设置表格样式 + * @param style + * @param border + * @param color + */ + private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) { + style.setBorderTop(border); + style.setBorderLeft(border); + style.setBorderRight(border); + style.setBorderBottom(border); + style.setBorderColor(XSSFCellBorder.BorderSide.TOP, color); + style.setBorderColor(XSSFCellBorder.BorderSide.LEFT, color); + style.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, color); + style.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color); + } + + /** + * 将rgb颜色码 转换为 XSSFColor + * @param color + * @return + */ + private static XSSFColor createXssfColor(String color) { + int[] rgbColor = hexToRgb(color); + XSSFColor xssfColor = new XSSFColor(new java.awt.Color(rgbColor[0], rgbColor[1], rgbColor[2]), new DefaultIndexedColorMap()); + return xssfColor; + } + + /** + * 将颜色码 转换为 r g b + * @param hex + * @return + */ + public static int[] hexToRgb(String hex) { + String colorStr = hex; + if (hex.startsWith("#")) { + colorStr = hex.substring(1); + } + if (StringUtils.length(colorStr) == 8) { + colorStr = hex.substring(2); + } + int r= Integer.valueOf( colorStr.substring( 0, 2 ), 16 ); + int g= Integer.valueOf( colorStr.substring( 2, 4 ), 16 ); + int b= Integer.valueOf( colorStr.substring( 4, 6 ), 16 ); + + return new int[] { r, g, b }; + } + + + + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/fieYun/FeiYunUtils.java b/src/main/java/com/sqx/modules/utils/fieYun/FeiYunUtils.java new file mode 100644 index 0000000..682bf76 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/fieYun/FeiYunUtils.java @@ -0,0 +1,705 @@ +package com.sqx.modules.utils.fieYun; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.sqx.modules.common.service.CommonInfoService; +import com.sqx.modules.orders.entity.Orders; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +@Component +@Slf4j +public class FeiYunUtils { + + + private static CommonInfoService commonInfoService; + + @Autowired + public void setCommonInfoService(CommonInfoService commonRepository) { + FeiYunUtils.commonInfoService = commonRepository; + } + + /** + * 添加打印机接口 + * @param snlist 提示:打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填),多台打印机请换行(\n)添加新打印机信息,每次最多100行(台)。 + * @return 正确例子:{"msg":"ok","ret":0,"data":{"ok":["sn#key#remark#carnum","316500011#abcdefgh#快餐前台"],"no":["316500012#abcdefgh#快餐前台#13688889999 (错误:识别码不正确)"]},"serverExecutedTime":3} + * 错误:{"msg":"参数错误 : 该帐号未注册.","ret":-2,"data":null,"serverExecutedTime":37} + */ + public static String addprinter(String snlist){ + String URL = commonInfoService.findOne(325).getValue(); + String USER = commonInfoService.findOne(326).getValue(); + String UKEY = commonInfoService.findOne(327).getValue(); + //通过POST请求,发送打印信息到服务器 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(30000)//读取超时 + .setConnectTimeout(30000)//连接超时 + .build(); + + CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + + HttpPost post = new HttpPost(URL); + List nvps = new ArrayList(); + nvps.add(new BasicNameValuePair("user",USER)); + String STIME = String.valueOf(System.currentTimeMillis()/1000); + nvps.add(new BasicNameValuePair("stime",STIME)); + nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); + nvps.add(new BasicNameValuePair("apiname","Open_printerAddlist"));//固定值,不需要修改 + nvps.add(new BasicNameValuePair("printerContent",snlist)); + + CloseableHttpResponse response = null; + String result = null; + try + { + post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); + response = httpClient.execute(post); + int statecode = response.getStatusLine().getStatusCode(); + if(statecode == 200){ + HttpEntity httpentity = response.getEntity(); + if (httpentity != null){ + result = EntityUtils.toString(httpentity); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + finally{ + try { + if(response!=null){ + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + post.abort(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + + } + + /** + * 修改打印机接口 + * @param snlist 提示:打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填),多台打印机请换行(\n)添加新打印机信息,每次最多100行(台)。 + * @return 正确例子:{"msg":"ok","ret":0,"data":{"ok":["sn#key#remark#carnum","316500011#abcdefgh#快餐前台"],"no":["316500012#abcdefgh#快餐前台#13688889999 (错误:识别码不正确)"]},"serverExecutedTime":3} + * 错误:{"msg":"参数错误 : 该帐号未注册.","ret":-2,"data":null,"serverExecutedTime":37} + */ + public static String updatePrinter(String snlist,String name){ + String URL = commonInfoService.findOne(325).getValue(); + String USER = commonInfoService.findOne(326).getValue(); + String UKEY = commonInfoService.findOne(327).getValue(); + //通过POST请求,发送打印信息到服务器 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(30000)//读取超时 + .setConnectTimeout(30000)//连接超时 + .build(); + + CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + + HttpPost post = new HttpPost(URL); + List nvps = new ArrayList(); + nvps.add(new BasicNameValuePair("user",USER)); + String STIME = String.valueOf(System.currentTimeMillis()/1000); + nvps.add(new BasicNameValuePair("stime",STIME)); + nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); + nvps.add(new BasicNameValuePair("apiname","Open_printerEdit"));//固定值,不需要修改 + nvps.add(new BasicNameValuePair("sn",snlist)); + nvps.add(new BasicNameValuePair("name",name)); + CloseableHttpResponse response = null; + String result = null; + try + { + post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); + response = httpClient.execute(post); + int statecode = response.getStatusLine().getStatusCode(); + if(statecode == 200){ + HttpEntity httpentity = response.getEntity(); + if (httpentity != null){ + result = EntityUtils.toString(httpentity); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + finally{ + try { + if(response!=null){ + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + post.abort(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * 删除打印机接口 + * @param snlist 提示:打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填),多台打印机请换行(\n)添加新打印机信息,每次最多100行(台)。 + * @return 正确例子:{"msg":"ok","ret":0,"data":{"ok":["sn#key#remark#carnum","316500011#abcdefgh#快餐前台"],"no":["316500012#abcdefgh#快餐前台#13688889999 (错误:识别码不正确)"]},"serverExecutedTime":3} + * 错误:{"msg":"参数错误 : 该帐号未注册.","ret":-2,"data":null,"serverExecutedTime":37} + */ + public static String deletePrinter(String snlist){ + try{ + String URL = commonInfoService.findOne(325).getValue(); + String USER = commonInfoService.findOne(326).getValue(); + String UKEY = commonInfoService.findOne(327).getValue(); + //通过POST请求,发送打印信息到服务器 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(30000)//读取超时 + .setConnectTimeout(30000)//连接超时 + .build(); + + CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + + HttpPost post = new HttpPost(URL); + List nvps = new ArrayList(); + nvps.add(new BasicNameValuePair("user",USER)); + String STIME = String.valueOf(System.currentTimeMillis()/1000); + nvps.add(new BasicNameValuePair("stime",STIME)); + nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); + nvps.add(new BasicNameValuePair("apiname","Open_printerDelList"));//固定值,不需要修改 + nvps.add(new BasicNameValuePair("snlist",snlist)); + + CloseableHttpResponse response = null; + String result = null; + try + { + post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); + response = httpClient.execute(post); + int statecode = response.getStatusLine().getStatusCode(); + if(statecode == 200){ + HttpEntity httpentity = response.getEntity(); + if (httpentity != null){ + result = EntityUtils.toString(httpentity); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + finally{ + try { + if(response!=null){ + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + post.abort(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + }catch (Exception e){ + e.printStackTrace(); + log.error("删除打印机异常:"+e.getMessage(),e); + } + return null; + } + + + /** + * 小票机打印订单接口 + * @return 成功:{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5} + * 失败:{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5} + */ + public static String print(String sn, String value, Orders tbOrder){ +// String name=commonInfoService.findOne(12).getValue(); +// String snlist = sn + "#" + value + "#" + name; +// String method = FeiYunUtils.addprinter(snlist); +// JSONObject jsonObject = JSON.parseObject(method); +// if (jsonObject != null) { +// log.error("添加打印机接口返回:"+jsonObject.toString()); +// } +// +// try{ +// //标签说明: +// //单标签: +// //"
"为换行,""为切刀指令(主动切纸,仅限切刀打印机使用才有效果) +// //""为打印LOGO指令(前提是预先在机器内置LOGO图片),""为钱箱或者外置音响指令 +// //成对标签: +// //""为居中放大一倍,""为放大一倍,""为居中,字体变高一倍 +// //字体变宽一倍,""为二维码,""为字体加粗,""为右对齐 +// //拼凑订单内容时可参考如下格式 +// //根据打印纸张的宽度,自行调整内容的格式,可参考下面的样例格式 +// +// content += "http://www.dzist.com";*/ +// StringBuilder stringBuilder=new StringBuilder(); +// stringBuilder.append("新订单
"); +// stringBuilder.append("类型:").append(tbOrder.getFinishTime()).append("
"); +// stringBuilder.append("订单号:").append(tbOrder.getOrderNum()).append("
"); +// stringBuilder.append("--------------------------------
"); +// stringBuilder.append("名称    单价  数量  金额 
"); +// stringBuilder.append("--------------------------------
"); +// stringBuilder.append("
"); +// stringBuilder.append(tbOrder.getTitle()); +// if(StringUtils.isNotEmpty(tbOrder.getDetailJson())){ +// stringBuilder.append("(").append(tbOrder.getDetailJson()).append(")"); +// } +// stringBuilder.append("
"); +// stringBuilder.append("      "); +// stringBuilder.append(tbOrder.getPrice()); +// if(tbOrder.getPrice().doubleValue()<10){ +// stringBuilder.append("  "); +// }else if(tbOrder.getPrice().doubleValue()<100){ +// stringBuilder.append("  "); +// }else{ +// stringBuilder.append("  "); +// } +// stringBuilder.append(tbOrder.getNumber()); +// stringBuilder.append("  "); +// stringBuilder.append(tbOrder.getPayMoney()).append("
"); +// stringBuilder.append("
"); +// stringBuilder.append("--------------------------------
"); +// String remark = tbOrder.getDescrition(); +// if(StringUtils.isEmpty(remark)){ +// remark=""; +// } +// stringBuilder.append("备注:").append(remark).append("
"); +// stringBuilder.append("--------------------------------
"); +// +// if(tbOrder.getCouponMoney()!=null && tbOrder.getCouponMoney().doubleValue()>0){ +// stringBuilder.append("优惠券:-").append(tbOrder.getCouponMoney()).append("元
"); +// } +// stringBuilder.append("支付金额:").append(tbOrder.getPayMoney()).append("元
"); +// stringBuilder.append("--------------------------------
"); +// stringBuilder.append("姓名:").append(tbOrder.getConsignee()).append("
"); +// stringBuilder.append("联系电话:").append(tbOrder.getMobile()).append("
"); +// stringBuilder.append("送货地点:").append(tbOrder.getProvinces()).append(tbOrder.getDetail()).append("
"); +// +// stringBuilder.append("订餐时间:").append(tbOrder.getPayTime()).append("
"); +// stringBuilder.append("预约时间:").append(tbOrder.getStartTime()).append("
"); +// stringBuilder.append("
").append("
").append("
"); +// stringBuilder.append("祝您用餐愉快
"); +// stringBuilder.append("
").append("
").append("
"); +// stringBuilder.append(""); +// String content=stringBuilder.toString(); +// //通过POST请求,发送打印信息到服务器 +// RequestConfig requestConfig = RequestConfig.custom() +// .setSocketTimeout(30000)//读取超时 +// .setConnectTimeout(30000)//连接超时 +// .build(); +// +// CloseableHttpClient httpClient = HttpClients.custom() +// .setDefaultRequestConfig(requestConfig) +// .build(); +// String URL = commonInfoService.findOne(325).getValue(); +// String USER = commonInfoService.findOne(326).getValue(); +// String UKEY = commonInfoService.findOne(327).getValue(); +// HttpPost post = new HttpPost(URL); +// List nvps = new ArrayList(); +// nvps.add(new BasicNameValuePair("user",USER)); +// String STIME = String.valueOf(System.currentTimeMillis()/1000); +// nvps.add(new BasicNameValuePair("stime",STIME)); +// nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); +// nvps.add(new BasicNameValuePair("apiname","Open_printMsg"));//固定值,不需要修改 +// nvps.add(new BasicNameValuePair("sn",sn)); +// nvps.add(new BasicNameValuePair("content",content)); +// nvps.add(new BasicNameValuePair("times","1"));//打印联数 +// +// CloseableHttpResponse response = null; +// String result = null; +// try +// { +// post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); +// response = httpClient.execute(post); +// int statecode = response.getStatusLine().getStatusCode(); +// if(statecode == 200){ +// HttpEntity httpentity = response.getEntity(); +// if (httpentity != null){ +// //服务器返回的JSON字符串,建议要当做日志记录起来 +// result = EntityUtils.toString(httpentity); +// } +// } +// } +// catch (Exception e) +// { +// e.printStackTrace(); +// } +// finally{ +// try { +// if(response!=null){ +// response.close(); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// try { +// post.abort(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// try { +// httpClient.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// log.error("打印返回值:"+result); +// return result; +// }catch (Exception e){ +// e.printStackTrace(); +// log.error("打印异常:"+e.getMessage(),e); +// } + return null; + } + + + /** + * 标签机专用打印订单接口 + * @param sn 打印机编号 + * @return 成功:{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5} + * 失败:{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5} + */ + private static String printLabelMsg(String sn){ + + String content; + content = "1";//设定打印时出纸和打印字体的方向,n 0 或 1,每次设备重启后都会初始化为 0 值设置,1:正向出纸,0:反向出纸, + content += "#001 五号桌 1/3可乐鸡翅张三先生 13800138000";//40mm宽度标签纸打印例子,打开注释调用标签打印接口打印 + + //通过POST请求,发送打印信息到服务器 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(30000)//读取超时 + .setConnectTimeout(30000)//连接超时 + .build(); + + CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + String URL = commonInfoService.findOne(325).getValue(); + String USER = commonInfoService.findOne(326).getValue(); + String UKEY = commonInfoService.findOne(327).getValue(); + HttpPost post = new HttpPost(URL); + List nvps = new ArrayList(); + nvps.add(new BasicNameValuePair("user",USER)); + String STIME = String.valueOf(System.currentTimeMillis()/1000); + nvps.add(new BasicNameValuePair("stime",STIME)); + nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); + nvps.add(new BasicNameValuePair("apiname","Open_printLabelMsg"));//固定值,不需要修改 + nvps.add(new BasicNameValuePair("sn",sn)); + nvps.add(new BasicNameValuePair("content",content)); + nvps.add(new BasicNameValuePair("times","1"));//打印联数 + + CloseableHttpResponse response = null; + String result = null; + try + { + post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); + response = httpClient.execute(post); + int statecode = response.getStatusLine().getStatusCode(); + if(statecode == 200){ + HttpEntity httpentity = response.getEntity(); + if (httpentity != null){ + //服务器返回的JSON字符串,建议要当做日志记录起来 + result = EntityUtils.toString(httpentity); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + finally{ + try { + if(response!=null){ + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + post.abort(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + + } + + + /** + * 查询某订单是否打印成功 + * @param orderid 订单id + * @return 成功:{"msg":"ok","ret":0,"data":true,"serverExecutedTime":2}//data:true为已打印,false为未打印 + * 失败:{"msg":"错误描述","ret":非0, "data":null,"serverExecutedTime":7} + */ + private static String queryOrderState(String orderid){ + + //通过POST请求,发送打印信息到服务器 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(30000)//读取超时 + .setConnectTimeout(30000)//连接超时 + .build(); + + CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + String URL = commonInfoService.findOne(325).getValue(); + String USER = commonInfoService.findOne(326).getValue(); + String UKEY = commonInfoService.findOne(327).getValue(); + HttpPost post = new HttpPost(URL); + List nvps = new ArrayList(); + nvps.add(new BasicNameValuePair("user",USER)); + String STIME = String.valueOf(System.currentTimeMillis()/1000); + nvps.add(new BasicNameValuePair("stime",STIME)); + nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); + nvps.add(new BasicNameValuePair("apiname","Open_queryOrderState"));//固定值,不需要修改 + nvps.add(new BasicNameValuePair("orderid",orderid)); + + CloseableHttpResponse response = null; + String result = null; + try + { + post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); + response = httpClient.execute(post); + int statecode = response.getStatusLine().getStatusCode(); + if(statecode == 200){ + HttpEntity httpentity = response.getEntity(); + if (httpentity != null){ + //服务器返回 + result = EntityUtils.toString(httpentity); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + finally{ + try { + if(response!=null){ + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + post.abort(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + + } + + + /** + * 查询指定打印机某天的订单详情 + * @param sn 打印机编号 + * @param strdate 时间 "yyyy-MM-dd" + * @return 成功:{"msg":"ok","ret":0,"data":{"print":6,"waiting":1},"serverExecutedTime":9}//print已打印,waiting为打印 + * 失败:{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5} + */ + private static String queryOrderInfoByDate(String sn,String strdate){ + + //通过POST请求,发送打印信息到服务器 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(30000)//读取超时 + .setConnectTimeout(30000)//连接超时 + .build(); + + CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + String URL = commonInfoService.findOne(325).getValue(); + String USER = commonInfoService.findOne(326).getValue(); + String UKEY = commonInfoService.findOne(327).getValue(); + HttpPost post = new HttpPost(URL); + List nvps = new ArrayList(); + nvps.add(new BasicNameValuePair("user",USER)); + String STIME = String.valueOf(System.currentTimeMillis()/1000); + nvps.add(new BasicNameValuePair("stime",STIME)); + nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); + nvps.add(new BasicNameValuePair("apiname","Open_queryOrderInfoByDate"));//固定值,不需要修改 + nvps.add(new BasicNameValuePair("sn",sn)); + nvps.add(new BasicNameValuePair("date",strdate));//yyyy-MM-dd格式 + + CloseableHttpResponse response = null; + String result = null; + try + { + post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); + response = httpClient.execute(post); + int statecode = response.getStatusLine().getStatusCode(); + if(statecode == 200){ + HttpEntity httpentity = response.getEntity(); + if (httpentity != null){ + //服务器返回 + result = EntityUtils.toString(httpentity); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + finally{ + try { + if(response!=null){ + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + post.abort(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + + } + + + /** + * 查询打印机的状态 + * @param sn 打印机编号 + * @return 成功:{"msg":"ok","ret":0,"data":"状态","serverExecutedTime":4} + * 失败:{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5} + */ + private static String queryPrinterStatus(String sn){ + + //通过POST请求,发送打印信息到服务器 + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(30000)//读取超时 + .setConnectTimeout(30000)//连接超时 + .build(); + + CloseableHttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + String URL = commonInfoService.findOne(325).getValue(); + String USER = commonInfoService.findOne(326).getValue(); + String UKEY = commonInfoService.findOne(327).getValue(); + HttpPost post = new HttpPost(URL); + List nvps = new ArrayList(); + nvps.add(new BasicNameValuePair("user",USER)); + String STIME = String.valueOf(System.currentTimeMillis()/1000); + nvps.add(new BasicNameValuePair("stime",STIME)); + nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME))); + nvps.add(new BasicNameValuePair("apiname","Open_queryPrinterStatus"));//固定值,不需要修改 + nvps.add(new BasicNameValuePair("sn",sn)); + + CloseableHttpResponse response = null; + String result = null; + try + { + post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); + response = httpClient.execute(post); + int statecode = response.getStatusLine().getStatusCode(); + if(statecode == 200){ + HttpEntity httpentity = response.getEntity(); + if (httpentity != null){ + //服务器返回 + result = EntityUtils.toString(httpentity); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + finally{ + try { + if(response!=null){ + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + post.abort(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + + } + + + //生成签名字符串 + private static String signature(String USER,String UKEY,String STIME){ + String s = DigestUtils.sha1Hex(USER+UKEY+STIME); + return s; + } + + + +} diff --git a/src/main/java/com/sqx/modules/utils/fieYun/model/OrderForm.java b/src/main/java/com/sqx/modules/utils/fieYun/model/OrderForm.java new file mode 100644 index 0000000..84c5eff --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/fieYun/model/OrderForm.java @@ -0,0 +1,40 @@ +package com.sqx.modules.utils.fieYun.model; + +import lombok.Data; + +@Data +public class OrderForm { + + private String userPhone; + + private String money; + + private String brandName; + + private String sn; + + private String orderNo; + + private String payTime; + + private String oilType; + + private String oilGun; + + private String oilPrice; + + private String oilNum; + + private String orderMoney; + + private String cashierName; + + private String startTime; + + private String endTime; + + private String totalNo; + + private String totalAmount; + +} diff --git a/src/main/java/com/sqx/modules/utils/wx/SignType.java b/src/main/java/com/sqx/modules/utils/wx/SignType.java new file mode 100644 index 0000000..df3b237 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/wx/SignType.java @@ -0,0 +1,30 @@ +package com.sqx.modules.utils.wx; + +/** + * @author fang + * @date 2020/12/10 + */ +public enum SignType { + /** + * HMAC-SHA256 加密 + */ + HMACSHA256("HMAC-SHA256"), + /** + * MD5 加密 + */ + MD5("MD5"), + /** + * RSA + */ + RSA("RSA"); + + SignType(String type) { + this.type = type; + } + + private final String type; + + public String getType() { + return type; + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/wx/WeChatPayRequest.java b/src/main/java/com/sqx/modules/utils/wx/WeChatPayRequest.java new file mode 100644 index 0000000..5eb699b --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/wx/WeChatPayRequest.java @@ -0,0 +1,111 @@ +package com.sqx.modules.utils.wx; + +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.DefaultHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.security.SecureRandom; + +/** + * @author fang + * @date 2020/12/10 + */ +@Slf4j +public class WeChatPayRequest { + + private static int socketTimeout = 10000;// 连接超时时间,默认10秒 + private static int connectTimeout = 30000;// 传输超时时间,默认30秒 + + /** + * 向微信发送请求 + * @param data + * @param useCert 是否使用证书 + * @return + * @throws Exception + */ + public String request(String currentPath,final String url, String data, boolean useCert,String mchId) throws Exception { + BasicHttpClientConnectionManager connManager; + if (useCert) { + // 证书 + // 证书密码,默认为商户ID + String key = mchId; + // 指定读取证书格式为PKCS12 + KeyStore ks = KeyStore.getInstance("PKCS12"); + + // 读取本机存放的PKCS12证书文件 + log.info("路径:{}", currentPath); + FileInputStream instream = new FileInputStream(new File(currentPath)); + + ks.load(instream, key.toCharArray()); + + // 实例化密钥库 & 初始化密钥工厂 + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, key.toCharArray()); + + // 创建 SSLContext + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(kmf.getKeyManagers(), null, new SecureRandom()); + + SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( + sslContext, + new String[]{"TLSv1"}, + null, + new DefaultHostnameVerifier()); + + connManager = new BasicHttpClientConnectionManager( + RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslConnectionSocketFactory) + .build(), + null, + null, + null + ); + } + else { + connManager = new BasicHttpClientConnectionManager( + RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", SSLConnectionSocketFactory.getSocketFactory()) + .build(), + null, + null, + null + ); + } + + org.apache.http.client.HttpClient httpClient = HttpClientBuilder.create() + .setConnectionManager(connManager) + .build(); + + HttpPost httpPost = new HttpPost(url); + + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build(); + httpPost.setConfig(requestConfig); + + StringEntity postEntity = new StringEntity(data, "UTF-8"); + httpPost.addHeader("Content-Type", "text/xml"); + httpPost.setEntity(postEntity); + + HttpResponse httpResponse = httpClient.execute(httpPost); + HttpEntity httpEntity = httpResponse.getEntity(); + return EntityUtils.toString(httpEntity, "UTF-8"); + + } +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/wx/WxPay.java b/src/main/java/com/sqx/modules/utils/wx/WxPay.java new file mode 100644 index 0000000..105ab86 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/wx/WxPay.java @@ -0,0 +1,75 @@ +package com.sqx.modules.utils.wx; + +import lombok.Data; + +/** + * @author fang + * @date 2020/12/10 + */ +@Data +public class WxPay { + + /** + * 与商户号关联应用(如微信公众号/小程序)的APPID + */ + private String mch_appid; + + /** + * 微信支付分配的商户号 + */ + private String mchid; + + /** + * 微信支付分配的终端设备号 + */ + private String device_info; + + /** + * 随机字符串,不长于32位 + */ + private String nonce_str; + + /** + * 签名 + */ + private String sign; + + /** + * 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有其他字符) + */ + private String partner_trade_no; + + /** + * 商户appid下,某用户的openid + */ + private String openid; + + /** + * NO_CHECK:不校验真实姓名 FORCE_CHECK:强校验真实姓名 + */ + private String check_name; + + /** + * 收款用户真实姓名。 + * 强校验必填项 + */ + private String re_user_name; + + /** + * 企业付款金额,单位为分 + */ + private Integer amount; + + + /** + * 企业付款备注 + */ + private String desc; + + /** + * 发起者IP地址+该IP可传用户端或者服务端的IP。 + */ + private String spbill_create_ip; + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/wx/WxPayUtils.java b/src/main/java/com/sqx/modules/utils/wx/WxPayUtils.java new file mode 100644 index 0000000..1e811f9 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/wx/WxPayUtils.java @@ -0,0 +1,100 @@ +package com.sqx.modules.utils.wx; + +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.crypto.SecureUtil; +import cn.hutool.crypto.digest.HmacAlgorithm; + +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author fang + * @date 2020/12/10 + */ +public class WxPayUtils { + + private static final String FIELD_SIGN = "sign"; + + public static final String WX_COM_DO_TRANS_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; + + /** + * 创建签名 + * @param map 方法 + * @param paterNerkey api密钥 + * @return + */ + public static String createSign(Map map, String paterNerkey) { + return createSign(map, paterNerkey, SignType.MD5); + } + + public static String createSign(Map map, String partnerKey, SignType signType) { + map.remove(FIELD_SIGN); + + String sign = createLinkString(map, "&"); + + String SignTemp = sign += "&key=" + partnerKey; + + if (signType == SignType.MD5) { + return md5(SignTemp).toUpperCase(); + } else { + return hmacSha256(SignTemp, partnerKey).toUpperCase(); + } + + } + + /** + * 生成MD5字符串 + * SecureUtil 来自 hutool + * @param data 数据 + * @return MD5字符串 + */ + public static String md5(String data) { + return SecureUtil.md5(data); + } + + /** + * 生成16进制的 sha256 字符串 + * SecureUtil 来自 hutool + * @param data 数据 + * @param key 密钥 + * @return sha256 字符串 + */ + public static String hmacSha256(String data, String key) { + return SecureUtil.hmac(HmacAlgorithm.HmacSHA256, key).digestHex(data, CharsetUtil.UTF_8); + } + + /** + * 排序并拼接 + * @param map 需要排序并拼接的map + * @param delimiter 拼接符 + * @return 拼接字符串 + */ + public static String createLinkString(Map map, String delimiter) { + List keys = new ArrayList<>(map.keySet()); + Collections.sort(keys); + + String sign = keys.stream() + .filter(k -> !Objects.isNull(map.get(k))) + .map(key -> { + return key + "=" + map.get(key).toString(); + }) + .collect(Collectors.joining(delimiter)); + + return sign; + } + + + public static String generateNonceStr() { + return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32); + } + + public static String getGeneralOrder(){ + Date date=new Date(); + String newString = String.format("%0"+4+"d", (int)((Math.random()*9+1)*1000)); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + String format = sdf.format(date); + return format+newString; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/wx/WxResult.java b/src/main/java/com/sqx/modules/utils/wx/WxResult.java new file mode 100644 index 0000000..e6175d2 --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/wx/WxResult.java @@ -0,0 +1,73 @@ +package com.sqx.modules.utils.wx; + +import lombok.Data; + +/** + * @author fang + * @date 2020/12/10 + */ +@Data +public class WxResult { + + /** + * 返回状态码 + */ + private String return_code; + + /** + * 返回信息 + */ + private String return_msg; + + /** + * 商户appid + */ + private String mch_appid; + + /** + * 商户号 + */ + private String mchid; + + /** + * 设备号 + */ + private String device_info; + + /** + * 随机字符串 + */ + private String nonce_str; + + /** + * 业务结果 + */ + private String result_code; + + /** + * 错误代码 + */ + private String err_code; + + /** + * 错误代码描述 + */ + private String err_code_des; + + /** + * 商户订单号 + */ + private String partner_trade_no; + + /** + * 微信付款单号 + */ + private String payment_no; + + /** + * 付款成功时间 + */ + private String payment_time; + + +} \ No newline at end of file diff --git a/src/main/java/com/sqx/modules/utils/wx/XmlUtil.java b/src/main/java/com/sqx/modules/utils/wx/XmlUtil.java new file mode 100644 index 0000000..a0f4c2c --- /dev/null +++ b/src/main/java/com/sqx/modules/utils/wx/XmlUtil.java @@ -0,0 +1,53 @@ +package com.sqx.modules.utils.wx; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.xml.DomDriver; +import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer; +import com.thoughtworks.xstream.mapper.MapperWrapper; + +/** + * @author fang + * @date 2020/12/10 + */ +public class XmlUtil { + + // xml转java对象 + public static T xmlToBean(String xml, Class clazz) { + XStream xstream = new XStream() { + @Override + protected MapperWrapper wrapMapper(MapperWrapper next) { + return new MapperWrapper(next) { + @Override + public boolean shouldSerializeMember(Class definedIn, String fieldName) { + if (definedIn == Object.class) { + try { + return this.realClass(fieldName) != null; + } catch (Exception e) { + return false; + } + } else { + return super.shouldSerializeMember(definedIn, fieldName); + } + } + }; + } + }; + + XStream.setupDefaultSecurity(xstream); + xstream.autodetectAnnotations(true); + xstream.alias("xml", clazz); + xstream.allowTypes(new Class[] { clazz }); + + return (T) xstream.fromXML(xml); + } + + // java对象转xml + public static String beanToXml(T t, Class clazz) { + XStream xstream = new XStream(new DomDriver("UTF-8",new XmlFriendlyReplacer("_-", "_"))); + XStream.setupDefaultSecurity(xstream); + xstream.autodetectAnnotations(true); + xstream.alias("xml", clazz); + xstream.allowTypes(new Class[] { clazz }); + return xstream.toXML(t); + } +} \ No newline at end of file diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..cdea09f --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,35 @@ +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + druid: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://127.0.0.1:3308/taotao?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT + username: root + password: abc123 + initial-size: 10 + max-active: 100 + min-idle: 10 + max-wait: 60000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + #Oracle需要打开注释 + #validation-query: SELECT 1 FROM DUAL + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: true + url-pattern: /druid/* + #login-username: admin + #login-password: admin + filter: + stat: + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: false + wall: + config: + multi-statement-allow: true + diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..2e8b14d --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,35 @@ +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + druid: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://127.0.0.1:3306/songshui?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT + username: root + password: 123456 + initial-size: 10 + max-active: 100 + min-idle: 10 + max-wait: 60000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + #Oracle需要打开注释 + #validation-query: SELECT 1 FROM DUAL + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: true + url-pattern: /druid/* + #login-username: admin + #login-password: admin + filter: + stat: + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: false + wall: + config: + multi-statement-allow: true + diff --git a/src/main/resources/application-test.yml b/src/main/resources/application-test.yml new file mode 100644 index 0000000..2e8b14d --- /dev/null +++ b/src/main/resources/application-test.yml @@ -0,0 +1,35 @@ +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + druid: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://127.0.0.1:3306/songshui?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT + username: root + password: 123456 + initial-size: 10 + max-active: 100 + min-idle: 10 + max-wait: 60000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + #Oracle需要打开注释 + #validation-query: SELECT 1 FROM DUAL + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: true + url-pattern: /druid/* + #login-username: admin + #login-password: admin + filter: + stat: + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: false + wall: + config: + multi-statement-allow: true + diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..4239262 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,88 @@ +logging: + file: + name: logs/songshui.log +# Tomcat +server: + tomcat: + uri-encoding: UTF-8 + max-threads: 1000 + min-spare-threads: 30 + connection-timeout: 5000ms + port: 8964 + + servlet: + context-path: /sqx_fast + +spring: + main: + allow-bean-definition-overriding: true + allow-circular-references: true + # 环境 dev|test|prod + profiles: + active: dev + # jackson时间格式化 + jackson: + time-zone: GMT+8 + date-format: yyyy-MM-dd HH:mm:ss + servlet: + multipart: + max-file-size: 10240MB + max-request-size: 10240MB + enabled: true + redis: + open: false # 是否开启redis缓存 true开启 false关闭 + database: 0 + host: localhost + port: 6379 + password: root # 密码(默认为空) + timeout: 6000ms # 连接超时时长(毫秒) + jedis: + pool: + max-active: 1000 # 连接池最大连接数(使用负值表示没有限制) + max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) + max-idle: 10 # 连接池中的最大空闲连接 + min-idle: 5 # 连接池中的最小空闲连接 + mvc: + throw-exception-if-no-handler-found: true + pathmatch: + matching-strategy: ant_path_matcher +# resources: +# add-mappings: false + + +#mybatis +mybatis-plus: + mapper-locations: classpath*:/mapper/**/*.xml + #实体扫描,多个package用逗号或者分号分隔 + typeAliasesPackage: com.sqx.modules.*.entity + global-config: + #数据库相关配置 + db-config: + #主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID"; + id-type: AUTO + logic-delete-value: -1 + logic-not-delete-value: 0 + insert-strategy: not_empty + update-strategy: not_empty + select-strategy: not_empty + banner: false + #原生配置 + configuration: + map-underscore-to-camel-case: true + cache-enabled: false + call-setters-on-nulls: true + jdbc-type-for-null: 'null' + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + +sqx: + redis: + open: false + shiro: + redis: false + # APP模块,是通过jwt认证的,如果要使用APP模块,则需要修改【加密秘钥】 + jwt: + # 加密秘钥 + secret: f4e2e52034348f86b67cde581c0f9eb5 + # token有效时长,7天,单位秒 + expire: 2592000 + header: token \ No newline at end of file diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 0000000..edfe5fe --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,23 @@ + +//////////////////////////////////////////////////////////////////// +// _ooOoo_ // +// o8888888o // +// 88" . "88 // +// (| ^_^ |) // +// O\ = /O // +// ____/`---'\____ // +// .' \\| |// `. // +// / \\||| : |||// \ // +// / _||||| -:- |||||- \ // +// | | \\\ - /// | | // +// | \_| ''\---/'' | | // +// \ .-\__ `-` ___/-. / // +// ___`. .' /--.--\ `. . ___ // +// ."" '< `.___\_<|>_/___.' >'"". // +// | | : `- \`.;`\ _ /`;.`/ - ` : | | // +// \ \ `-. \_ __\ /__ _/ .-` / / // +// ========`-.____`-.___\_____/___.-`____.-'======== // +// `=---=' // +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // +// 佛祖保佑 永不宕机 永无BUG // +//////////////////////////////////////////////////////////////////// diff --git a/src/main/resources/mapper/app/AddressDao.xml b/src/main/resources/mapper/app/AddressDao.xml new file mode 100644 index 0000000..8e7bf6f --- /dev/null +++ b/src/main/resources/mapper/app/AddressDao.xml @@ -0,0 +1,12 @@ + + + + + + + + update address set is_default=0 where user_id=#{userId} + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/AppDao.xml b/src/main/resources/mapper/app/AppDao.xml new file mode 100644 index 0000000..784c299 --- /dev/null +++ b/src/main/resources/mapper/app/AppDao.xml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/CarDao.xml b/src/main/resources/mapper/app/CarDao.xml new file mode 100644 index 0000000..6f1231b --- /dev/null +++ b/src/main/resources/mapper/app/CarDao.xml @@ -0,0 +1,22 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/CityAgencyDao.xml b/src/main/resources/mapper/app/CityAgencyDao.xml new file mode 100644 index 0000000..1e23df6 --- /dev/null +++ b/src/main/resources/mapper/app/CityAgencyDao.xml @@ -0,0 +1,22 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/MsgDao.xml b/src/main/resources/mapper/app/MsgDao.xml new file mode 100644 index 0000000..cb6980b --- /dev/null +++ b/src/main/resources/mapper/app/MsgDao.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/UserBrowseDao.xml b/src/main/resources/mapper/app/UserBrowseDao.xml new file mode 100644 index 0000000..73a533f --- /dev/null +++ b/src/main/resources/mapper/app/UserBrowseDao.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/UserCertificationDao.xml b/src/main/resources/mapper/app/UserCertificationDao.xml new file mode 100644 index 0000000..c054e4a --- /dev/null +++ b/src/main/resources/mapper/app/UserCertificationDao.xml @@ -0,0 +1,32 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/UserDao.xml b/src/main/resources/mapper/app/UserDao.xml new file mode 100644 index 0000000..9f8ed44 --- /dev/null +++ b/src/main/resources/mapper/app/UserDao.xml @@ -0,0 +1,428 @@ + + + + + + update tb_user + set province=#{userEntity.province}, + city=#{userEntity.city}, + district=#{userEntity.district} + where user_id = #{userEntity.userId} + + + + + + + + + + + + + INSERT INTO tb_user + + + user_name, + + + phone, + + + avatar, + + + sex, + + + age, + + + open_id, + + + wx_open_id, + + + password, + + + create_time, + + + update_time, + + + apple_id, + + + sys_phone, + + + status, + + + platform, + + + jifen, + + + invitation_code, + + + inviter_code, + + + clientid, + + + zhi_fu_bao_name, + + + zhi_fu_bao + + + + + #{userName}, + + + #{phone}, + + + #{avatar}, + + + #{sex}, + + + #{age}, + + + #{openId}, + + + #{wxOpenId}, + + + #{password}, + + + #{createTime}, + + + #{updateTime}, + + + #{appleId}, + + + #{sysPhone}, + + + #{status}, + + + #{platform}, + + + #{jifen}, + + + #{invitationCode}, + + + #{inviterCode}, + + + #{clientid}, + + + #{zhiFuBaoName}, + + + #{zhiFuBao} + + + + + + + + + + update tb_user + set laundry_id = null + where laundry_id = #{laundryId} + + + + update tb_user u + set laundry_id = null + where u.user_id = #{userId} + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/UserFollowDao.xml b/src/main/resources/mapper/app/UserFollowDao.xml new file mode 100644 index 0000000..c472ccc --- /dev/null +++ b/src/main/resources/mapper/app/UserFollowDao.xml @@ -0,0 +1,54 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/UserMoneyDao.xml b/src/main/resources/mapper/app/UserMoneyDao.xml new file mode 100644 index 0000000..4a202c3 --- /dev/null +++ b/src/main/resources/mapper/app/UserMoneyDao.xml @@ -0,0 +1,32 @@ + + + + + + + update user_money set + + money=money+#{money} + + + money=money-#{money} + + where user_id=#{userId} + + + + update user_money set + + safety_money=safety_money+#{money} + + + safety_money=safety_money-#{money} + + where user_id=#{userId} + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/UserMoneyDetailsDao.xml b/src/main/resources/mapper/app/UserMoneyDetailsDao.xml new file mode 100644 index 0000000..598acaf --- /dev/null +++ b/src/main/resources/mapper/app/UserMoneyDetailsDao.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/app/UserVisitorDao.xml b/src/main/resources/mapper/app/UserVisitorDao.xml new file mode 100644 index 0000000..80cfe8a --- /dev/null +++ b/src/main/resources/mapper/app/UserVisitorDao.xml @@ -0,0 +1,32 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/banner/ActivityDao.xml b/src/main/resources/mapper/banner/ActivityDao.xml new file mode 100644 index 0000000..1426bb4 --- /dev/null +++ b/src/main/resources/mapper/banner/ActivityDao.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/banner/BannerDao.xml b/src/main/resources/mapper/banner/BannerDao.xml new file mode 100644 index 0000000..baebc4b --- /dev/null +++ b/src/main/resources/mapper/banner/BannerDao.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/chat/ChatContentDao.xml b/src/main/resources/mapper/chat/ChatContentDao.xml new file mode 100644 index 0000000..d5ceb8b --- /dev/null +++ b/src/main/resources/mapper/chat/ChatContentDao.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + update chat_content + set status=1 + where user_id!=#{userId} + and chat_conversation_id=#{chatConversationId} + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/chat/ChatConversationDao.xml b/src/main/resources/mapper/chat/ChatConversationDao.xml new file mode 100644 index 0000000..5420e7c --- /dev/null +++ b/src/main/resources/mapper/chat/ChatConversationDao.xml @@ -0,0 +1,73 @@ + + + + + + + + + INSERT INTO chat_conversation + + + user_id, + + + focused_user_id, + + + status, + + + create_time, + + + update_time, + + + remark + + + + + #{userId}, + + + #{focusedUserId}, + + + #{status}, + + + #{createTime}, + + + #{updateTime}, + + + #{remark} + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/common/CommonInfoDao.xml b/src/main/resources/mapper/common/CommonInfoDao.xml new file mode 100644 index 0000000..320abee --- /dev/null +++ b/src/main/resources/mapper/common/CommonInfoDao.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/integra/UserIntegralDetailsMapper.xml b/src/main/resources/mapper/integra/UserIntegralDetailsMapper.xml new file mode 100644 index 0000000..12150a4 --- /dev/null +++ b/src/main/resources/mapper/integra/UserIntegralDetailsMapper.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/integra/UserIntegralMapper.xml b/src/main/resources/mapper/integra/UserIntegralMapper.xml new file mode 100644 index 0000000..75a754f --- /dev/null +++ b/src/main/resources/mapper/integra/UserIntegralMapper.xml @@ -0,0 +1,16 @@ + + + + + + update user_integral set + integral_num = integral_num+#{num} + where user_id = #{userId} + + + + update user_integral set + integral_num = integral_num-#{needIntegral} + where user_id = #{userId} + + \ No newline at end of file diff --git a/src/main/resources/mapper/invite/InviteDao.xml b/src/main/resources/mapper/invite/InviteDao.xml new file mode 100644 index 0000000..e1fdede --- /dev/null +++ b/src/main/resources/mapper/invite/InviteDao.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/invite/InviteMoneyDao.xml b/src/main/resources/mapper/invite/InviteMoneyDao.xml new file mode 100644 index 0000000..f0ad518 --- /dev/null +++ b/src/main/resources/mapper/invite/InviteMoneyDao.xml @@ -0,0 +1,26 @@ + + + + + + + + + update invite_money set money=money+#{money},money_sum=money_sum+#{money} where user_id=#{userId} + + + + update invite_money set + + cash_out=cash_out-#{money},money=money+#{money} + + + cash_out=cash_out+#{money},money=money-#{money} + + where user_id=#{userId} + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/job/ScheduleJobDao.xml b/src/main/resources/mapper/job/ScheduleJobDao.xml new file mode 100644 index 0000000..7def400 --- /dev/null +++ b/src/main/resources/mapper/job/ScheduleJobDao.xml @@ -0,0 +1,14 @@ + + + + + + + + update schedule_job set status = #{status} where job_id in + + #{jobId} + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/job/ScheduleJobLogDao.xml b/src/main/resources/mapper/job/ScheduleJobLogDao.xml new file mode 100644 index 0000000..8081592 --- /dev/null +++ b/src/main/resources/mapper/job/ScheduleJobLogDao.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/message/ActivityMessageInfoDao.xml b/src/main/resources/mapper/message/ActivityMessageInfoDao.xml new file mode 100644 index 0000000..9ef48de --- /dev/null +++ b/src/main/resources/mapper/message/ActivityMessageInfoDao.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + update activity_message_info s set s.state=#{state} where s.id=#{id} + + + + update activity_message_info s set s.send_state=#{state} where s.id=#{id} + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/message/MessageInfoDao.xml b/src/main/resources/mapper/message/MessageInfoDao.xml new file mode 100644 index 0000000..1425ad7 --- /dev/null +++ b/src/main/resources/mapper/message/MessageInfoDao.xml @@ -0,0 +1,14 @@ + + + + + + + update message_info s set s.is_see=2 where s.user_id=#{userId} and s.state=#{state} + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/orders/OrdersDao.xml b/src/main/resources/mapper/orders/OrdersDao.xml new file mode 100644 index 0000000..c8a26e2 --- /dev/null +++ b/src/main/resources/mapper/orders/OrdersDao.xml @@ -0,0 +1,903 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + update orders + set is_remind=1 + where order_taking_user_id = #{userId} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + update orders + set state=3 + where state = 0 + and date_format(date_add(create_time, interval #{time} minute), '%Y-%m-%d %H:%i:%S') <= + date_format(now(), '%Y-%m-%d %H:%i:%S') + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/oss/SysOssDao.xml b/src/main/resources/mapper/oss/SysOssDao.xml new file mode 100644 index 0000000..8b2feb3 --- /dev/null +++ b/src/main/resources/mapper/oss/SysOssDao.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/pay/CashDao.xml b/src/main/resources/mapper/pay/CashDao.xml new file mode 100644 index 0000000..ec695aa --- /dev/null +++ b/src/main/resources/mapper/pay/CashDao.xml @@ -0,0 +1,161 @@ + + + + + + + + + + + + + + + + + + + + + + + + update user_money set + + money=money+#{money} + + + money=money-#{money} + + where user_id=#{userId} + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/pay/PayDetailsDao.xml b/src/main/resources/mapper/pay/PayDetailsDao.xml new file mode 100644 index 0000000..b5be9a1 --- /dev/null +++ b/src/main/resources/mapper/pay/PayDetailsDao.xml @@ -0,0 +1,203 @@ + + + + + + + + + + + + + update pay_details + set `state`=#{state}, + pay_time=#{time}, + trade_no=#{tradeNo} + where id = #{id} + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/peratorsLog/peratorsLog.xml b/src/main/resources/mapper/peratorsLog/peratorsLog.xml new file mode 100644 index 0000000..c678470 --- /dev/null +++ b/src/main/resources/mapper/peratorsLog/peratorsLog.xml @@ -0,0 +1,24 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/search/AppSearchDao.xml b/src/main/resources/mapper/search/AppSearchDao.xml new file mode 100644 index 0000000..db3855e --- /dev/null +++ b/src/main/resources/mapper/search/AppSearchDao.xml @@ -0,0 +1,14 @@ + + + + + + + + + delete from `search` where user_id=#{userId} + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysConfigDao.xml b/src/main/resources/mapper/sys/SysConfigDao.xml new file mode 100644 index 0000000..dabb7c4 --- /dev/null +++ b/src/main/resources/mapper/sys/SysConfigDao.xml @@ -0,0 +1,15 @@ + + + + + + + update sys_config set param_value = #{paramValue} where param_key = #{paramKey} + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysDictDao.xml b/src/main/resources/mapper/sys/SysDictDao.xml new file mode 100644 index 0000000..09ba58a --- /dev/null +++ b/src/main/resources/mapper/sys/SysDictDao.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/main/resources/mapper/sys/SysLogDao.xml b/src/main/resources/mapper/sys/SysLogDao.xml new file mode 100644 index 0000000..048d81a --- /dev/null +++ b/src/main/resources/mapper/sys/SysLogDao.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysMenuDao.xml b/src/main/resources/mapper/sys/SysMenuDao.xml new file mode 100644 index 0000000..003d107 --- /dev/null +++ b/src/main/resources/mapper/sys/SysMenuDao.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysRoleDao.xml b/src/main/resources/mapper/sys/SysRoleDao.xml new file mode 100644 index 0000000..5b5f4dc --- /dev/null +++ b/src/main/resources/mapper/sys/SysRoleDao.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysRoleMenuDao.xml b/src/main/resources/mapper/sys/SysRoleMenuDao.xml new file mode 100644 index 0000000..3cece0a --- /dev/null +++ b/src/main/resources/mapper/sys/SysRoleMenuDao.xml @@ -0,0 +1,17 @@ + + + + + + + + + delete from sys_role_menu where role_id in + + #{roleId} + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysUserDao.xml b/src/main/resources/mapper/sys/SysUserDao.xml new file mode 100644 index 0000000..2999b6d --- /dev/null +++ b/src/main/resources/mapper/sys/SysUserDao.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysUserRoleDao.xml b/src/main/resources/mapper/sys/SysUserRoleDao.xml new file mode 100644 index 0000000..0ab4280 --- /dev/null +++ b/src/main/resources/mapper/sys/SysUserRoleDao.xml @@ -0,0 +1,16 @@ + + + + + + + delete from sys_user_role where role_id in + + #{roleId} + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/sys/SysUserTokenDao.xml b/src/main/resources/mapper/sys/SysUserTokenDao.xml new file mode 100644 index 0000000..d7f9db4 --- /dev/null +++ b/src/main/resources/mapper/sys/SysUserTokenDao.xml @@ -0,0 +1,9 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/taking/GoodsAttrMapper.xml b/src/main/resources/mapper/taking/GoodsAttrMapper.xml new file mode 100644 index 0000000..a0bcc4c --- /dev/null +++ b/src/main/resources/mapper/taking/GoodsAttrMapper.xml @@ -0,0 +1,17 @@ + + + + + + INSERT INTO goods_attr + + attr_name,goods_id,rule_id + + + #{attrName},#{goodsId},#{ruleId} + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/taking/GoodsRuleMapper.xml b/src/main/resources/mapper/taking/GoodsRuleMapper.xml new file mode 100644 index 0000000..d6b522f --- /dev/null +++ b/src/main/resources/mapper/taking/GoodsRuleMapper.xml @@ -0,0 +1,14 @@ + + + + + + INSERT INTO goods_rule (create_time, rule_name,game_id) values (#{createTime}, #{ruleName},#{gameId}) + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/taking/OrderTakingCommentDao.xml b/src/main/resources/mapper/taking/OrderTakingCommentDao.xml new file mode 100644 index 0000000..4c99713 --- /dev/null +++ b/src/main/resources/mapper/taking/OrderTakingCommentDao.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + DELETE + FROM comment_fabulous + WHERE id = #{id} + + + INSERT + comment_fabulous ( taking_comment_id, user_id ) + VALUES ( + #{commentId}, + #{userId} + ) + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/taking/OrderTakingDao.xml b/src/main/resources/mapper/taking/OrderTakingDao.xml new file mode 100644 index 0000000..5cd82b2 --- /dev/null +++ b/src/main/resources/mapper/taking/OrderTakingDao.xml @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + update order_taking + set status=2 + where user_id = #{userId} + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/task/HelpOrderDao.xml b/src/main/resources/mapper/task/HelpOrderDao.xml new file mode 100644 index 0000000..669476f --- /dev/null +++ b/src/main/resources/mapper/task/HelpOrderDao.xml @@ -0,0 +1,106 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/task/HelpTakeDao.xml b/src/main/resources/mapper/task/HelpTakeDao.xml new file mode 100644 index 0000000..ddfd466 --- /dev/null +++ b/src/main/resources/mapper/task/HelpTakeDao.xml @@ -0,0 +1,152 @@ + + + + + + + insert into help_take + + order_id, + user_id, + money, + status, + create_time, + end_time, + + + #{orderId}, + #{userId}, + #{money}, + #{status}, + #{createTime}, + #{endTime}, + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/tickets/Tickets.xml b/src/main/resources/mapper/tickets/Tickets.xml new file mode 100644 index 0000000..a616a2b --- /dev/null +++ b/src/main/resources/mapper/tickets/Tickets.xml @@ -0,0 +1,43 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/ticketsGiveRecord/TicketsGiveRecord.xml b/src/main/resources/mapper/ticketsGiveRecord/TicketsGiveRecord.xml new file mode 100644 index 0000000..7e7e37c --- /dev/null +++ b/src/main/resources/mapper/ticketsGiveRecord/TicketsGiveRecord.xml @@ -0,0 +1,28 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/ticketsUserRole/TicketsUserRoleDao.xml b/src/main/resources/mapper/ticketsUserRole/TicketsUserRoleDao.xml new file mode 100644 index 0000000..14e7da5 --- /dev/null +++ b/src/main/resources/mapper/ticketsUserRole/TicketsUserRoleDao.xml @@ -0,0 +1,42 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/swagger/css/print.css b/src/main/resources/static/swagger/css/print.css new file mode 100644 index 0000000..f2e8446 --- /dev/null +++ b/src/main/resources/static/swagger/css/print.css @@ -0,0 +1 @@ +.swagger-section pre code{display:block;padding:.5em;background:#f0f0f0}.swagger-section pre .clojure .built_in,.swagger-section pre .lisp .title,.swagger-section pre .nginx .title,.swagger-section pre .subst,.swagger-section pre .tag .title,.swagger-section pre code{color:#000}.swagger-section pre .addition,.swagger-section pre .aggregate,.swagger-section pre .apache .cbracket,.swagger-section pre .apache .tag,.swagger-section pre .bash .variable,.swagger-section pre .constant,.swagger-section pre .django .variable,.swagger-section pre .erlang_repl .function_or_atom,.swagger-section pre .flow,.swagger-section pre .markdown .header,.swagger-section pre .parent,.swagger-section pre .preprocessor,.swagger-section pre .ruby .symbol,.swagger-section pre .ruby .symbol .string,.swagger-section pre .rules .value,.swagger-section pre .rules .value .number,.swagger-section pre .smalltalk .class,.swagger-section pre .stream,.swagger-section pre .string,.swagger-section pre .tag .value,.swagger-section pre .template_tag,.swagger-section pre .tex .command,.swagger-section pre .tex .special,.swagger-section pre .title{color:#800}.swagger-section pre .annotation,.swagger-section pre .chunk,.swagger-section pre .comment,.swagger-section pre .diff .header,.swagger-section pre .markdown .blockquote,.swagger-section pre .template_comment{color:#888}.swagger-section pre .change,.swagger-section pre .date,.swagger-section pre .go .constant,.swagger-section pre .literal,.swagger-section pre .markdown .bullet,.swagger-section pre .markdown .link_url,.swagger-section pre .number,.swagger-section pre .regexp,.swagger-section pre .smalltalk .char,.swagger-section pre .smalltalk .symbol{color:#080}.swagger-section pre .apache .sqbracket,.swagger-section pre .array,.swagger-section pre .attr_selector,.swagger-section pre .clojure .attribute,.swagger-section pre .coffeescript .property,.swagger-section pre .decorator,.swagger-section pre .deletion,.swagger-section pre .doctype,.swagger-section pre .envvar,.swagger-section pre .erlang_repl .reserved,.swagger-section pre .filter .argument,.swagger-section pre .important,.swagger-section pre .javadoc,.swagger-section pre .label,.swagger-section pre .localvars,.swagger-section pre .markdown .link_label,.swagger-section pre .nginx .built_in,.swagger-section pre .pi,.swagger-section pre .prompt,.swagger-section pre .pseudo,.swagger-section pre .ruby .string,.swagger-section pre .shebang,.swagger-section pre .tex .formula,.swagger-section pre .vhdl .attribute{color:#88f}.swagger-section pre .aggregate,.swagger-section pre .apache .tag,.swagger-section pre .bash .variable,.swagger-section pre .built_in,.swagger-section pre .css .tag,.swagger-section pre .go .typename,.swagger-section pre .id,.swagger-section pre .javadoctag,.swagger-section pre .keyword,.swagger-section pre .markdown .strong,.swagger-section pre .phpdoc,.swagger-section pre .request,.swagger-section pre .smalltalk .class,.swagger-section pre .status,.swagger-section pre .tex .command,.swagger-section pre .title,.swagger-section pre .winutils,.swagger-section pre .yardoctag{font-weight:700}.swagger-section pre .markdown .emphasis{font-style:italic}.swagger-section pre .nginx .built_in{font-weight:400}.swagger-section pre .coffeescript .javascript,.swagger-section pre .javascript .xml,.swagger-section pre .tex .formula,.swagger-section pre .xml .cdata,.swagger-section pre .xml .css,.swagger-section pre .xml .javascript,.swagger-section pre .xml .vbscript{opacity:.5}.swagger-section .hljs{display:block;overflow-x:auto;padding:.5em;background:#f0f0f0}.swagger-section .hljs,.swagger-section .hljs-subst{color:#444}.swagger-section .hljs-attribute,.swagger-section .hljs-doctag,.swagger-section .hljs-keyword,.swagger-section .hljs-meta-keyword,.swagger-section .hljs-name,.swagger-section .hljs-selector-tag{font-weight:700}.swagger-section .hljs-addition,.swagger-section .hljs-built_in,.swagger-section .hljs-bullet,.swagger-section .hljs-code,.swagger-section .hljs-literal{color:#1f811f}.swagger-section .hljs-link,.swagger-section .hljs-regexp,.swagger-section .hljs-selector-attr,.swagger-section .hljs-selector-pseudo,.swagger-section .hljs-symbol,.swagger-section .hljs-template-variable,.swagger-section .hljs-variable{color:#bc6060}.swagger-section .hljs-deletion,.swagger-section .hljs-number,.swagger-section .hljs-quote,.swagger-section .hljs-selector-class,.swagger-section .hljs-selector-id,.swagger-section .hljs-string,.swagger-section .hljs-template-tag,.swagger-section .hljs-type{color:#800}.swagger-section .hljs-section,.swagger-section .hljs-title{color:#800;font-weight:700}.swagger-section .hljs-comment{color:#888}.swagger-section .hljs-meta{color:#2b6ea1}.swagger-section .hljs-emphasis{font-style:italic}.swagger-section .hljs-strong{font-weight:700}.swagger-section .swagger-ui-wrap{line-height:1;font-family:Droid Sans,sans-serif;min-width:760px;max-width:960px;margin-left:auto;margin-right:auto}.swagger-section .swagger-ui-wrap b,.swagger-section .swagger-ui-wrap strong{font-family:Droid Sans,sans-serif;font-weight:700}.swagger-section .swagger-ui-wrap blockquote,.swagger-section .swagger-ui-wrap q{quotes:none}.swagger-section .swagger-ui-wrap p{line-height:1.4em;padding:0 0 10px;color:#333}.swagger-section .swagger-ui-wrap blockquote:after,.swagger-section .swagger-ui-wrap blockquote:before,.swagger-section .swagger-ui-wrap q:after,.swagger-section .swagger-ui-wrap q:before{content:none}.swagger-section .swagger-ui-wrap .heading_with_menu h1,.swagger-section .swagger-ui-wrap .heading_with_menu h2,.swagger-section .swagger-ui-wrap .heading_with_menu h3,.swagger-section .swagger-ui-wrap .heading_with_menu h4,.swagger-section .swagger-ui-wrap .heading_with_menu h5,.swagger-section .swagger-ui-wrap .heading_with_menu h6{display:block;clear:none;float:left;-ms-box-sizing:border-box;box-sizing:border-box;width:60%}.swagger-section .swagger-ui-wrap table{border-collapse:collapse;border-spacing:0}.swagger-section .swagger-ui-wrap table thead tr th{padding:5px;font-size:.9em;color:#666;border-bottom:1px solid #999}.swagger-section .swagger-ui-wrap table tbody tr:last-child td{border-bottom:none}.swagger-section .swagger-ui-wrap table tbody tr.offset{background-color:#f0f0f0}.swagger-section .swagger-ui-wrap table tbody tr td{padding:6px;font-size:.9em;border-bottom:1px solid #ccc;vertical-align:top;line-height:1.3em}.swagger-section .swagger-ui-wrap ol{margin:0 0 10px;padding:0 0 0 18px;list-style-type:decimal}.swagger-section .swagger-ui-wrap ol li{padding:5px 0;font-size:.9em;color:#333}.swagger-section .swagger-ui-wrap ol,.swagger-section .swagger-ui-wrap ul{list-style:none}.swagger-section .swagger-ui-wrap h1 a,.swagger-section .swagger-ui-wrap h2 a,.swagger-section .swagger-ui-wrap h3 a,.swagger-section .swagger-ui-wrap h4 a,.swagger-section .swagger-ui-wrap h5 a,.swagger-section .swagger-ui-wrap h6 a{text-decoration:none}.swagger-section .swagger-ui-wrap h1 a:hover,.swagger-section .swagger-ui-wrap h2 a:hover,.swagger-section .swagger-ui-wrap h3 a:hover,.swagger-section .swagger-ui-wrap h4 a:hover,.swagger-section .swagger-ui-wrap h5 a:hover,.swagger-section .swagger-ui-wrap h6 a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap h1 span.divider,.swagger-section .swagger-ui-wrap h2 span.divider,.swagger-section .swagger-ui-wrap h3 span.divider,.swagger-section .swagger-ui-wrap h4 span.divider,.swagger-section .swagger-ui-wrap h5 span.divider,.swagger-section .swagger-ui-wrap h6 span.divider{color:#aaa}.swagger-section .swagger-ui-wrap a{color:#547f00}.swagger-section .swagger-ui-wrap a img{border:none}.swagger-section .swagger-ui-wrap article,.swagger-section .swagger-ui-wrap aside,.swagger-section .swagger-ui-wrap details,.swagger-section .swagger-ui-wrap figcaption,.swagger-section .swagger-ui-wrap figure,.swagger-section .swagger-ui-wrap footer,.swagger-section .swagger-ui-wrap header,.swagger-section .swagger-ui-wrap hgroup,.swagger-section .swagger-ui-wrap menu,.swagger-section .swagger-ui-wrap nav,.swagger-section .swagger-ui-wrap section,.swagger-section .swagger-ui-wrap summary{display:block}.swagger-section .swagger-ui-wrap pre{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;background-color:#fcf6db;border:1px solid #e5e0c6;padding:10px}.swagger-section .swagger-ui-wrap pre code{line-height:1.6em;background:none}.swagger-section .swagger-ui-wrap .content>.content-type>div>label{clear:both;display:block;color:#0f6ab4;font-size:1.1em;margin:0;padding:15px 0 5px}.swagger-section .swagger-ui-wrap .content pre{font-size:12px;margin-top:5px;padding:5px}.swagger-section .swagger-ui-wrap .icon-btn{cursor:pointer}.swagger-section .swagger-ui-wrap .info_title{padding-bottom:10px;font-weight:700;font-size:25px}.swagger-section .swagger-ui-wrap .footer{margin-top:20px}.swagger-section .swagger-ui-wrap div.big p,.swagger-section .swagger-ui-wrap p.big{font-size:1em;margin-bottom:10px}.swagger-section .swagger-ui-wrap form.fullwidth ol li.numeric input,.swagger-section .swagger-ui-wrap form.fullwidth ol li.string input,.swagger-section .swagger-ui-wrap form.fullwidth ol li.text textarea,.swagger-section .swagger-ui-wrap form.fullwidth ol li.url input{width:500px!important}.swagger-section .swagger-ui-wrap .info_license,.swagger-section .swagger-ui-wrap .info_tos{padding-bottom:5px}.swagger-section .swagger-ui-wrap .message-fail{color:#c00}.swagger-section .swagger-ui-wrap .info_email,.swagger-section .swagger-ui-wrap .info_name,.swagger-section .swagger-ui-wrap .info_url{padding-bottom:5px}.swagger-section .swagger-ui-wrap .info_description{padding-bottom:10px;font-size:15px}.swagger-section .swagger-ui-wrap .markdown ol li,.swagger-section .swagger-ui-wrap .markdown ul li{padding:3px 0;line-height:1.4em;color:#333}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input{display:block;padding:4px;width:auto;clear:both}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input.title,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input.title,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input.title{font-size:1.3em}.swagger-section .swagger-ui-wrap table.fullwidth{width:100%}.swagger-section .swagger-ui-wrap .model-signature{font-family:Droid Sans,sans-serif;font-size:1em;line-height:1.5em}.swagger-section .swagger-ui-wrap .model-signature .signature-nav a{text-decoration:none;color:#aaa}.swagger-section .swagger-ui-wrap .model-signature .signature-nav a:hover{text-decoration:underline;color:#000}.swagger-section .swagger-ui-wrap .model-signature .signature-nav .selected{color:#000;text-decoration:none}.swagger-section .swagger-ui-wrap .model-signature .propType{color:#55a}.swagger-section .swagger-ui-wrap .model-signature pre:hover{background-color:#ffd}.swagger-section .swagger-ui-wrap .model-signature pre{font-size:.85em;line-height:1.2em;overflow:auto;height:200px;resize:vertical;cursor:pointer}.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav{display:block;min-width:230px;margin:0;padding:0}.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li:last-child{padding-right:0;border-right:none}.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li{float:left;margin:0 5px 5px 0;padding:2px 5px 2px 0;border-right:1px solid #ddd}.swagger-section .swagger-ui-wrap .model-signature .propOpt{color:#555}.swagger-section .swagger-ui-wrap .model-signature .snippet small{font-size:.75em}.swagger-section .swagger-ui-wrap .model-signature .propOptKey{font-style:italic}.swagger-section .swagger-ui-wrap .model-signature .description .strong{font-weight:700;color:#000;font-size:.9em}.swagger-section .swagger-ui-wrap .model-signature .description div{font-size:.9em;line-height:1.5em;margin-left:1em}.swagger-section .swagger-ui-wrap .model-signature .description .stronger{font-weight:700;color:#000}.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper{border-spacing:0;position:absolute;background-color:#fff;border:1px solid #bbb;display:none;font-size:11px;max-width:400px;line-height:30px;color:#000;padding:5px;margin-left:10px}.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper th{text-align:center;background-color:#eee;border:1px solid #bbb;font-size:11px;color:#666;font-weight:700;padding:5px;line-height:15px}.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper .optionName{font-weight:700}.swagger-section .swagger-ui-wrap .model-signature .description .propDesc.markdown>p:first-child,.swagger-section .swagger-ui-wrap .model-signature .description .propDesc.markdown>p:last-child{display:inline}.swagger-section .swagger-ui-wrap .model-signature .description .propDesc.markdown>p:not(:first-child):before{display:block;content:''}.swagger-section .swagger-ui-wrap .model-signature .description span:last-of-type.propDesc.markdown>p:only-child{margin-right:-3px}.swagger-section .swagger-ui-wrap .model-signature .propName{font-weight:700}.swagger-section .swagger-ui-wrap .model-signature .signature-container{clear:both}.swagger-section .swagger-ui-wrap .body-textarea{width:300px;height:100px;border:1px solid #aaa}.swagger-section .swagger-ui-wrap .markdown li code,.swagger-section .swagger-ui-wrap .markdown p code{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;background-color:#f0f0f0;color:#000;padding:1px 3px}.swagger-section .swagger-ui-wrap .required{font-weight:700}.swagger-section .swagger-ui-wrap .editor_holder{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;font-size:.9em}.swagger-section .swagger-ui-wrap .editor_holder label{font-weight:400!important}.swagger-section .swagger-ui-wrap .editor_holder label.required{font-weight:700!important}.swagger-section .swagger-ui-wrap input.parameter{width:300px;border:1px solid #aaa}.swagger-section .swagger-ui-wrap h1{color:#000;font-size:1.5em;line-height:1.3em;padding:10px 0;font-family:Droid Sans,sans-serif;font-weight:700}.swagger-section .swagger-ui-wrap .heading_with_menu{float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap .heading_with_menu ul{display:block;clear:none;float:right;-ms-box-sizing:border-box;box-sizing:border-box;margin-top:10px}.swagger-section .swagger-ui-wrap h2{color:#000;font-size:1.3em;padding:10px 0}.swagger-section .swagger-ui-wrap h2 a{color:#000}.swagger-section .swagger-ui-wrap h2 span.sub{font-size:.7em;color:#999;font-style:italic}.swagger-section .swagger-ui-wrap h2 span.sub a{color:#777}.swagger-section .swagger-ui-wrap span.weak{color:#666}.swagger-section .swagger-ui-wrap .message-success{color:#89bf04}.swagger-section .swagger-ui-wrap caption,.swagger-section .swagger-ui-wrap td,.swagger-section .swagger-ui-wrap th{text-align:left;font-weight:400;vertical-align:middle}.swagger-section .swagger-ui-wrap .code{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.text textarea{font-family:Droid Sans,sans-serif;height:250px;padding:4px;display:block;clear:both}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.select select{display:block;clear:both}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean{float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean label{display:block;float:left;clear:none;margin:0;padding:0}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean input{display:block;float:left;clear:none;margin:0 5px 0 0}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.required label{color:#000}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label{display:block;clear:both;width:auto;padding:0 0 3px;color:#666}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label abbr{padding-left:3px;color:#888}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li p.inline-hints{margin-left:0;font-style:italic;font-size:.9em;margin:0}.swagger-section .swagger-ui-wrap form.formtastic fieldset.buttons{margin:0;padding:0}.swagger-section .swagger-ui-wrap span.blank,.swagger-section .swagger-ui-wrap span.empty{color:#888;font-style:italic}.swagger-section .swagger-ui-wrap .markdown h3{color:#547f00}.swagger-section .swagger-ui-wrap .markdown h4{color:#666}.swagger-section .swagger-ui-wrap .markdown pre{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;background-color:#fcf6db;border:1px solid #e5e0c6;padding:10px;margin:0 0 10px}.swagger-section .swagger-ui-wrap .markdown pre code{line-height:1.6em;overflow:auto}.swagger-section .swagger-ui-wrap div.gist{margin:20px 0 25px!important}.swagger-section .swagger-ui-wrap ul#resources{font-family:Droid Sans,sans-serif;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource{border-bottom:1px solid #ddd}.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading h2 a,.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading h2 a{color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading ul.options li a,.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading ul.options li a{color:#555}.swagger-section .swagger-ui-wrap ul#resources li.resource:last-child{border-bottom:none}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading{border:1px solid transparent;float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options{overflow:hidden;padding:0;display:block;clear:none;float:right;margin:14px 10px 0 0}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li{float:left;clear:none;margin:0;padding:2px 10px;border-right:1px solid #ddd;color:#666;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a{color:#aaa;text-decoration:none}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover{text-decoration:underline;color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a.active,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:active,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.first,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:first-child{padding-left:0}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:last-child{padding-right:0;border-right:none}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options.first,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options:first-child{padding-left:0}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2{color:#999;padding-left:0;display:block;clear:none;float:left;font-family:Droid Sans,sans-serif;font-weight:700}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a{color:#999}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a:hover{color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation{float:none;clear:both;overflow:hidden;display:block;margin:0 0 10px;padding:0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading{float:none;clear:both;overflow:hidden;display:block;margin:0;padding:0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3{display:block;clear:none;float:left;width:auto;margin:0;padding:0;line-height:1.1em;color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path{padding-left:10px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a{color:#000;text-decoration:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a.toggleOperation.deprecated{text-decoration:line-through}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.http_method a{text-transform:uppercase;text-decoration:none;color:#fff;display:inline-block;width:50px;font-size:.7em;text-align:center;padding:7px 0 4px;border-radius:2px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span{margin:0;padding:0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options{overflow:hidden;padding:0;display:block;clear:none;float:right;margin:6px 10px 0 0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li{float:left;clear:none;margin:0;padding:2px 10px;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a{text-decoration:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a .markdown p{color:inherit;padding:0;line-height:inherit}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a .nickname{color:#aaa;padding:0;line-height:inherit}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li.access{color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content{border-top:none;padding:10px;border-bottom-left-radius:6px;border-bottom-right-radius:6px;margin:0 0 20px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content h4{font-size:1.1em;margin:0;padding:15px 0 5px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header{float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header a{padding:4px 0 0 10px;display:inline-block;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header input.submit{display:block;clear:none;float:left;padding:6px 8px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header span.response_throbber{background-image:url(../images/throbber.gif);width:128px;height:16px;display:block;clear:none;float:right}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content form input[type=text].error{outline:2px solid #000;outline-color:#c00}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content form select[name=parameterContentType]{max-width:300px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.response div.block pre{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;padding:10px;font-size:.9em;max-height:400px;overflow-y:auto}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading{background-color:#f9f2e9;border:1px solid #f0e0ca}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading h3 span.http_method a{background-color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#f0e0ca;color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li a{color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content{background-color:#faf5ee;border:1px solid #f0e0ca}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content h4{color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content div.sandbox_header a{color:#dcb67f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading{background-color:#fcffcd;border:1px solid #000;border-color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading h3 span.http_method a{text-transform:uppercase;background-color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#ffd20f;color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li a{color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content{background-color:#fcffcd;border:1px solid #000;border-color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content h4{color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content div.sandbox_header a{color:#6fc992}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading{background-color:#f5e8e8;border:1px solid #e8c6c7}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading h3 span.http_method a{text-transform:uppercase;background-color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#e8c6c7;color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li a{color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content{background-color:#f7eded;border:1px solid #e8c6c7}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content h4{color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content div.sandbox_header a{color:#c8787a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading{background-color:#e7f6ec;border:1px solid #c3e8d1}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading h3 span.http_method a{background-color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#c3e8d1;color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li a{color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content{background-color:#ebf7f0;border:1px solid #c3e8d1}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content h4{color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content div.sandbox_header a{color:#6fc992}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading{background-color:#fce9e3;border:1px solid #f5d5c3}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading h3 span.http_method a{background-color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#f0cecb;color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li a{color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content{background-color:#faf0ef;border:1px solid #f0cecb}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content h4{color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content div.sandbox_header a{color:#dcb67f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading{background-color:#e7f0f7;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading h3 span.http_method a{background-color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#c3d9ec;color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li a{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content{background-color:#ebf3f9;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content h4{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content div.sandbox_header a{color:#6fa5d2}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading{background-color:#e7f0f7;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading h3 span.http_method a{background-color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#c3d9ec;color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li a{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content{background-color:#ebf3f9;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content h4{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content div.sandbox_header a{color:#6fa5d2}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content{border-top:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li:last-child{padding-right:0;border-right:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a.active,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:active,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations.first,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations:first-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li.first,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li:first-child{padding-left:0}.swagger-section .swagger-ui-wrap p#colophon{margin:0 15px 40px;padding:10px 0;font-size:.8em;border-top:1px solid #ddd;font-family:Droid Sans,sans-serif;color:#999;font-style:italic}.swagger-section .swagger-ui-wrap p#colophon a{text-decoration:none;color:#547f00}.swagger-section .swagger-ui-wrap h3{color:#000;font-size:1.1em;padding:10px 0}.swagger-section .swagger-ui-wrap .markdown ol,.swagger-section .swagger-ui-wrap .markdown ul{font-family:Droid Sans,sans-serif;margin:5px 0 10px;padding:0 0 0 18px;list-style-type:disc}.swagger-section .swagger-ui-wrap form.form_box{background-color:#ebf3f9;border:1px solid #c3d9ec;padding:10px}.swagger-section .swagger-ui-wrap form.form_box label{color:#0f6ab4!important}.swagger-section .swagger-ui-wrap form.form_box input[type=submit]{display:block;padding:10px}.swagger-section .swagger-ui-wrap form.form_box p.weak{font-size:.8em}.swagger-section .swagger-ui-wrap form.form_box p{font-size:.9em;padding:0 0 15px;color:#7e7b6d}.swagger-section .swagger-ui-wrap form.form_box p a{color:#646257}.swagger-section .swagger-ui-wrap form.form_box p strong{color:#000}.swagger-section .swagger-ui-wrap .operation-status td.markdown>p:last-child{padding-bottom:0}.swagger-section .title{font-style:bold}.swagger-section .secondary_form{display:none}.swagger-section .main_image{display:block;margin-left:auto;margin-right:auto}.swagger-section .oauth_body{margin-left:100px;margin-right:100px}.swagger-section .oauth_submit{text-align:center;display:inline-block}.swagger-section .authorize-wrapper{margin:15px 0 10px}.swagger-section .authorize-wrapper_operation{float:right}.swagger-section .authorize__btn:hover{text-decoration:underline;cursor:pointer}.swagger-section .authorize__btn_operation:hover .authorize-scopes{display:block}.swagger-section .authorize-scopes{position:absolute;margin-top:20px;background:#fff;border:1px solid #ccc;border-radius:5px;display:none;font-size:13px;max-width:300px;line-height:30px;color:#000;padding:5px}.swagger-section .authorize-scopes .authorize__scope{text-decoration:none}.swagger-section .authorize__btn_operation{height:18px;vertical-align:middle;display:inline-block;background:url(../images/explorer_icons.png) no-repeat}.swagger-section .authorize__btn_operation_login{background-position:0 0;width:18px;margin-top:-6px;margin-left:4px}.swagger-section .authorize__btn_operation_logout{background-position:-30px 0;width:18px;margin-top:-6px;margin-left:4px}.swagger-section #auth_container{color:#fff;display:inline-block;border:none;padding:5px;width:87px;height:13px}.swagger-section #auth_container .authorize__btn{color:#fff}.swagger-section .auth_container{padding:0 0 10px;margin-bottom:5px;border-bottom:1px solid #ccc;font-size:.9em}.swagger-section .auth_container .auth__title{color:#547f00;font-size:1.2em}.swagger-section .auth_container .basic_auth__label{display:inline-block;width:60px}.swagger-section .auth_container .auth__description{color:#999;margin-bottom:5px}.swagger-section .auth_container .auth__button{margin-top:10px;height:30px}.swagger-section .auth_container .key_auth__field{margin:5px 0}.swagger-section .auth_container .key_auth__label{display:inline-block;width:60px}.swagger-section .api-popup-dialog{position:absolute;display:none}.swagger-section .api-popup-dialog-wrapper{z-index:2;width:500px;background:#fff;padding:20px;border:1px solid #ccc;border-radius:5px;font-size:13px;color:#777;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%)}.swagger-section .api-popup-dialog-shadow{position:fixed;top:0;left:0;width:100%;height:100%;opacity:.2;background-color:gray;z-index:1}.swagger-section .api-popup-dialog .api-popup-title{font-size:24px;padding:10px 0}.swagger-section .api-popup-dialog .error-msg{padding-left:5px;padding-bottom:5px}.swagger-section .api-popup-dialog .api-popup-content{max-height:500px;overflow-y:auto}.swagger-section .api-popup-dialog .api-popup-authbtn,.swagger-section .api-popup-dialog .api-popup-cancel{height:30px}.swagger-section .api-popup-scopes{padding:10px 20px}.swagger-section .api-popup-scopes li{padding:5px 0;line-height:20px}.swagger-section .api-popup-scopes li input{position:relative;top:2px}.swagger-section .api-popup-scopes .api-scope-desc{padding-left:20px;font-style:italic}.swagger-section .api-popup-actions{padding-top:10px}.swagger-section fieldset{padding-bottom:10px;padding-left:20px}#header{display:none}.swagger-section .swagger-ui-wrap .model-signature pre{max-height:none}.swagger-section .swagger-ui-wrap .body-textarea,.swagger-section .swagger-ui-wrap input.parameter{width:100px}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options{display:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content{display:block!important} \ No newline at end of file diff --git a/src/main/resources/static/swagger/css/reset.css b/src/main/resources/static/swagger/css/reset.css new file mode 100644 index 0000000..40dc830 --- /dev/null +++ b/src/main/resources/static/swagger/css/reset.css @@ -0,0 +1 @@ +a,abbr,acronym,address,applet,article,aside,audio,b,big,blockquote,body,canvas,caption,center,cite,code,dd,del,details,dfn,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,nav,object,ol,output,p,pre,q,ruby,s,samp,section,small,span,strike,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,tt,u,ul,var,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:after,blockquote:before,q:after,q:before{content:'';content:none}table{border-collapse:collapse;border-spacing:0} \ No newline at end of file diff --git a/src/main/resources/static/swagger/css/screen.css b/src/main/resources/static/swagger/css/screen.css new file mode 100644 index 0000000..1f069f6 --- /dev/null +++ b/src/main/resources/static/swagger/css/screen.css @@ -0,0 +1 @@ +.swagger-section pre code{display:block;padding:.5em;background:#f0f0f0}.swagger-section pre .clojure .built_in,.swagger-section pre .lisp .title,.swagger-section pre .nginx .title,.swagger-section pre .subst,.swagger-section pre .tag .title,.swagger-section pre code{color:#000}.swagger-section pre .addition,.swagger-section pre .aggregate,.swagger-section pre .apache .cbracket,.swagger-section pre .apache .tag,.swagger-section pre .bash .variable,.swagger-section pre .constant,.swagger-section pre .django .variable,.swagger-section pre .erlang_repl .function_or_atom,.swagger-section pre .flow,.swagger-section pre .markdown .header,.swagger-section pre .parent,.swagger-section pre .preprocessor,.swagger-section pre .ruby .symbol,.swagger-section pre .ruby .symbol .string,.swagger-section pre .rules .value,.swagger-section pre .rules .value .number,.swagger-section pre .smalltalk .class,.swagger-section pre .stream,.swagger-section pre .string,.swagger-section pre .tag .value,.swagger-section pre .template_tag,.swagger-section pre .tex .command,.swagger-section pre .tex .special,.swagger-section pre .title{color:#800}.swagger-section pre .annotation,.swagger-section pre .chunk,.swagger-section pre .comment,.swagger-section pre .diff .header,.swagger-section pre .markdown .blockquote,.swagger-section pre .template_comment{color:#888}.swagger-section pre .change,.swagger-section pre .date,.swagger-section pre .go .constant,.swagger-section pre .literal,.swagger-section pre .markdown .bullet,.swagger-section pre .markdown .link_url,.swagger-section pre .number,.swagger-section pre .regexp,.swagger-section pre .smalltalk .char,.swagger-section pre .smalltalk .symbol{color:#080}.swagger-section pre .apache .sqbracket,.swagger-section pre .array,.swagger-section pre .attr_selector,.swagger-section pre .clojure .attribute,.swagger-section pre .coffeescript .property,.swagger-section pre .decorator,.swagger-section pre .deletion,.swagger-section pre .doctype,.swagger-section pre .envvar,.swagger-section pre .erlang_repl .reserved,.swagger-section pre .filter .argument,.swagger-section pre .important,.swagger-section pre .javadoc,.swagger-section pre .label,.swagger-section pre .localvars,.swagger-section pre .markdown .link_label,.swagger-section pre .nginx .built_in,.swagger-section pre .pi,.swagger-section pre .prompt,.swagger-section pre .pseudo,.swagger-section pre .ruby .string,.swagger-section pre .shebang,.swagger-section pre .tex .formula,.swagger-section pre .vhdl .attribute{color:#88f}.swagger-section pre .aggregate,.swagger-section pre .apache .tag,.swagger-section pre .bash .variable,.swagger-section pre .built_in,.swagger-section pre .css .tag,.swagger-section pre .go .typename,.swagger-section pre .id,.swagger-section pre .javadoctag,.swagger-section pre .keyword,.swagger-section pre .markdown .strong,.swagger-section pre .phpdoc,.swagger-section pre .request,.swagger-section pre .smalltalk .class,.swagger-section pre .status,.swagger-section pre .tex .command,.swagger-section pre .title,.swagger-section pre .winutils,.swagger-section pre .yardoctag{font-weight:700}.swagger-section pre .markdown .emphasis{font-style:italic}.swagger-section pre .nginx .built_in{font-weight:400}.swagger-section pre .coffeescript .javascript,.swagger-section pre .javascript .xml,.swagger-section pre .tex .formula,.swagger-section pre .xml .cdata,.swagger-section pre .xml .css,.swagger-section pre .xml .javascript,.swagger-section pre .xml .vbscript{opacity:.5}.swagger-section .hljs{display:block;overflow-x:auto;padding:.5em;background:#f0f0f0}.swagger-section .hljs,.swagger-section .hljs-subst{color:#444}.swagger-section .hljs-attribute,.swagger-section .hljs-doctag,.swagger-section .hljs-keyword,.swagger-section .hljs-meta-keyword,.swagger-section .hljs-name,.swagger-section .hljs-selector-tag{font-weight:700}.swagger-section .hljs-addition,.swagger-section .hljs-built_in,.swagger-section .hljs-bullet,.swagger-section .hljs-code,.swagger-section .hljs-literal{color:#1f811f}.swagger-section .hljs-link,.swagger-section .hljs-regexp,.swagger-section .hljs-selector-attr,.swagger-section .hljs-selector-pseudo,.swagger-section .hljs-symbol,.swagger-section .hljs-template-variable,.swagger-section .hljs-variable{color:#bc6060}.swagger-section .hljs-deletion,.swagger-section .hljs-number,.swagger-section .hljs-quote,.swagger-section .hljs-selector-class,.swagger-section .hljs-selector-id,.swagger-section .hljs-string,.swagger-section .hljs-template-tag,.swagger-section .hljs-type{color:#800}.swagger-section .hljs-section,.swagger-section .hljs-title{color:#800;font-weight:700}.swagger-section .hljs-comment{color:#888}.swagger-section .hljs-meta{color:#2b6ea1}.swagger-section .hljs-emphasis{font-style:italic}.swagger-section .hljs-strong{font-weight:700}.swagger-section .swagger-ui-wrap{line-height:1;font-family:Droid Sans,sans-serif;min-width:760px;max-width:960px;margin-left:auto;margin-right:auto}.swagger-section .swagger-ui-wrap b,.swagger-section .swagger-ui-wrap strong{font-family:Droid Sans,sans-serif;font-weight:700}.swagger-section .swagger-ui-wrap blockquote,.swagger-section .swagger-ui-wrap q{quotes:none}.swagger-section .swagger-ui-wrap p{line-height:1.4em;padding:0 0 10px;color:#333}.swagger-section .swagger-ui-wrap blockquote:after,.swagger-section .swagger-ui-wrap blockquote:before,.swagger-section .swagger-ui-wrap q:after,.swagger-section .swagger-ui-wrap q:before{content:none}.swagger-section .swagger-ui-wrap .heading_with_menu h1,.swagger-section .swagger-ui-wrap .heading_with_menu h2,.swagger-section .swagger-ui-wrap .heading_with_menu h3,.swagger-section .swagger-ui-wrap .heading_with_menu h4,.swagger-section .swagger-ui-wrap .heading_with_menu h5,.swagger-section .swagger-ui-wrap .heading_with_menu h6{display:block;clear:none;float:left;-ms-box-sizing:border-box;box-sizing:border-box;width:60%}.swagger-section .swagger-ui-wrap table{border-collapse:collapse;border-spacing:0}.swagger-section .swagger-ui-wrap table thead tr th{padding:5px;font-size:.9em;color:#666;border-bottom:1px solid #999}.swagger-section .swagger-ui-wrap table tbody tr:last-child td{border-bottom:none}.swagger-section .swagger-ui-wrap table tbody tr.offset{background-color:#f0f0f0}.swagger-section .swagger-ui-wrap table tbody tr td{padding:6px;font-size:.9em;border-bottom:1px solid #ccc;vertical-align:top;line-height:1.3em}.swagger-section .swagger-ui-wrap ol{margin:0 0 10px;padding:0 0 0 18px;list-style-type:decimal}.swagger-section .swagger-ui-wrap ol li{padding:5px 0;font-size:.9em;color:#333}.swagger-section .swagger-ui-wrap ol,.swagger-section .swagger-ui-wrap ul{list-style:none}.swagger-section .swagger-ui-wrap h1 a,.swagger-section .swagger-ui-wrap h2 a,.swagger-section .swagger-ui-wrap h3 a,.swagger-section .swagger-ui-wrap h4 a,.swagger-section .swagger-ui-wrap h5 a,.swagger-section .swagger-ui-wrap h6 a{text-decoration:none}.swagger-section .swagger-ui-wrap h1 a:hover,.swagger-section .swagger-ui-wrap h2 a:hover,.swagger-section .swagger-ui-wrap h3 a:hover,.swagger-section .swagger-ui-wrap h4 a:hover,.swagger-section .swagger-ui-wrap h5 a:hover,.swagger-section .swagger-ui-wrap h6 a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap h1 span.divider,.swagger-section .swagger-ui-wrap h2 span.divider,.swagger-section .swagger-ui-wrap h3 span.divider,.swagger-section .swagger-ui-wrap h4 span.divider,.swagger-section .swagger-ui-wrap h5 span.divider,.swagger-section .swagger-ui-wrap h6 span.divider{color:#aaa}.swagger-section .swagger-ui-wrap a{color:#547f00}.swagger-section .swagger-ui-wrap a img{border:none}.swagger-section .swagger-ui-wrap article,.swagger-section .swagger-ui-wrap aside,.swagger-section .swagger-ui-wrap details,.swagger-section .swagger-ui-wrap figcaption,.swagger-section .swagger-ui-wrap figure,.swagger-section .swagger-ui-wrap footer,.swagger-section .swagger-ui-wrap header,.swagger-section .swagger-ui-wrap hgroup,.swagger-section .swagger-ui-wrap menu,.swagger-section .swagger-ui-wrap nav,.swagger-section .swagger-ui-wrap section,.swagger-section .swagger-ui-wrap summary{display:block}.swagger-section .swagger-ui-wrap pre{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;background-color:#fcf6db;border:1px solid #e5e0c6;padding:10px}.swagger-section .swagger-ui-wrap pre code{line-height:1.6em;background:none}.swagger-section .swagger-ui-wrap .content>.content-type>div>label{clear:both;display:block;color:#0f6ab4;font-size:1.1em;margin:0;padding:15px 0 5px}.swagger-section .swagger-ui-wrap .content pre{font-size:12px;margin-top:5px;padding:5px}.swagger-section .swagger-ui-wrap .icon-btn{cursor:pointer}.swagger-section .swagger-ui-wrap .info_title{padding-bottom:10px;font-weight:700;font-size:25px}.swagger-section .swagger-ui-wrap .footer{margin-top:20px}.swagger-section .swagger-ui-wrap div.big p,.swagger-section .swagger-ui-wrap p.big{font-size:1em;margin-bottom:10px}.swagger-section .swagger-ui-wrap form.fullwidth ol li.numeric input,.swagger-section .swagger-ui-wrap form.fullwidth ol li.string input,.swagger-section .swagger-ui-wrap form.fullwidth ol li.text textarea,.swagger-section .swagger-ui-wrap form.fullwidth ol li.url input{width:500px!important}.swagger-section .swagger-ui-wrap .info_license,.swagger-section .swagger-ui-wrap .info_tos{padding-bottom:5px}.swagger-section .swagger-ui-wrap .message-fail{color:#c00}.swagger-section .swagger-ui-wrap .info_email,.swagger-section .swagger-ui-wrap .info_name,.swagger-section .swagger-ui-wrap .info_url{padding-bottom:5px}.swagger-section .swagger-ui-wrap .info_description{padding-bottom:10px;font-size:15px}.swagger-section .swagger-ui-wrap .markdown ol li,.swagger-section .swagger-ui-wrap .markdown ul li{padding:3px 0;line-height:1.4em;color:#333}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input{display:block;padding:4px;width:auto;clear:both}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input.title,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input.title,.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input.title{font-size:1.3em}.swagger-section .swagger-ui-wrap table.fullwidth{width:100%}.swagger-section .swagger-ui-wrap .model-signature{font-family:Droid Sans,sans-serif;font-size:1em;line-height:1.5em}.swagger-section .swagger-ui-wrap .model-signature .signature-nav a{text-decoration:none;color:#aaa}.swagger-section .swagger-ui-wrap .model-signature .signature-nav a:hover{text-decoration:underline;color:#000}.swagger-section .swagger-ui-wrap .model-signature .signature-nav .selected{color:#000;text-decoration:none}.swagger-section .swagger-ui-wrap .model-signature .propType{color:#55a}.swagger-section .swagger-ui-wrap .model-signature pre:hover{background-color:#ffd}.swagger-section .swagger-ui-wrap .model-signature pre{font-size:.85em;line-height:1.2em;overflow:auto;height:200px;resize:vertical;cursor:pointer}.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav{display:block;min-width:230px;margin:0;padding:0}.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li:last-child{padding-right:0;border-right:none}.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li{float:left;margin:0 5px 5px 0;padding:2px 5px 2px 0;border-right:1px solid #ddd}.swagger-section .swagger-ui-wrap .model-signature .propOpt{color:#555}.swagger-section .swagger-ui-wrap .model-signature .snippet small{font-size:.75em}.swagger-section .swagger-ui-wrap .model-signature .propOptKey{font-style:italic}.swagger-section .swagger-ui-wrap .model-signature .description .strong{font-weight:700;color:#000;font-size:.9em}.swagger-section .swagger-ui-wrap .model-signature .description div{font-size:.9em;line-height:1.5em;margin-left:1em}.swagger-section .swagger-ui-wrap .model-signature .description .stronger{font-weight:700;color:#000}.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper{border-spacing:0;position:absolute;background-color:#fff;border:1px solid #bbb;display:none;font-size:11px;max-width:400px;line-height:30px;color:#000;padding:5px;margin-left:10px}.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper th{text-align:center;background-color:#eee;border:1px solid #bbb;font-size:11px;color:#666;font-weight:700;padding:5px;line-height:15px}.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper .optionName{font-weight:700}.swagger-section .swagger-ui-wrap .model-signature .description .propDesc.markdown>p:first-child,.swagger-section .swagger-ui-wrap .model-signature .description .propDesc.markdown>p:last-child{display:inline}.swagger-section .swagger-ui-wrap .model-signature .description .propDesc.markdown>p:not(:first-child):before{display:block;content:''}.swagger-section .swagger-ui-wrap .model-signature .description span:last-of-type.propDesc.markdown>p:only-child{margin-right:-3px}.swagger-section .swagger-ui-wrap .model-signature .propName{font-weight:700}.swagger-section .swagger-ui-wrap .model-signature .signature-container{clear:both}.swagger-section .swagger-ui-wrap .body-textarea{width:300px;height:100px;border:1px solid #aaa}.swagger-section .swagger-ui-wrap .markdown li code,.swagger-section .swagger-ui-wrap .markdown p code{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;background-color:#f0f0f0;color:#000;padding:1px 3px}.swagger-section .swagger-ui-wrap .required{font-weight:700}.swagger-section .swagger-ui-wrap .editor_holder{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;font-size:.9em}.swagger-section .swagger-ui-wrap .editor_holder label{font-weight:400!important}.swagger-section .swagger-ui-wrap .editor_holder label.required{font-weight:700!important}.swagger-section .swagger-ui-wrap input.parameter{width:300px;border:1px solid #aaa}.swagger-section .swagger-ui-wrap h1{color:#000;font-size:1.5em;line-height:1.3em;padding:10px 0;font-family:Droid Sans,sans-serif;font-weight:700}.swagger-section .swagger-ui-wrap .heading_with_menu{float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap .heading_with_menu ul{display:block;clear:none;float:right;-ms-box-sizing:border-box;box-sizing:border-box;margin-top:10px}.swagger-section .swagger-ui-wrap h2{color:#000;font-size:1.3em;padding:10px 0}.swagger-section .swagger-ui-wrap h2 a{color:#000}.swagger-section .swagger-ui-wrap h2 span.sub{font-size:.7em;color:#999;font-style:italic}.swagger-section .swagger-ui-wrap h2 span.sub a{color:#777}.swagger-section .swagger-ui-wrap span.weak{color:#666}.swagger-section .swagger-ui-wrap .message-success{color:#89bf04}.swagger-section .swagger-ui-wrap caption,.swagger-section .swagger-ui-wrap td,.swagger-section .swagger-ui-wrap th{text-align:left;font-weight:400;vertical-align:middle}.swagger-section .swagger-ui-wrap .code{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.text textarea{font-family:Droid Sans,sans-serif;height:250px;padding:4px;display:block;clear:both}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.select select{display:block;clear:both}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean{float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean label{display:block;float:left;clear:none;margin:0;padding:0}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean input{display:block;float:left;clear:none;margin:0 5px 0 0}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.required label{color:#000}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label{display:block;clear:both;width:auto;padding:0 0 3px;color:#666}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label abbr{padding-left:3px;color:#888}.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li p.inline-hints{margin-left:0;font-style:italic;font-size:.9em;margin:0}.swagger-section .swagger-ui-wrap form.formtastic fieldset.buttons{margin:0;padding:0}.swagger-section .swagger-ui-wrap span.blank,.swagger-section .swagger-ui-wrap span.empty{color:#888;font-style:italic}.swagger-section .swagger-ui-wrap .markdown h3{color:#547f00}.swagger-section .swagger-ui-wrap .markdown h4{color:#666}.swagger-section .swagger-ui-wrap .markdown pre{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;background-color:#fcf6db;border:1px solid #e5e0c6;padding:10px;margin:0 0 10px}.swagger-section .swagger-ui-wrap .markdown pre code{line-height:1.6em;overflow:auto}.swagger-section .swagger-ui-wrap div.gist{margin:20px 0 25px!important}.swagger-section .swagger-ui-wrap ul#resources{font-family:Droid Sans,sans-serif;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource{border-bottom:1px solid #ddd}.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading h2 a,.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading h2 a{color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading ul.options li a,.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading ul.options li a{color:#555}.swagger-section .swagger-ui-wrap ul#resources li.resource:last-child{border-bottom:none}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading{border:1px solid transparent;float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options{overflow:hidden;padding:0;display:block;clear:none;float:right;margin:14px 10px 0 0}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li{float:left;clear:none;margin:0;padding:2px 10px;border-right:1px solid #ddd;color:#666;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a{color:#aaa;text-decoration:none}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover{text-decoration:underline;color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a.active,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:active,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.first,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:first-child{padding-left:0}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:last-child{padding-right:0;border-right:none}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options.first,.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options:first-child{padding-left:0}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2{color:#999;padding-left:0;display:block;clear:none;float:left;font-family:Droid Sans,sans-serif;font-weight:700}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a{color:#999}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a:hover{color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation{float:none;clear:both;overflow:hidden;display:block;margin:0 0 10px;padding:0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading{float:none;clear:both;overflow:hidden;display:block;margin:0;padding:0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3{display:block;clear:none;float:left;width:auto;margin:0;padding:0;line-height:1.1em;color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path{padding-left:10px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a{color:#000;text-decoration:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a.toggleOperation.deprecated{text-decoration:line-through}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.http_method a{text-transform:uppercase;text-decoration:none;color:#fff;display:inline-block;width:50px;font-size:.7em;text-align:center;padding:7px 0 4px;border-radius:2px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span{margin:0;padding:0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options{overflow:hidden;padding:0;display:block;clear:none;float:right;margin:6px 10px 0 0}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li{float:left;clear:none;margin:0;padding:2px 10px;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a{text-decoration:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a .markdown p{color:inherit;padding:0;line-height:inherit}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a .nickname{color:#aaa;padding:0;line-height:inherit}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li.access{color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content{border-top:none;padding:10px;border-bottom-left-radius:6px;border-bottom-right-radius:6px;margin:0 0 20px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content h4{font-size:1.1em;margin:0;padding:15px 0 5px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header{float:none;clear:both;overflow:hidden;display:block}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header a{padding:4px 0 0 10px;display:inline-block;font-size:.9em}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header input.submit{display:block;clear:none;float:left;padding:6px 8px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header span.response_throbber{background-image:url(../images/throbber.gif);width:128px;height:16px;display:block;clear:none;float:right}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content form input[type=text].error{outline:2px solid #000;outline-color:#c00}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content form select[name=parameterContentType]{max-width:300px}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.response div.block pre{font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;padding:10px;font-size:.9em;max-height:400px;overflow-y:auto}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading{background-color:#f9f2e9;border:1px solid #f0e0ca}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading h3 span.http_method a{background-color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#f0e0ca;color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li a{color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content{background-color:#faf5ee;border:1px solid #f0e0ca}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content h4{color:#c5862b}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content div.sandbox_header a{color:#dcb67f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading{background-color:#fcffcd;border:1px solid #000;border-color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading h3 span.http_method a{text-transform:uppercase;background-color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#ffd20f;color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li a{color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content{background-color:#fcffcd;border:1px solid #000;border-color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content h4{color:#ffd20f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content div.sandbox_header a{color:#6fc992}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading{background-color:#f5e8e8;border:1px solid #e8c6c7}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading h3 span.http_method a{text-transform:uppercase;background-color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#e8c6c7;color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li a{color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content{background-color:#f7eded;border:1px solid #e8c6c7}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content h4{color:#a41e22}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content div.sandbox_header a{color:#c8787a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading{background-color:#e7f6ec;border:1px solid #c3e8d1}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading h3 span.http_method a{background-color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#c3e8d1;color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li a{color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content{background-color:#ebf7f0;border:1px solid #c3e8d1}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content h4{color:#10a54a}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content div.sandbox_header a{color:#6fc992}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading{background-color:#fce9e3;border:1px solid #f5d5c3}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading h3 span.http_method a{background-color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#f0cecb;color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li a{color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content{background-color:#faf0ef;border:1px solid #f0cecb}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content h4{color:#d38042}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content div.sandbox_header a{color:#dcb67f}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading{background-color:#e7f0f7;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading h3 span.http_method a{background-color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#c3d9ec;color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li a{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content{background-color:#ebf3f9;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content h4{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content div.sandbox_header a{color:#6fa5d2}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading{background-color:#e7f0f7;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading h3 span.http_method a{background-color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li{border-right:1px solid #ddd;border-right-color:#c3d9ec;color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li a{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content{background-color:#ebf3f9;border:1px solid #c3d9ec}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content h4{color:#0f6ab4}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content div.sandbox_header a{color:#6fa5d2}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content{border-top:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li:last-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li.last,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li:last-child{padding-right:0;border-right:none}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a.active,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:active,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:hover{text-decoration:underline}.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations.first,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations:first-child,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li.first,.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li:first-child{padding-left:0}.swagger-section .swagger-ui-wrap p#colophon{margin:0 15px 40px;padding:10px 0;font-size:.8em;border-top:1px solid #ddd;font-family:Droid Sans,sans-serif;color:#999;font-style:italic}.swagger-section .swagger-ui-wrap p#colophon a{text-decoration:none;color:#547f00}.swagger-section .swagger-ui-wrap h3{color:#000;font-size:1.1em;padding:10px 0}.swagger-section .swagger-ui-wrap .markdown ol,.swagger-section .swagger-ui-wrap .markdown ul{font-family:Droid Sans,sans-serif;margin:5px 0 10px;padding:0 0 0 18px;list-style-type:disc}.swagger-section .swagger-ui-wrap form.form_box{background-color:#ebf3f9;border:1px solid #c3d9ec;padding:10px}.swagger-section .swagger-ui-wrap form.form_box label{color:#0f6ab4!important}.swagger-section .swagger-ui-wrap form.form_box input[type=submit]{display:block;padding:10px}.swagger-section .swagger-ui-wrap form.form_box p.weak{font-size:.8em}.swagger-section .swagger-ui-wrap form.form_box p{font-size:.9em;padding:0 0 15px;color:#7e7b6d}.swagger-section .swagger-ui-wrap form.form_box p a{color:#646257}.swagger-section .swagger-ui-wrap form.form_box p strong{color:#000}.swagger-section .swagger-ui-wrap .operation-status td.markdown>p:last-child{padding-bottom:0}.swagger-section .title{font-style:bold}.swagger-section .secondary_form{display:none}.swagger-section .main_image{display:block;margin-left:auto;margin-right:auto}.swagger-section .oauth_body{margin-left:100px;margin-right:100px}.swagger-section .oauth_submit{text-align:center;display:inline-block}.swagger-section .authorize-wrapper{margin:15px 0 10px}.swagger-section .authorize-wrapper_operation{float:right}.swagger-section .authorize__btn:hover{text-decoration:underline;cursor:pointer}.swagger-section .authorize__btn_operation:hover .authorize-scopes{display:block}.swagger-section .authorize-scopes{position:absolute;margin-top:20px;background:#fff;border:1px solid #ccc;border-radius:5px;display:none;font-size:13px;max-width:300px;line-height:30px;color:#000;padding:5px}.swagger-section .authorize-scopes .authorize__scope{text-decoration:none}.swagger-section .authorize__btn_operation{height:18px;vertical-align:middle;display:inline-block;background:url(../images/explorer_icons.png) no-repeat}.swagger-section .authorize__btn_operation_login{background-position:0 0;width:18px;margin-top:-6px;margin-left:4px}.swagger-section .authorize__btn_operation_logout{background-position:-30px 0;width:18px;margin-top:-6px;margin-left:4px}.swagger-section #auth_container{color:#fff;display:inline-block;border:none;padding:5px;width:87px;height:13px}.swagger-section #auth_container .authorize__btn{color:#fff}.swagger-section .auth_container{padding:0 0 10px;margin-bottom:5px;border-bottom:1px solid #ccc;font-size:.9em}.swagger-section .auth_container .auth__title{color:#547f00;font-size:1.2em}.swagger-section .auth_container .basic_auth__label{display:inline-block;width:60px}.swagger-section .auth_container .auth__description{color:#999;margin-bottom:5px}.swagger-section .auth_container .auth__button{margin-top:10px;height:30px}.swagger-section .auth_container .key_auth__field{margin:5px 0}.swagger-section .auth_container .key_auth__label{display:inline-block;width:60px}.swagger-section .api-popup-dialog{position:absolute;display:none}.swagger-section .api-popup-dialog-wrapper{z-index:2;width:500px;background:#fff;padding:20px;border:1px solid #ccc;border-radius:5px;font-size:13px;color:#777;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%)}.swagger-section .api-popup-dialog-shadow{position:fixed;top:0;left:0;width:100%;height:100%;opacity:.2;background-color:gray;z-index:1}.swagger-section .api-popup-dialog .api-popup-title{font-size:24px;padding:10px 0}.swagger-section .api-popup-dialog .error-msg{padding-left:5px;padding-bottom:5px}.swagger-section .api-popup-dialog .api-popup-content{max-height:500px;overflow-y:auto}.swagger-section .api-popup-dialog .api-popup-authbtn,.swagger-section .api-popup-dialog .api-popup-cancel{height:30px}.swagger-section .api-popup-scopes{padding:10px 20px}.swagger-section .api-popup-scopes li{padding:5px 0;line-height:20px}.swagger-section .api-popup-scopes li input{position:relative;top:2px}.swagger-section .api-popup-scopes .api-scope-desc{padding-left:20px;font-style:italic}.swagger-section .api-popup-actions{padding-top:10px}.swagger-section fieldset{padding-bottom:10px;padding-left:20px}.swagger-section .access,.swagger-section .auth{float:right}.swagger-section .api-ic{height:18px;vertical-align:middle;display:inline-block;background:url(../images/explorer_icons.png) no-repeat}.swagger-section .api-ic .api_information_panel{position:relative;margin-top:20px;margin-left:-5px;background:#fff;border:1px solid #ccc;border-radius:5px;display:none;font-size:13px;max-width:300px;line-height:30px;color:#000;padding:5px}.swagger-section .api-ic .api_information_panel p .api-msg-enabled{color:green}.swagger-section .api-ic .api_information_panel p .api-msg-disabled{color:red}.swagger-section .api-ic:hover .api_information_panel{position:absolute;display:block}.swagger-section .ic-info{background-position:0 0;width:18px;margin-top:-6px;margin-left:4px}.swagger-section .ic-warning{background-position:-60px 0;width:18px;margin-top:-6px;margin-left:4px}.swagger-section .ic-error{background-position:-30px 0;width:18px;margin-top:-6px;margin-left:4px}.swagger-section .ic-off{background-position:-90px 0;width:58px;margin-top:-4px;cursor:pointer}.swagger-section .ic-on{background-position:-160px 0;width:58px;margin-top:-4px;cursor:pointer}.swagger-section #header{background-color:#89bf04;padding:9px 14px 19px;height:23px;min-width:775px}.swagger-section #input_baseUrl{width:400px}.swagger-section #api_selector{display:block;clear:none;float:right}.swagger-section #api_selector .input{display:inline-block;clear:none;margin:0 10px 0 0}.swagger-section #api_selector input{font-size:.9em;padding:3px;margin:0}.swagger-section #input_apiKey{width:200px}.swagger-section #auth_container .authorize__btn,.swagger-section #explore{display:block;text-decoration:none;font-weight:700;padding:6px 8px;font-size:.9em;color:#fff;background-color:#547f00;border-radius:4px}.swagger-section #auth_container .authorize__btn:hover,.swagger-section #explore:hover{background-color:#547f00}.swagger-section #header #logo{font-size:1.5em;font-weight:700;text-decoration:none;color:#fff}.swagger-section #header #logo .logo__img{display:block;float:left;margin-top:2px}.swagger-section #header #logo .logo__title{display:inline-block;padding:5px 0 0 10px}.swagger-section #content_message{margin:10px 15px;font-style:italic;color:#999}.swagger-section #message-bar{min-height:30px;text-align:center;padding-top:10px}.swagger-section .swagger-collapse:before{content:"-"}.swagger-section .swagger-expand:before{content:"+"}.swagger-section .error{outline-color:#c00;background-color:#f2dede} \ No newline at end of file diff --git a/src/main/resources/static/swagger/css/style.css b/src/main/resources/static/swagger/css/style.css new file mode 100644 index 0000000..52907e4 --- /dev/null +++ b/src/main/resources/static/swagger/css/style.css @@ -0,0 +1 @@ +.swagger-section #header a#logo{font-size:1.5em;font-weight:700;text-decoration:none;padding:20px 0 20px 40px}#text-head{font-size:80px;font-family:Roboto,sans-serif;color:#fff;float:right;margin-right:20%}.navbar-fixed-top .navbar-brand,.navbar-fixed-top .navbar-nav,.navbar-header{height:auto}.navbar-inverse{background-color:#000;border-color:#000}#navbar-brand{margin-left:20%}.navtext{font-size:10px}.h1,h1{font-size:60px}.navbar-default .navbar-header .navbar-brand{color:#a2dfee}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a{color:#393939;font-family:Arvo,serif;font-size:1.5em}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a:hover{color:#000}.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2{color:#525252;padding-left:0;display:block;clear:none;float:left;font-family:Arvo,serif;font-weight:700}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#0a0a0a}.container1{width:1500px;margin:auto;margin-top:0;background-repeat:no-repeat;background-position:-40px -20px;margin-bottom:210px}.container-inner{width:1200px;margin:auto;background-color:hsla(192,8%,88%,.75);padding-bottom:40px;padding-top:40px;border-radius:15px}.header-content{padding:0;width:1000px}.title1{font-size:80px;font-family:Vollkorn,serif;color:#404040;text-align:center;padding-top:40px;padding-bottom:100px}#icon{margin-top:-18px}.subtext{font-size:25px;font-style:italic;color:#08b;text-align:right;padding-right:250px}.bg-primary{background-color:#00468b}.navbar-default .nav>li>a,.navbar-default .nav>li>a:focus,.navbar-default .nav>li>a:focus:hover,.navbar-default .nav>li>a:hover{color:#08b}.text-faded{font-size:25px;font-family:Vollkorn,serif}.section-heading{font-family:Vollkorn,serif;font-size:45px;padding-bottom:10px}hr{border-color:#00468b;padding-bottom:10px}.description{margin-top:20px;padding-bottom:200px}.description li{font-family:Vollkorn,serif;font-size:25px;color:#525252;margin-left:28%;padding-top:5px}.gap{margin-top:200px}.troubleshootingtext{color:hsla(0,0%,100%,.7);padding-left:30%}.troubleshootingtext li{list-style-type:circle;font-size:25px;padding-bottom:5px}.overlay{position:absolute;top:0;left:0;width:100%;height:100%;z-index:1}.block.response_body.json:hover{cursor:pointer}.backdrop{color:blue}#myModal{height:100%}.modal-backdrop{bottom:0;position:fixed}.curl{padding:10px;font-family:Anonymous Pro,Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace;font-size:.9em;max-height:400px;margin-top:5px;overflow-y:auto;background-color:#fcf6db;border:1px solid #e5e0c6;border-radius:4px}.curl_title{font-size:1.1em;margin:0;padding:15px 0 5px;font-family:Open Sans,Helvetica Neue,Arial,sans-serif;font-weight:500;line-height:1.1}.footer{display:none}.swagger-section .swagger-ui-wrap h2{padding:0}h2{margin:0;margin-bottom:5px}.markdown p,.swagger-section .swagger-ui-wrap .code{font-size:15px;font-family:Arvo,serif}.swagger-section .swagger-ui-wrap b{font-family:Arvo,serif}#signin:hover{cursor:pointer}.dropdown-menu{padding:15px}.navbar-right .dropdown-menu{left:0;right:auto}#signinbutton{width:100%;height:32px;font-size:13px;font-weight:700;color:#08b}.navbar-default .nav>li .details{color:#000;text-transform:none;font-size:15px;font-weight:400;font-family:Open Sans,sans-serif;font-style:italic;line-height:20px;top:-2px}.navbar-default .nav>li .details:hover{color:#000}#signout{width:100%;height:32px;font-size:13px;font-weight:700;color:#08b} \ No newline at end of file diff --git a/src/main/resources/static/swagger/css/typography.css b/src/main/resources/static/swagger/css/typography.css new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/static/swagger/favicon-16x16.png b/src/main/resources/static/swagger/favicon-16x16.png new file mode 100644 index 0000000..0f7e13b Binary files /dev/null and b/src/main/resources/static/swagger/favicon-16x16.png differ diff --git a/src/main/resources/static/swagger/favicon-32x32.png b/src/main/resources/static/swagger/favicon-32x32.png new file mode 100644 index 0000000..b0a3352 Binary files /dev/null and b/src/main/resources/static/swagger/favicon-32x32.png differ diff --git a/src/main/resources/static/swagger/fonts/DroidSans-Bold.ttf b/src/main/resources/static/swagger/fonts/DroidSans-Bold.ttf new file mode 100644 index 0000000..036c4d1 Binary files /dev/null and b/src/main/resources/static/swagger/fonts/DroidSans-Bold.ttf differ diff --git a/src/main/resources/static/swagger/fonts/DroidSans.ttf b/src/main/resources/static/swagger/fonts/DroidSans.ttf new file mode 100644 index 0000000..e517a0c Binary files /dev/null and b/src/main/resources/static/swagger/fonts/DroidSans.ttf differ diff --git a/src/main/resources/static/swagger/images/collapse.gif b/src/main/resources/static/swagger/images/collapse.gif new file mode 100644 index 0000000..8843e8c Binary files /dev/null and b/src/main/resources/static/swagger/images/collapse.gif differ diff --git a/src/main/resources/static/swagger/images/expand.gif b/src/main/resources/static/swagger/images/expand.gif new file mode 100644 index 0000000..477bf13 Binary files /dev/null and b/src/main/resources/static/swagger/images/expand.gif differ diff --git a/src/main/resources/static/swagger/images/explorer_icons.png b/src/main/resources/static/swagger/images/explorer_icons.png new file mode 100644 index 0000000..be43b27 Binary files /dev/null and b/src/main/resources/static/swagger/images/explorer_icons.png differ diff --git a/src/main/resources/static/swagger/images/favicon-16x16.png b/src/main/resources/static/swagger/images/favicon-16x16.png new file mode 100644 index 0000000..0f7e13b Binary files /dev/null and b/src/main/resources/static/swagger/images/favicon-16x16.png differ diff --git a/src/main/resources/static/swagger/images/favicon-32x32.png b/src/main/resources/static/swagger/images/favicon-32x32.png new file mode 100644 index 0000000..b0a3352 Binary files /dev/null and b/src/main/resources/static/swagger/images/favicon-32x32.png differ diff --git a/src/main/resources/static/swagger/images/favicon.ico b/src/main/resources/static/swagger/images/favicon.ico new file mode 100644 index 0000000..8b60bcf Binary files /dev/null and b/src/main/resources/static/swagger/images/favicon.ico differ diff --git a/src/main/resources/static/swagger/images/logo_small.png b/src/main/resources/static/swagger/images/logo_small.png new file mode 100644 index 0000000..ce3908e Binary files /dev/null and b/src/main/resources/static/swagger/images/logo_small.png differ diff --git a/src/main/resources/static/swagger/images/pet_store_api.png b/src/main/resources/static/swagger/images/pet_store_api.png new file mode 100644 index 0000000..1192ad8 Binary files /dev/null and b/src/main/resources/static/swagger/images/pet_store_api.png differ diff --git a/src/main/resources/static/swagger/images/throbber.gif b/src/main/resources/static/swagger/images/throbber.gif new file mode 100644 index 0000000..0639388 Binary files /dev/null and b/src/main/resources/static/swagger/images/throbber.gif differ diff --git a/src/main/resources/static/swagger/images/wordnik_api.png b/src/main/resources/static/swagger/images/wordnik_api.png new file mode 100644 index 0000000..dc0ddab Binary files /dev/null and b/src/main/resources/static/swagger/images/wordnik_api.png differ diff --git a/src/main/resources/static/swagger/index.html b/src/main/resources/static/swagger/index.html new file mode 100644 index 0000000..0696781 --- /dev/null +++ b/src/main/resources/static/swagger/index.html @@ -0,0 +1,107 @@ + + + + + + 接口文档 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
+
+ + diff --git a/src/main/resources/static/swagger/index.yaml b/src/main/resources/static/swagger/index.yaml new file mode 100644 index 0000000..4c67b27 --- /dev/null +++ b/src/main/resources/static/swagger/index.yaml @@ -0,0 +1,1663 @@ +swagger: '2.0' +info: + description: sqx-fast是一个轻量级的Java快速开发平台 + version: 1.0.0 + +basePath: /sqx-fast + +schemes: + - http + +#认证 +securityDefinitions: + api_key: + type: "apiKey" + name: "token" + in: "header" + +#定义接口数据 +paths: + /captcha.jpg: + get: + tags: + - 用户登录 + summary: 获取验证码 + produces: + - application/octet-stream + parameters: + - name: uuid + description: UUID + in: query + type: string + required: true + /sys/login: + post: + tags: + - 用户登录 + summary: 用户登录 + produces: + - application/json + parameters: + - name: body + description: 管理员对象 + in: body + type: string + schema: + $ref: '#/definitions/LoginForm' + required: true + responses: + '200': + schema: + $ref: '#/definitions/Login' + + /sys/user/list: + get: + tags: + - 管理员管理 + summary: 管理员列表 + produces: + - application/json + parameters: + - name: page + description: 页码 + in: query + type: integer + required: true + - name: limit + description: 每页条数 + in: query + type: integer + required: true + - name: sidx + description: 排序字段 + in: query + type: string + - name: order + description: 排序方式,如:asc、desc + in: query + type: string + - name: username + description: 用户名 + in: query + type: string + responses: + '200': + description: 返回管理员列表 + schema: + $ref: '#/definitions/SysUserEntityList' + /sys/user/info: + get: + tags: + - 管理员管理 + summary: 当前管理员信息 + produces: + - application/json + responses: + '200': + description: 返回当前管理员信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + user: + $ref: '#/definitions/SysUserEntity' + /sys/user/info/{userId}: + get: + tags: + - 管理员管理 + summary: 获取管理员信息 + produces: + - application/json + parameters: + - name: userId + description: 用户ID + in: path + type: integer + required: true + responses: + '200': + description: 返回管理员信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + user: + $ref: '#/definitions/SysUserEntity' + /sys/user/password: + post: + tags: + - 管理员管理 + summary: 修改密码 + produces: + - application/json + parameters: + - name: body + description: 管理员对象 + in: body + type: string + schema: + $ref: '#/definitions/PasswordForm' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/user/save: + post: + tags: + - 管理员管理 + summary: 添加管理员 + produces: + - application/json + parameters: + - name: body + description: 管理员对象 + in: body + type: string + schema: + $ref: '#/definitions/SysUserEntityEdit' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/user/update: + post: + tags: + - 管理员管理 + summary: 修改管理员 + produces: + - application/json + parameters: + - name: body + description: 管理员对象 + in: body + type: string + schema: + $ref: '#/definitions/SysUserEntityEdit' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/user/delete: + post: + tags: + - 管理员管理 + summary: 删除管理员 + produces: + - application/json + parameters: + - name: body + description: 用户ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + + /sys/role/list: + get: + tags: + - 角色管理 + summary: 角色列表 + produces: + - application/json + parameters: + - name: page + description: 页码 + in: query + type: integer + required: true + - name: limit + description: 每页条数 + in: query + type: integer + required: true + - name: sidx + description: 排序字段 + in: query + type: string + - name: order + description: 排序方式,如:asc、desc + in: query + type: string + - name: roleName + description: 角色名 + in: query + type: string + responses: + '200': + description: 返回角色列表 + schema: + $ref: '#/definitions/SysRoleEntityList' + /sys/role/select: + get: + tags: + - 角色管理 + summary: 当前账号角色列表 + description: 如果是超级管理员,则能查询所有的角色列表 + produces: + - application/json + responses: + '200': + description: 返回角色列表 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/SysRoleEntity' + /sys/role/info/{roleId}: + get: + tags: + - 角色管理 + summary: 获取角色信息 + produces: + - application/json + parameters: + - name: roleId + description: 角色ID + in: path + type: integer + required: true + responses: + '200': + description: 返回角色信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + role: + $ref: '#/definitions/SysRoleEntity' + /sys/role/save: + post: + tags: + - 角色管理 + summary: 添加角色 + produces: + - application/json + parameters: + - name: body + description: 角色对象 + in: body + type: string + schema: + $ref: '#/definitions/SysRoleEntityEdit' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/role/update: + post: + tags: + - 角色管理 + summary: 修改角色 + produces: + - application/json + parameters: + - name: body + description: 角色对象 + in: body + type: string + schema: + $ref: '#/definitions/SysRoleEntityEdit' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/role/delete: + post: + tags: + - 角色管理 + summary: 删除角色 + produces: + - application/json + parameters: + - name: body + description: 角色ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + + /sys/menu/nav: + get: + tags: + - 菜单管理 + summary: 导航菜单列表 + produces: + - application/json + responses: + '200': + description: 返回导航菜单列表 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + menuList: + description: 菜单列表 + type: array + items: + $ref: '#/definitions/SysMenuEntity' + permissions: + description: 权限列表 + type: array + items: + type: string + /sys/menu/list: + get: + tags: + - 菜单管理 + summary: 菜单列表 + produces: + - application/json + responses: + '200': + description: 返回菜单列表 + schema: + type: array + items: + $ref: '#/definitions/SysMenuEntity' + /sys/menu/select: + get: + tags: + - 菜单管理 + summary: 选择菜单 + description: 添加、修改菜单的时候,选择上级菜单接口 + produces: + - application/json + responses: + '200': + description: 返回菜单列表 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + menuList: + description: 菜单列表 + type: array + items: + $ref: '#/definitions/SysMenuEntity' + /sys/menu/info/{menuId}: + get: + tags: + - 菜单管理 + summary: 获取菜单信息 + produces: + - application/json + parameters: + - name: menuId + description: 菜单ID + in: path + type: integer + required: true + responses: + '200': + description: 返回菜单信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + menu: + description: 菜单信息 + $ref: '#/definitions/SysMenuEntity' + /sys/menu/save: + post: + tags: + - 菜单管理 + summary: 添加菜单 + produces: + - application/json + parameters: + - name: body + description: 菜单对象 + in: body + type: string + schema: + $ref: '#/definitions/SysMenuEntityEdit' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/menu/update: + post: + tags: + - 菜单管理 + summary: 修改菜单 + produces: + - application/json + parameters: + - name: body + description: 菜单对象 + in: body + type: string + schema: + $ref: '#/definitions/SysMenuEntityEdit' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/menu/delete/{menuId}: + post: + tags: + - 菜单管理 + summary: 删除菜单 + produces: + - application/json + parameters: + - name: menuId + description: 菜单ID + in: path + type: integer + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + + /sys/log/list: + get: + tags: + - 系统日志 + summary: 日志列表 + produces: + - application/json + parameters: + - name: page + description: 页码 + in: query + type: integer + required: true + - name: limit + description: 每页条数 + in: query + type: integer + required: true + - name: sidx + description: 排序字段 + in: query + type: string + - name: order + description: 排序方式,如:asc、desc + in: query + type: string + - name: key + description: 用户名或用户操作 + in: query + type: string + responses: + '200': + description: 返回日志列表 + schema: + $ref: '#/definitions/SysLogEntityList' + + /sys/config/list: + get: + tags: + - 参数管理 + summary: 参数列表 + produces: + - application/json + parameters: + - name: page + description: 页码 + in: query + type: integer + required: true + - name: limit + description: 每页条数 + in: query + type: integer + required: true + - name: sidx + description: 排序字段 + in: query + type: string + - name: order + description: 排序方式,如:asc、desc + in: query + type: string + - name: key + description: 参数名 + in: query + type: string + responses: + '200': + description: 返回参数列表 + schema: + $ref: '#/definitions/SysConfigEntityList' + /sys/config/info/{id}: + get: + tags: + - 参数管理 + summary: 获取参数信息 + produces: + - application/json + parameters: + - name: id + description: 参数ID + in: path + type: integer + required: true + responses: + '200': + description: 返回参数信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + config: + description: 返回参数信息 + $ref: '#/definitions/SysConfigEntity' + /sys/config/save: + post: + tags: + - 参数管理 + summary: 添加参数 + produces: + - application/json + parameters: + - name: body + description: 参数对象 + in: body + type: string + schema: + $ref: '#/definitions/SysConfigEntity' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/config/update: + post: + tags: + - 参数管理 + summary: 修改参数 + produces: + - application/json + parameters: + - name: body + description: 参数对象 + in: body + type: string + schema: + $ref: '#/definitions/SysConfigEntity' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/config/delete: + post: + tags: + - 参数管理 + summary: 删除参数 + produces: + - application/json + parameters: + - name: body + description: 参数ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + + /sys/oss/list: + get: + tags: + - 文件服务 + summary: 文件列表 + produces: + - application/json + parameters: + - name: page + description: 页码 + in: query + type: integer + required: true + - name: limit + description: 每页条数 + in: query + type: integer + required: true + - name: sidx + description: 排序字段 + in: query + type: string + - name: order + description: 排序方式,如:asc、desc + in: query + type: string + responses: + '200': + description: 返回文件列表 + schema: + $ref: '#/definitions/SysOssEntityList' + /sys/oss/config: + get: + tags: + - 文件服务 + summary: 云存储配置信息 + produces: + - application/json + responses: + '200': + description: 返回云存储配置信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + config: + description: 云存储配置信息 + $ref: '#/definitions/SysCloudStorageEntity' + /sys/oss/saveConfig: + post: + tags: + - 文件服务 + summary: 保存云存储配置信息 + produces: + - application/json + parameters: + - name: body + description: 参数对象 + in: body + type: string + schema: + $ref: '#/definitions/SysCloudStorageEntity' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/oss/upload: + post: + tags: + - 文件服务 + summary: 上传文件 + consumes: + - multipart/form-data + produces: + - application/json + parameters: + - name: file + description: 文件 + in: formData + type: file + required: true + responses: + '200': + description: 返回文件列表 + schema: + $ref: '#/definitions/FileUpload' + /sys/oss/delete: + post: + tags: + - 文件服务 + summary: 删除文件 + produces: + - application/json + parameters: + - name: body + description: 文件ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + + /sys/schedule/list: + get: + tags: + - 定时任务 + summary: 定时任务列表 + produces: + - application/json + parameters: + - name: page + description: 页码 + in: query + type: integer + required: true + - name: limit + description: 每页条数 + in: query + type: integer + required: true + - name: sidx + description: 排序字段 + in: query + type: string + - name: order + description: 排序方式,如:asc、desc + in: query + type: string + - name: beanName + description: spring bean名称 + in: query + type: string + responses: + '200': + description: 返回定时任务列表 + schema: + $ref: '#/definitions/ScheduleJobEntityList' + /sys/schedule/info/{jobId}: + get: + tags: + - 定时任务 + summary: 获取定时任务信息 + produces: + - application/json + parameters: + - name: jobId + description: 定时任务ID + in: path + type: integer + required: true + responses: + '200': + description: 返回定时任务信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + schedule: + description: 定时任务信息 + $ref: '#/definitions/ScheduleJobEntity' + /sys/schedule/save: + post: + tags: + - 定时任务 + summary: 添加定时任务 + produces: + - application/json + parameters: + - name: body + description: 定时任务对象 + in: body + type: string + schema: + $ref: '#/definitions/ScheduleJobEntity' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/schedule/update: + post: + tags: + - 定时任务 + summary: 修改定时任务 + produces: + - application/json + parameters: + - name: body + description: 定时任务对象 + in: body + type: string + schema: + $ref: '#/definitions/ScheduleJobEntity' + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/schedule/delete: + post: + tags: + - 定时任务 + summary: 删除定时任务 + produces: + - application/json + parameters: + - name: body + description: 定时任务ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/schedule/run: + post: + tags: + - 定时任务 + summary: 立即执行任务 + produces: + - application/json + parameters: + - name: body + description: 定时任务ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/schedule/pause: + post: + tags: + - 定时任务 + summary: 暂停定时任务 + produces: + - application/json + parameters: + - name: body + description: 定时任务ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + /sys/schedule/resume: + post: + tags: + - 定时任务 + summary: 恢复定时任务 + produces: + - application/json + parameters: + - name: body + description: 定时任务ID列表 + in: body + type: array + items: + type: integer + format: int64 + default: 0 + required: true + responses: + '200': + schema: + $ref: '#/definitions/R' + + /sys/scheduleLog/list: + get: + tags: + - 定时任务 + summary: 定时任务日志列表 + produces: + - application/json + parameters: + - name: page + description: 页码 + in: query + type: integer + required: true + - name: limit + description: 每页条数 + in: query + type: integer + required: true + - name: sidx + description: 排序字段 + in: query + type: string + - name: order + description: 排序方式,如:asc、desc + in: query + type: string + - name: beanName + description: spring bean名称 + in: query + type: string + responses: + '200': + description: 返回定时任务日志列表 + schema: + $ref: '#/definitions/ScheduleJobLogEntityList' + /sys/scheduleLog/info/{logId}: + get: + tags: + - 定时任务 + summary: 获取定时任务日志信息 + produces: + - application/json + parameters: + - name: logId + description: 日志ID + in: path + type: integer + required: true + responses: + '200': + description: 返回定时任务日志信息 + schema: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + schedule: + description: 定时任务日志信息 + $ref: '#/definitions/ScheduleJobLogEntity' + +#定义数据模型 +definitions: + R: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + msg: + description: 失败原因 + type: string + Login: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + token: + description: token + type: string + expire: + description: 过期时长 + type: integer + format: int32 + msg: + description: 失败原因 + type: string + LoginForm: + type: object + properties: + username: + description: 用户名 + type: string + password: + description: 密码 + type: string + captcha: + description: 验证码 + type: string + uuid: + description: UUID + type: string + PasswordForm: + type: object + properties: + password: + description: 原密码 + type: string + newPassword: + description: 新密码 + type: string + SysUserEntity: + type: object + properties: + userId: + description: 用户ID + type: integer + format: int64 + username: + description: 用户名 + type: string + password: + description: 密码 + type: string + email: + description: 邮箱 + type: string + mobile: + description: 手机号 + type: string + status: + description: 状态 0:禁用 1:正常 + type: integer + format: int32 + roleIdList: + description: 角色ID列表 + type: array + items: + type: integer + format: int64 + createUserId: + description: 创建者ID + type: integer + format: int64 + createTime: + description: 创建时间 + type: string + format: date-time + SysUserEntityList: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + page: + type: object + properties: + totalCount: + description: 总记录数 + type: integer + format: int32 + pageSize: + description: 每页记录数 + type: integer + format: int32 + totalPage: + description: 总页数 + type: integer + format: int32 + currPage: + description: 当前页数 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/SysUserEntity' + SysUserEntityEdit: + type: object + properties: + userId: + description: 用户ID + type: integer + format: int64 + username: + description: 用户名 + type: string + password: + description: 密码 + type: string + email: + description: 邮箱 + type: string + mobile: + description: 手机号 + type: string + status: + description: 状态 0:禁用 1:正常 + type: integer + format: int32 + roleIdList: + description: 角色ID列表 + type: array + items: + type: integer + format: int32 + + SysRoleEntity: + type: object + properties: + roleId: + description: 角色ID + type: integer + format: int64 + roleName: + description: 角色名称 + type: string + remark: + description: 备注 + type: string + menuIdList: + description: 菜单ID列表 + type: array + items: + type: integer + format: int64 + createUserId: + description: 创建者ID + type: integer + format: int64 + createTime: + description: 创建时间 + type: string + format: date-time + SysRoleEntityList: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + page: + type: object + properties: + totalCount: + description: 总记录数 + type: integer + format: int32 + pageSize: + description: 每页记录数 + type: integer + format: int32 + totalPage: + description: 总页数 + type: integer + format: int32 + currPage: + description: 当前页数 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/SysRoleEntity' + SysRoleEntityEdit: + type: object + properties: + roleId: + description: 角色ID + type: integer + format: int64 + roleName: + description: 角色名称 + type: string + remark: + description: 备注 + type: string + menuIdList: + description: 菜单ID列表 + type: array + items: + type: integer + format: int64 + + SysMenuEntity: + type: object + properties: + menuId: + description: 菜单ID + type: integer + format: int64 + name: + description: 菜单名称 + type: string + parentId: + description: 父菜单ID,一级菜单为0 + type: integer + format: int64 + parentName: + description: 父菜单名称 + type: string + url: + description: 菜单URL + type: string + perms: + description: 授权标识 + type: string + type: + description: 类型 0:目录 1:菜单 2:按钮 + type: integer + format: int32 + icon: + description: 菜单图标 + type: string + orderNum: + description: 排序 + type: integer + format: int32 + open: + description: 是否展开 true:展开 false:不展开 + type: boolean + format: int32 + SysMenuEntityEdit: + type: object + properties: + menuId: + description: 菜单ID + type: integer + format: int64 + name: + description: 菜单名称 + type: string + parentId: + description: 父菜单ID,一级菜单为0 + type: integer + format: int64 + url: + description: 菜单URL + type: string + perms: + description: 授权标识 + type: string + type: + description: 类型 0:目录 1:菜单 2:按钮 + type: integer + format: int32 + icon: + description: 菜单图标 + type: string + orderNum: + description: 排序 + type: integer + format: int32 + + SysLogEntity: + type: object + properties: + id: + description: 日志ID + type: integer + format: int64 + username: + description: 用户名 + type: string + operation: + description: 用户操作 + type: string + method: + description: 请求方法 + type: string + params: + description: 请求参数 + type: string + time: + description: 执行时长(毫秒) + type: integer + format: int64 + ip: + description: IP地址 + type: string + createTime: + description: 创建时间 + type: string + format: date-time + SysLogEntityList: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + page: + type: object + properties: + totalCount: + description: 总记录数 + type: integer + format: int32 + pageSize: + description: 每页记录数 + type: integer + format: int32 + totalPage: + description: 总页数 + type: integer + format: int32 + currPage: + description: 当前页数 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/SysLogEntity' + + SysConfigEntity: + type: object + properties: + id: + description: 参数ID + type: integer + format: int64 + key: + description: 参数名 + type: string + value: + description: 参数值 + type: string + remark: + description: 备注 + type: string + SysConfigEntityList: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + page: + type: object + properties: + totalCount: + description: 总记录数 + type: integer + format: int32 + pageSize: + description: 每页记录数 + type: integer + format: int32 + totalPage: + description: 总页数 + type: integer + format: int32 + currPage: + description: 当前页数 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/SysConfigEntity' + + SysOssEntity: + type: object + properties: + id: + description: ID + type: integer + format: int64 + url: + description: URL地址 + type: string + createTime: + description: 创建时间 + type: string + format: date-time + SysOssEntityList: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + page: + type: object + properties: + totalCount: + description: 总记录数 + type: integer + format: int32 + pageSize: + description: 每页记录数 + type: integer + format: int32 + totalPage: + description: 总页数 + type: integer + format: int32 + currPage: + description: 当前页数 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/SysOssEntity' + SysCloudStorageEntity: + type: object + properties: + type: + description: 类型 1:七牛 2:阿里云 3:腾讯云 + type: integer + format: int32 + qiniuDomain: + description: 七牛绑定的域名 + type: string + qiniuPrefix: + description: 七牛路径前缀 + type: string + qiniuAccessKey: + description: 七牛ACCESS_KEY + type: string + qiniuSecretKey: + description: 七牛SECRET_KEY + type: string + qiniuBucketName: + description: 七牛存储空间名 + type: string + aliyunDomain: + description: 阿里云绑定的域名 + type: string + aliyunPrefix: + description: 阿里云路径前缀 + type: string + aliyunEndPoint: + description: 阿里云EndPoint + type: string + aliyunAccessKeyId: + description: 阿里云AccessKeyId + type: string + aliyunAccessKeySecret: + description: 阿里云AccessKeySecret + type: string + aliyunBucketName: + description: 阿里云BucketName + type: string + qcloudDomain: + description: 腾讯云绑定的域名 + type: string + qcloudPrefix: + description: 腾讯云路径前缀 + type: string + qcloudAppId: + description: 腾讯云AppId + type: string + qcloudSecretId: + description: 腾讯云SecretId + type: string + qcloudSecretKey: + description: 腾讯云SecretKey + type: string + qcloudBucketName: + description: 腾讯云BucketName + type: string + qcloudRegion: + description: 腾讯云COS所属地区 + type: string + FileUpload: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + url: + description: 文件URL地址 + type: string + msg: + description: 失败原因 + type: string + + ScheduleJobEntity: + type: object + properties: + jobId: + description: 任务ID + type: integer + format: int64 + beanName: + description: spring bean名称 + type: string + methodName: + description: 方法名 + type: string + params: + description: 参数 + type: string + cronExpression: + description: cron表达式 + type: string + status: + description: 任务状态 0:正常 1:暂停 + type: integer + format: int32 + remark: + description: 备注 + type: string + createTime: + description: 创建时间 + type: string + format: date-time + ScheduleJobEntityList: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + page: + type: object + properties: + totalCount: + description: 总记录数 + type: integer + format: int32 + pageSize: + description: 每页记录数 + type: integer + format: int32 + totalPage: + description: 总页数 + type: integer + format: int32 + currPage: + description: 当前页数 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/ScheduleJobEntity' + + ScheduleJobLogEntity: + type: object + properties: + logId: + description: 日志id + type: integer + format: int64 + jobId: + description: 任务id + type: integer + format: int64 + beanName: + description: spring bean名称 + type: string + methodName: + description: 方法名 + type: string + params: + description: 参数 + type: string + status: + description: 任务状态 0:成功 1:失败 + type: integer + format: int32 + error: + description: 失败信息 + type: string + times: + description: 耗时(单位:毫秒) + type: integer + format: int32 + createTime: + description: 创建时间 + type: string + format: date-time + ScheduleJobLogEntityList: + type: object + properties: + code: + description: 状态码 0:成功 非0:失败 + type: integer + format: int32 + page: + type: object + properties: + totalCount: + description: 总记录数 + type: integer + format: int32 + pageSize: + description: 每页记录数 + type: integer + format: int32 + totalPage: + description: 总页数 + type: integer + format: int32 + currPage: + description: 当前页数 + type: integer + format: int32 + list: + type: array + items: + $ref: '#/definitions/ScheduleJobLogEntity' diff --git a/src/main/resources/static/swagger/lang/en.js b/src/main/resources/static/swagger/lang/en.js new file mode 100644 index 0000000..9183136 --- /dev/null +++ b/src/main/resources/static/swagger/lang/en.js @@ -0,0 +1,56 @@ +'use strict'; + +/* jshint quotmark: double */ +window.SwaggerTranslator.learn({ + "Warning: Deprecated":"Warning: Deprecated", + "Implementation Notes":"Implementation Notes", + "Response Class":"Response Class", + "Status":"Status", + "Parameters":"Parameters", + "Parameter":"Parameter", + "Value":"Value", + "Description":"Description", + "Parameter Type":"Parameter Type", + "Data Type":"Data Type", + "Response Messages":"Response Messages", + "HTTP Status Code":"HTTP Status Code", + "Reason":"Reason", + "Response Model":"Response Model", + "Request URL":"Request URL", + "Response Body":"Response Body", + "Response Code":"Response Code", + "Response Headers":"Response Headers", + "Hide Response":"Hide Response", + "Headers":"Headers", + "Try it out!":"Try it out!", + "Show/Hide":"Show/Hide", + "List Operations":"List Operations", + "Expand Operations":"Expand Operations", + "Raw":"Raw", + "can't parse JSON. Raw result":"can't parse JSON. Raw result", + "Example Value":"Example Value", + "Model Schema":"Model Schema", + "Model":"Model", + "Click to set as parameter value":"Click to set as parameter value", + "apply":"apply", + "Username":"Username", + "Password":"Password", + "Terms of service":"Terms of service", + "Created by":"Created by", + "See more at":"See more at", + "Contact the developer":"Contact the developer", + "api version":"api version", + "Response Content Type":"Response Content Type", + "Parameter content type:":"Parameter content type:", + "fetching resource":"fetching resource", + "fetching resource list":"fetching resource list", + "Explore":"Explore", + "Show Swagger Petstore Example Apis":"Show Swagger Petstore Example Apis", + "Can't read from server. It may not have the appropriate access-control-origin settings.":"Can't read from server. It may not have the appropriate access-control-origin settings.", + "Please specify the protocol for":"Please specify the protocol for", + "Can't read swagger JSON from":"Can't read swagger JSON from", + "Finished Loading Resource Information. Rendering Swagger UI":"Finished Loading Resource Information. Rendering Swagger UI", + "Unable to read api":"Unable to read api", + "from path":"from path", + "server returned":"server returned" +}); diff --git a/src/main/resources/static/swagger/lang/translator.js b/src/main/resources/static/swagger/lang/translator.js new file mode 100644 index 0000000..ffb879f --- /dev/null +++ b/src/main/resources/static/swagger/lang/translator.js @@ -0,0 +1,39 @@ +'use strict'; + +/** + * Translator for documentation pages. + * + * To enable translation you should include one of language-files in your index.html + * after . + * For example - + * + * If you wish to translate some new texts you should do two things: + * 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). It will be great if you add it in other language files too. + * 2. Mark that text it templates this way New Phrase or . + * The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate. + * + */ +window.SwaggerTranslator = { + + _words:[], + + translate: function(sel) { + var $this = this; + sel = sel || '[data-sw-translate]'; + + $(sel).each(function() { + $(this).html($this._tryTranslate($(this).html())); + + $(this).val($this._tryTranslate($(this).val())); + $(this).attr('title', $this._tryTranslate($(this).attr('title'))); + }); + }, + + _tryTranslate: function(word) { + return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word; + }, + + learn: function(wordsMap) { + this._words = wordsMap; + } +}; diff --git a/src/main/resources/static/swagger/lang/zh-cn.js b/src/main/resources/static/swagger/lang/zh-cn.js new file mode 100644 index 0000000..c7f55b4 --- /dev/null +++ b/src/main/resources/static/swagger/lang/zh-cn.js @@ -0,0 +1,56 @@ +'use strict'; + +/* jshint quotmark: double */ +window.SwaggerTranslator.learn({ + "Warning: Deprecated":"警告:已过时", + "Implementation Notes":"接口备注", + "Response Class":"响应类", + "Status":"状态", + "Parameters":"参数", + "Parameter":"参数", + "Value":"值", + "Description":"描述", + "Parameter Type":"参数类型", + "Data Type":"数据类型", + "Response Messages":"响应消息", + "HTTP Status Code":"HTTP状态码", + "Reason":"原因", + "Response Model":"响应模型", + "Request URL":"请求URL", + "Response Body":"响应体", + "Response Code":"响应码", + "Response Headers":"响应头", + "Hide Response":"隐藏响应", + "Headers":"头", + "Try it out!":"试一下!", + "Show/Hide":"显示/隐藏", + "List Operations":"显示操作", + "Expand Operations":"展开操作", + "Raw":"原始", + "can't parse JSON. Raw result":"无法解析JSON. 原始结果", + "Example Value":"示例", + "Click to set as parameter value":"点击设置参数", + "Model Schema":"模型架构", + "Model":"模型", + "apply":"应用", + "Username":"用户名", + "Password":"密码", + "Terms of service":"服务条款", + "Created by":"创建者", + "See more at":"查看更多:", + "Contact the developer":"联系开发者", + "api version":"api版本", + "Response Content Type":"响应类型", + "Parameter content type:":"参数类型:", + "fetching resource":"正在获取资源", + "fetching resource list":"正在获取资源列表", + "Explore":"浏览", + "Show Swagger Petstore Example Apis":"显示 Swagger Petstore 示例 Apis", + "Can't read from server. It may not have the appropriate access-control-origin settings.":"无法从服务器读取。可能没有正确设置access-control-origin。", + "Please specify the protocol for":"请指定协议:", + "Can't read swagger JSON from":"无法读取swagger JSON于", + "Finished Loading Resource Information. Rendering Swagger UI":"已加载资源信息。正在渲染Swagger UI", + "Unable to read api":"无法读取api", + "from path":"从路径", + "server returned":"服务器返回" +}); diff --git a/src/main/resources/static/swagger/lib/backbone-min.js b/src/main/resources/static/swagger/lib/backbone-min.js new file mode 100644 index 0000000..8eff02e --- /dev/null +++ b/src/main/resources/static/swagger/lib/backbone-min.js @@ -0,0 +1 @@ +!function(t,e){if("function"==typeof define&&define.amd)define(["underscore","jquery","exports"],function(i,n,s){t.Backbone=e(t,s,i,n)});else if("undefined"!=typeof exports){var i=require("underscore");e(t,exports,i)}else t.Backbone=e(t,{},t._,t.jQuery||t.Zepto||t.ender||t.$)}(this,function(t,e,i,n){var s=t.Backbone,r=[],a=(r.push,r.slice);r.splice;e.VERSION="1.1.2",e.$=n,e.noConflict=function(){return t.Backbone=s,this},e.emulateHTTP=!1,e.emulateJSON=!1;var o=e.Events={on:function(t,e,i){if(!c(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var n=this._events[t]||(this._events[t]=[]);return n.push({callback:e,context:i,ctx:i||this}),this},once:function(t,e,n){if(!c(this,"once",t,[e,n])||!e)return this;var s=this,r=i.once(function(){s.off(t,r),e.apply(this,arguments)});return r._callback=e,this.on(t,r,n)},off:function(t,e,n){var s,r,a,o,h,u,l,d;if(!this._events||!c(this,"off",t,[e,n]))return this;if(!t&&!e&&!n)return this._events=void 0,this;for(o=t?[t]:i.keys(this._events),h=0,u=o.length;h").attr(t);this.setElement(n,!1)}}}),e.sync=function(t,n,s){var r=E[t];i.defaults(s||(s={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:r,dataType:"json"};if(s.url||(a.url=i.result(n,"url")||j()),null!=s.data||!n||"create"!==t&&"update"!==t&&"patch"!==t||(a.contentType="application/json",a.data=JSON.stringify(s.attrs||n.toJSON(s))),s.emulateJSON&&(a.contentType="application/x-www-form-urlencoded",a.data=a.data?{model:a.data}:{}),s.emulateHTTP&&("PUT"===r||"DELETE"===r||"PATCH"===r)){a.type="POST",s.emulateJSON&&(a.data._method=r);var o=s.beforeSend;s.beforeSend=function(t){if(t.setRequestHeader("X-HTTP-Method-Override",r),o)return o.apply(this,arguments)}}"GET"===a.type||s.emulateJSON||(a.processData=!1),"PATCH"===a.type&&x&&(a.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")});var h=s.xhr=e.ajax(i.extend(a,s));return n.trigger("request",n,h,s),h};var x=!("undefined"==typeof window||!window.ActiveXObject||window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent),E={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var k=e.Router=function(t){t||(t={}),t.routes&&(this.routes=t.routes),this._bindRoutes(),this.initialize.apply(this,arguments)},T=/\((.*?)\)/g,$=/(\(\?)?:\w+/g,S=/\*\w+/g,H=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend(k.prototype,o,{initialize:function(){},route:function(t,n,s){i.isRegExp(t)||(t=this._routeToRegExp(t)),i.isFunction(n)&&(s=n,n=""),s||(s=this[n]);var r=this;return e.history.route(t,function(i){var a=r._extractParameters(t,i);r.execute(s,a),r.trigger.apply(r,["route:"+n].concat(a)),r.trigger("route",n,a),e.history.trigger("route",r,n,a)}),this},execute:function(t,e){t&&t.apply(this,e)},navigate:function(t,i){return e.history.navigate(t,i),this},_bindRoutes:function(){if(this.routes){this.routes=i.result(this,"routes");for(var t,e=i.keys(this.routes);null!=(t=e.pop());)this.route(t,this.routes[t])}},_routeToRegExp:function(t){return t=t.replace(H,"\\$&").replace(T,"(?:$1)?").replace($,function(t,e){return e?t:"([^/?]+)"}).replace(S,"([^?]*?)"),new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var n=t.exec(e).slice(1);return i.map(n,function(t,e){return e===n.length-1?t||null:t?decodeURIComponent(t):null})}});var A=e.History=function(){this.handlers=[],i.bindAll(this,"checkUrl"),"undefined"!=typeof window&&(this.location=window.location,this.history=window.history)},I=/^[#\/]|\s+$/g,N=/^\/+|\/+$/g,R=/msie [\w.]+/,O=/\/$/,P=/#.*$/;A.started=!1,i.extend(A.prototype,o,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(null==t)if(this._hasPushState||!this._wantsHashChange||e){t=decodeURI(this.location.pathname+this.location.search);var i=this.root.replace(O,"");t.indexOf(i)||(t=t.slice(i.length))}else t=this.getHash();return t.replace(I,"")},start:function(t){if(A.started)throw new Error("Backbone.history has already been started");A.started=!0,this.options=i.extend({root:"/"},this.options,t),this.root=this.options.root,this._wantsHashChange=this.options.hashChange!==!1,this._wantsPushState=!!this.options.pushState,this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var n=this.getFragment(),s=document.documentMode,r=R.exec(navigator.userAgent.toLowerCase())&&(!s||s<=7);if(this.root=("/"+this.root+"/").replace(N,"/"),r&&this._wantsHashChange){var a=e.$('