diff --git a/ant-design-vue-jeecg/src/utils/util.js b/ant-design-vue-jeecg/src/utils/util.js index d63d8850..ad6b6306 100644 --- a/ant-design-vue-jeecg/src/utils/util.js +++ b/ant-design-vue-jeecg/src/utils/util.js @@ -1,564 +1,564 @@ -import * as api from '@/api/api' -import { isURL } from '@/utils/validate' -//YU-优化 -import onlineCommons from '@jeecg/antd-online-mini' - -export function timeFix() { - const time = new Date() - const hour = time.getHours() - return hour < 9 ? '早上好' : (hour <= 11 ? '上午好' : (hour <= 13 ? '中午好' : (hour < 20 ? '下午好' : '晚上好'))) -} - -export function welcome() { - const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了'] - let index = Math.floor((Math.random()*arr.length)) - return arr[index] -} - -/** - * 触发 window.resize - */ -export function triggerWindowResizeEvent() { - let event = document.createEvent('HTMLEvents') - event.initEvent('resize', true, true) - event.eventType = 'message' - window.dispatchEvent(event) -} - -/** - * 过滤对象中为空的属性 - * @param obj - * @returns {*} - */ -export function filterObj(obj) { - if (!(typeof obj == 'object')) { - return; - } - - for ( let key in obj) { - if (obj.hasOwnProperty(key) - && (obj[key] == null || obj[key] == undefined || obj[key] === '')) { - delete obj[key]; - } - } - return obj; -} - -/** - * 时间格式化 - * @param value - * @param fmt - * @returns {*} - */ -export function formatDate(value, fmt) { - let regPos = /^\d+(\.\d+)?$/; - if(regPos.test(value)){ - //如果是数字 - let getDate = new Date(value); - let o = { - 'M+': getDate.getMonth() + 1, - 'd+': getDate.getDate(), - 'h+': getDate.getHours(), - 'm+': getDate.getMinutes(), - 's+': getDate.getSeconds(), - 'q+': Math.floor((getDate.getMonth() + 3) / 3), - 'S': getDate.getMilliseconds() - }; - if (/(y+)/.test(fmt)) { - fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length)) - } - for (let k in o) { - if (new RegExp('(' + k + ')').test(fmt)) { - fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) - } - } - return fmt; - }else{ - //TODO - value = value.trim(); - return value.substr(0,fmt.length); - } -} - -// 生成首页路由 -export function generateIndexRouter(data) { -let indexRouter = [{ - path: '/', - name: 'dashboard', - //component: () => import('@/components/layouts/BasicLayout'), - component: resolve => require(['@/components/layouts/TabLayout'], resolve), - meta: { title: '首页' }, - redirect: '/dashboard/analysis', - children: [ - ...generateChildRouters(data) - ] - },{ - "path": "*", "redirect": "/404", "hidden": true - }] - return indexRouter; -} - -// 生成嵌套路由(子路由) - -function generateChildRouters (data) { - const routers = []; - for (let item of data) { - let component = ""; - if(item.component.indexOf("layouts")>=0){ - component = "components/"+item.component; - }else{ - component = "views/"+item.component; - } - - // eslint-disable-next-line - let URL = (item.meta.url|| '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量 - if (isURL(URL)) { - item.meta.url = URL; - } - //YU-优化 - //let componentPath=resolve => require(['@/' + component+'.vue'], resolve) - let componentPath - if(item.component=="modules/online/cgform/OnlCgformHeadList"){ - componentPath = onlineCommons.OnlCgformHeadList - }else if(item.component=="modules/online/cgform/OnlCgformCopyList"){ - componentPath = onlineCommons.OnlCgformCopyList - }else if(item.component=="modules/online/cgform/auto/OnlCgformAutoList"){ - componentPath = onlineCommons.OnlCgformAutoList - }else if(item.component=="modules/online/cgform/auto/OnlCgformTreeList"){ - componentPath = onlineCommons.OnlCgformTreeList - }else if(item.component=="modules/online/cgform/auto/erp/OnlCgformErpList"){ - componentPath = onlineCommons.OnlCgformErpList - }else if(item.component=="modules/online/cgform/auto/tab/OnlCgformTabList"){ - componentPath = onlineCommons.OnlCgformTabList - }else if(item.component=="modules/online/cgform/auto/innerTable/OnlCgformInnerTableList"){ - componentPath = onlineCommons.OnlCgformInnerTableList - }else if(item.component=="modules/online/cgreport/OnlCgreportHeadList"){ - componentPath = onlineCommons.OnlCgreportHeadList - }else if(item.component=="modules/online/cgreport/auto/OnlCgreportAutoList"){ - componentPath = onlineCommons.OnlCgreportAutoList - }else{ - componentPath = resolve => require(['@/' + component+'.vue'], resolve) - } - - let menu = { - path: item.path, - name: item.name, - redirect:item.redirect, - component: componentPath, - //component: resolve => require(['@/' + component+'.vue'], resolve), - hidden:item.hidden, - meta: { - title:item.meta.title , - icon: item.meta.icon, - url:item.meta.url , - permissionList:item.meta.permissionList, - keepAlive:item.meta.keepAlive, - /*update_begin author:wuxianquan date:20190908 for:赋值 */ - internalOrExternal:item.meta.internalOrExternal, - /*update_end author:wuxianquan date:20190908 for:赋值 */ - componentName:item.meta.componentName - } - } - if(item.alwaysShow){ - menu.alwaysShow = true; - menu.redirect = menu.path; - } - if (item.children && item.children.length > 0) { - menu.children = [...generateChildRouters( item.children)]; - } - //--update-begin----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------ - //判断是否生成路由 - if(item.route && item.route === '0'){ - //console.log(' 不生成路由 item.route: '+item.route); - //console.log(' 不生成路由 item.path: '+item.path); - }else{ - routers.push(menu); - } - //--update-end----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------ - } - return routers -} - -/** - * 深度克隆对象、数组 - * @param obj 被克隆的对象 - * @return 克隆后的对象 - */ -export function cloneObject(obj) { - return JSON.parse(JSON.stringify(obj)) -} - -/** - * 随机生成数字 - * - * 示例:生成长度为 12 的随机数:randomNumber(12) - * 示例:生成 3~23 之间的随机数:randomNumber(3, 23) - * - * @param1 最小值 | 长度 - * @param2 最大值 - * @return int 生成后的数字 - */ -export function randomNumber() { - // 生成 最小值 到 最大值 区间的随机数 - const random = (min, max) => { - return Math.floor(Math.random() * (max - min + 1) + min) - } - if (arguments.length === 1) { - let [length] = arguments - // 生成指定长度的随机数字,首位一定不是 0 - let nums = [...Array(length).keys()].map((i) => (i > 0 ? random(0, 9) : random(1, 9))) - return parseInt(nums.join('')) - } else if (arguments.length >= 2) { - let [min, max] = arguments - return random(min, max) - } else { - return Number.NaN - } -} - -/** - * 随机生成字符串 - * @param length 字符串的长度 - * @param chats 可选字符串区间(只会生成传入的字符串中的字符) - * @return string 生成的字符串 - */ -export function randomString(length, chats) { - if (!length) length = 1 - if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm' - let str = '' - for (let i = 0; i < length; i++) { - let num = randomNumber(0, chats.length - 1) - str += chats[num] - } - return str -} - -/** - * 随机生成uuid - * @return string 生成的uuid - */ -export function randomUUID() { - let chats = '0123456789abcdef' - return randomString(32, chats) -} - -/** - * 下划线转驼峰 - * @param string - * @returns {*} - */ -export function underLine2CamelCase(string){ - return string.replace( /_([a-z])/g, function( all, letter ) { - return letter.toUpperCase(); - }); -} - -/** - * 判断是否显示办理按钮 - * @param bpmStatus - * @returns {*} - */ -export function showDealBtn(bpmStatus){ - if(bpmStatus!="1"&&bpmStatus!="3"&&bpmStatus!="4"){ - return true; - } - return false; -} - -/** - * 增强CSS,可以在页面上输出全局css - * @param css 要增强的css - * @param id style标签的id,可以用来清除旧样式 - */ -export function cssExpand(css, id) { - let style = document.createElement('style') - style.type = "text/css" - style.innerHTML = `@charset "UTF-8"; ${css}` - // 清除旧样式 - if (id) { - let $style = document.getElementById(id) - if ($style != null) $style.outerHTML = '' - style.id = id - } - // 应用新样式 - document.head.appendChild(style) -} - - -/** 用于js增强事件,运行JS代码,可以传参 */ -// options 所需参数: -// 参数名 类型 说明 -// vm VueComponent vue实例 -// event Object event对象 -// jsCode String 待执行的js代码 -// errorMessage String 执行出错后的提示(控制台) -export function jsExpand(options = {}) { - - // 绑定到window上的keyName - let windowKeyName = 'J_CLICK_EVENT_OPTIONS' - if (typeof window[windowKeyName] != 'object') { - window[windowKeyName] = {} - } - - // 随机生成JS增强的执行id,防止冲突 - let id = randomString(16, 'qwertyuioplkjhgfdsazxcvbnm'.toUpperCase()) - // 封装按钮点击事件 - let code = ` - (function (o_${id}) { - try { - (function (globalEvent, vm) { - ${options.jsCode} - })(o_${id}.event, o_${id}.vm) - } catch (e) { - o_${id}.error(e) - } - o_${id}.done() - })(window['${windowKeyName}']['EVENT_${id}']) - ` - // 创建script标签 - const script = document.createElement('script') - // 将需要传递的参数挂载到window对象上 - window[windowKeyName]['EVENT_' + id] = { - vm: options.vm, - event: options.event, - // 当执行完成时,无论如何都会调用的回调事件 - done() { - // 执行完后删除新增的 script 标签不会撤销执行结果(已产生的结果不会被撤销) - script.outerHTML = '' - delete window[windowKeyName]['EVENT_' + id] - }, - // 当js运行出错的时候调用的事件 - error(e) { - console.group(`${options.errorMessage || '用户自定义JS增强代码运行出错'}(${new Date()})`) - console.error(e) - console.groupEnd() - } - } - // 将事件挂载到document中 - script.innerHTML = code - document.body.appendChild(script) -} - - -/** - * 重复值验证工具方法 - * - * 使用示例: - * { validator: (rule, value, callback) => validateDuplicateValue('sys_fill_rule', 'rule_code', value, this.model.id, callback) } - * - * @param tableName 被验证的表名 - * @param fieldName 被验证的字段名 - * @param fieldVal 被验证的值 - * @param dataId 数据ID,可空 - * @param callback - */ -export function validateDuplicateValue(tableName, fieldName, fieldVal, dataId, callback) { - if (fieldVal) { - let params = { tableName, fieldName, fieldVal, dataId } - api.duplicateCheck(params).then(res => { - res['success'] ? callback() : callback(res['message']) - }).catch(err => { - callback(err.message || err) - }) - } else { - callback() - } -} - -/** - * 根据编码校验规则code,校验传入的值是否合法 - * - * 使用示例: - * { validator: (rule, value, callback) => validateCheckRule('common', value, callback) } - * - * @param ruleCode 编码校验规则 code - * @param value 被验证的值 - * @param callback - */ -export function validateCheckRule(ruleCode, value, callback) { - if (ruleCode && value) { - value = encodeURIComponent(value) - api.checkRuleByCode({ ruleCode, value }).then(res => { - res['success'] ? callback() : callback(res['message']) - }).catch(err => { - callback(err.message || err) - }) - } else { - callback() - } -} - -/** - * 如果值不存在就 push 进数组,反之不处理 - * @param array 要操作的数据 - * @param value 要添加的值 - * @param key 可空,如果比较的是对象,可能存在地址不一样但值实际上是一样的情况,可以传此字段判断对象中唯一的字段,例如 id。不传则直接比较实际值 - * @returns {boolean} 成功 push 返回 true,不处理返回 false - */ -export function pushIfNotExist(array, value, key) { - for (let item of array) { - if (key && (item[key] === value[key])) { - return false - } else if (item === value) { - return false - } - } - array.push(value) - return true -} - -/** - * 可用于判断是否成功 - * @type {symbol} - */ -export const succeedSymbol = Symbol() -/** - * 可用于判断是否失败 - * @type {symbol} - */ -export const failedSymbol = Symbol() - -/** - * 使 promise 无论如何都会 resolve,除非传入的参数不是一个Promise对象或返回Promise对象的方法 - * 一般用在 Promise.all 中 - * - * @param promise 可传Promise对象或返回Promise对象的方法 - * @returns {Promise} - */ -export function alwaysResolve(promise) { - return new Promise((resolve, reject) => { - let p = promise - if (typeof promise === 'function') { - p = promise() - } - if (p instanceof Promise) { - p.then(data => { - resolve({ type: succeedSymbol, data }) - }).catch(error => { - resolve({ type: failedSymbol, error }) - }) - } else { - reject('alwaysResolve: 传入的参数不是一个Promise对象或返回Promise对象的方法') - } - }) -} - -/** - * 简单实现防抖方法 - * - * 防抖(debounce)函数在第一次触发给定的函数时,不立即执行函数,而是给出一个期限值(delay),比如100ms。 - * 如果100ms内再次执行函数,就重新开始计时,直到计时结束后再真正执行函数。 - * 这样做的好处是如果短时间内大量触发同一事件,只会执行一次函数。 - * - * @param fn 要防抖的函数 - * @param delay 防抖的毫秒数 - * @returns {Function} - */ -export function simpleDebounce(fn, delay = 100) { - let timer = null - return function () { - let args = arguments - if (timer) { - clearTimeout(timer) - } - timer = setTimeout(() => { - fn.apply(this, args) - }, delay) - } -} - -/** - * 不用正则的方式替换所有值 - * @param text 被替换的字符串 - * @param checker 替换前的内容 - * @param replacer 替换后的内容 - * @returns {String} 替换后的字符串 - */ -export function replaceAll(text, checker, replacer) { - let lastText = text - text = text.replace(checker, replacer) - if (lastText !== text) { - return replaceAll(text, checker, replacer) - } - return text -} - -/** - * 获取事件冒泡路径,兼容 IE11,Edge,Chrome,Firefox,Safari - * 目前使用的地方:JEditableTable Span模式 - */ -export function getEventPath(event) { - let target = event.target - let path = (event.composedPath && event.composedPath()) || event.path - - if (path != null) { - return (path.indexOf(window) < 0) ? path.concat(window) : path - } - - if (target === window) { - return [window] - } - - let getParents = (node, memo) => { - memo = memo || [] - const parentNode = node.parentNode - - if (!parentNode) { - return memo - } else { - return getParents(parentNode, memo.concat(parentNode)) - } - } - return [target].concat(getParents(target), window) -} - -/** - * 根据组件名获取父级 - * @param vm - * @param name - * @returns {Vue | null|null|Vue} - */ -export function getVmParentByName(vm, name) { - let parent = vm.$parent - if (parent && parent.$options) { - if (parent.$options.name === name) { - return parent - } else { - let res = getVmParentByName(parent, name) - if (res) { - return res - } - } - } - return null -} - -/** - * 使一个值永远不会为(null | undefined) - * - * @param value 要处理的值 - * @param def 默认值,如果value为(null | undefined)则返回的默认值,可不传,默认为'' - */ -export function neverNull(value, def) { - return value == null ? (neverNull(def, '')) : value -} - -/** - * 根据元素值移除数组中的一个元素 - * @param array 数组 - * @param prod 属性名 - * @param value 属性值 - * @returns {string} - */ -export function removeArrayElement(array, prod, value) { - let index = -1 - for(let i = 0;i=0){ - array.splice(index, 1); - } +import * as api from '@/api/api' +import { isURL } from '@/utils/validate' +//YU-优化 +// import onlineCommons from '@jeecg/antd-online-mini' + +export function timeFix() { + const time = new Date() + const hour = time.getHours() + return hour < 9 ? '早上好' : (hour <= 11 ? '上午好' : (hour <= 13 ? '中午好' : (hour < 20 ? '下午好' : '晚上好'))) +} + +export function welcome() { + const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了'] + let index = Math.floor((Math.random()*arr.length)) + return arr[index] +} + +/** + * 触发 window.resize + */ +export function triggerWindowResizeEvent() { + let event = document.createEvent('HTMLEvents') + event.initEvent('resize', true, true) + event.eventType = 'message' + window.dispatchEvent(event) +} + +/** + * 过滤对象中为空的属性 + * @param obj + * @returns {*} + */ +export function filterObj(obj) { + if (!(typeof obj == 'object')) { + return; + } + + for ( let key in obj) { + if (obj.hasOwnProperty(key) + && (obj[key] == null || obj[key] == undefined || obj[key] === '')) { + delete obj[key]; + } + } + return obj; +} + +/** + * 时间格式化 + * @param value + * @param fmt + * @returns {*} + */ +export function formatDate(value, fmt) { + let regPos = /^\d+(\.\d+)?$/; + if(regPos.test(value)){ + //如果是数字 + let getDate = new Date(value); + let o = { + 'M+': getDate.getMonth() + 1, + 'd+': getDate.getDate(), + 'h+': getDate.getHours(), + 'm+': getDate.getMinutes(), + 's+': getDate.getSeconds(), + 'q+': Math.floor((getDate.getMonth() + 3) / 3), + 'S': getDate.getMilliseconds() + }; + if (/(y+)/.test(fmt)) { + fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length)) + } + for (let k in o) { + if (new RegExp('(' + k + ')').test(fmt)) { + fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) + } + } + return fmt; + }else{ + //TODO + value = value.trim(); + return value.substr(0,fmt.length); + } +} + +// 生成首页路由 +export function generateIndexRouter(data) { +let indexRouter = [{ + path: '/', + name: 'dashboard', + //component: () => import('@/components/layouts/BasicLayout'), + component: resolve => require(['@/components/layouts/TabLayout'], resolve), + meta: { title: '首页' }, + redirect: '/dashboard/analysis', + children: [ + ...generateChildRouters(data) + ] + },{ + "path": "*", "redirect": "/404", "hidden": true + }] + return indexRouter; +} + +// 生成嵌套路由(子路由) + +function generateChildRouters (data) { + const routers = []; + for (let item of data) { + let component = ""; + if(item.component.indexOf("layouts")>=0){ + component = "components/"+item.component; + }else{ + component = "views/"+item.component; + } + + // eslint-disable-next-line + let URL = (item.meta.url|| '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量 + if (isURL(URL)) { + item.meta.url = URL; + } + //YU-优化 + let componentPath=resolve => require(['@/' + component+'.vue'], resolve) + // let componentPath + // if(item.component=="modules/online/cgform/OnlCgformHeadList"){ + // componentPath = onlineCommons.OnlCgformHeadList + // }else if(item.component=="modules/online/cgform/OnlCgformCopyList"){ + // componentPath = onlineCommons.OnlCgformCopyList + // }else if(item.component=="modules/online/cgform/auto/OnlCgformAutoList"){ + // componentPath = onlineCommons.OnlCgformAutoList + // }else if(item.component=="modules/online/cgform/auto/OnlCgformTreeList"){ + // componentPath = onlineCommons.OnlCgformTreeList + // }else if(item.component=="modules/online/cgform/auto/erp/OnlCgformErpList"){ + // componentPath = onlineCommons.OnlCgformErpList + // }else if(item.component=="modules/online/cgform/auto/tab/OnlCgformTabList"){ + // componentPath = onlineCommons.OnlCgformTabList + // }else if(item.component=="modules/online/cgform/auto/innerTable/OnlCgformInnerTableList"){ + // componentPath = onlineCommons.OnlCgformInnerTableList + // }else if(item.component=="modules/online/cgreport/OnlCgreportHeadList"){ + // componentPath = onlineCommons.OnlCgreportHeadList + // }else if(item.component=="modules/online/cgreport/auto/OnlCgreportAutoList"){ + // componentPath = onlineCommons.OnlCgreportAutoList + // }else{ + // componentPath = resolve => require(['@/' + component+'.vue'], resolve) + // } + + let menu = { + path: item.path, + name: item.name, + redirect:item.redirect, + component: componentPath, + //component: resolve => require(['@/' + component+'.vue'], resolve), + hidden:item.hidden, + meta: { + title:item.meta.title , + icon: item.meta.icon, + url:item.meta.url , + permissionList:item.meta.permissionList, + keepAlive:item.meta.keepAlive, + /*update_begin author:wuxianquan date:20190908 for:赋值 */ + internalOrExternal:item.meta.internalOrExternal, + /*update_end author:wuxianquan date:20190908 for:赋值 */ + componentName:item.meta.componentName + } + } + if(item.alwaysShow){ + menu.alwaysShow = true; + menu.redirect = menu.path; + } + if (item.children && item.children.length > 0) { + menu.children = [...generateChildRouters( item.children)]; + } + //--update-begin----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------ + //判断是否生成路由 + if(item.route && item.route === '0'){ + //console.log(' 不生成路由 item.route: '+item.route); + //console.log(' 不生成路由 item.path: '+item.path); + }else{ + routers.push(menu); + } + //--update-end----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------ + } + return routers +} + +/** + * 深度克隆对象、数组 + * @param obj 被克隆的对象 + * @return 克隆后的对象 + */ +export function cloneObject(obj) { + return JSON.parse(JSON.stringify(obj)) +} + +/** + * 随机生成数字 + * + * 示例:生成长度为 12 的随机数:randomNumber(12) + * 示例:生成 3~23 之间的随机数:randomNumber(3, 23) + * + * @param1 最小值 | 长度 + * @param2 最大值 + * @return int 生成后的数字 + */ +export function randomNumber() { + // 生成 最小值 到 最大值 区间的随机数 + const random = (min, max) => { + return Math.floor(Math.random() * (max - min + 1) + min) + } + if (arguments.length === 1) { + let [length] = arguments + // 生成指定长度的随机数字,首位一定不是 0 + let nums = [...Array(length).keys()].map((i) => (i > 0 ? random(0, 9) : random(1, 9))) + return parseInt(nums.join('')) + } else if (arguments.length >= 2) { + let [min, max] = arguments + return random(min, max) + } else { + return Number.NaN + } +} + +/** + * 随机生成字符串 + * @param length 字符串的长度 + * @param chats 可选字符串区间(只会生成传入的字符串中的字符) + * @return string 生成的字符串 + */ +export function randomString(length, chats) { + if (!length) length = 1 + if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm' + let str = '' + for (let i = 0; i < length; i++) { + let num = randomNumber(0, chats.length - 1) + str += chats[num] + } + return str +} + +/** + * 随机生成uuid + * @return string 生成的uuid + */ +export function randomUUID() { + let chats = '0123456789abcdef' + return randomString(32, chats) +} + +/** + * 下划线转驼峰 + * @param string + * @returns {*} + */ +export function underLine2CamelCase(string){ + return string.replace( /_([a-z])/g, function( all, letter ) { + return letter.toUpperCase(); + }); +} + +/** + * 判断是否显示办理按钮 + * @param bpmStatus + * @returns {*} + */ +export function showDealBtn(bpmStatus){ + if(bpmStatus!="1"&&bpmStatus!="3"&&bpmStatus!="4"){ + return true; + } + return false; +} + +/** + * 增强CSS,可以在页面上输出全局css + * @param css 要增强的css + * @param id style标签的id,可以用来清除旧样式 + */ +export function cssExpand(css, id) { + let style = document.createElement('style') + style.type = "text/css" + style.innerHTML = `@charset "UTF-8"; ${css}` + // 清除旧样式 + if (id) { + let $style = document.getElementById(id) + if ($style != null) $style.outerHTML = '' + style.id = id + } + // 应用新样式 + document.head.appendChild(style) +} + + +/** 用于js增强事件,运行JS代码,可以传参 */ +// options 所需参数: +// 参数名 类型 说明 +// vm VueComponent vue实例 +// event Object event对象 +// jsCode String 待执行的js代码 +// errorMessage String 执行出错后的提示(控制台) +export function jsExpand(options = {}) { + + // 绑定到window上的keyName + let windowKeyName = 'J_CLICK_EVENT_OPTIONS' + if (typeof window[windowKeyName] != 'object') { + window[windowKeyName] = {} + } + + // 随机生成JS增强的执行id,防止冲突 + let id = randomString(16, 'qwertyuioplkjhgfdsazxcvbnm'.toUpperCase()) + // 封装按钮点击事件 + let code = ` + (function (o_${id}) { + try { + (function (globalEvent, vm) { + ${options.jsCode} + })(o_${id}.event, o_${id}.vm) + } catch (e) { + o_${id}.error(e) + } + o_${id}.done() + })(window['${windowKeyName}']['EVENT_${id}']) + ` + // 创建script标签 + const script = document.createElement('script') + // 将需要传递的参数挂载到window对象上 + window[windowKeyName]['EVENT_' + id] = { + vm: options.vm, + event: options.event, + // 当执行完成时,无论如何都会调用的回调事件 + done() { + // 执行完后删除新增的 script 标签不会撤销执行结果(已产生的结果不会被撤销) + script.outerHTML = '' + delete window[windowKeyName]['EVENT_' + id] + }, + // 当js运行出错的时候调用的事件 + error(e) { + console.group(`${options.errorMessage || '用户自定义JS增强代码运行出错'}(${new Date()})`) + console.error(e) + console.groupEnd() + } + } + // 将事件挂载到document中 + script.innerHTML = code + document.body.appendChild(script) +} + + +/** + * 重复值验证工具方法 + * + * 使用示例: + * { validator: (rule, value, callback) => validateDuplicateValue('sys_fill_rule', 'rule_code', value, this.model.id, callback) } + * + * @param tableName 被验证的表名 + * @param fieldName 被验证的字段名 + * @param fieldVal 被验证的值 + * @param dataId 数据ID,可空 + * @param callback + */ +export function validateDuplicateValue(tableName, fieldName, fieldVal, dataId, callback) { + if (fieldVal) { + let params = { tableName, fieldName, fieldVal, dataId } + api.duplicateCheck(params).then(res => { + res['success'] ? callback() : callback(res['message']) + }).catch(err => { + callback(err.message || err) + }) + } else { + callback() + } +} + +/** + * 根据编码校验规则code,校验传入的值是否合法 + * + * 使用示例: + * { validator: (rule, value, callback) => validateCheckRule('common', value, callback) } + * + * @param ruleCode 编码校验规则 code + * @param value 被验证的值 + * @param callback + */ +export function validateCheckRule(ruleCode, value, callback) { + if (ruleCode && value) { + value = encodeURIComponent(value) + api.checkRuleByCode({ ruleCode, value }).then(res => { + res['success'] ? callback() : callback(res['message']) + }).catch(err => { + callback(err.message || err) + }) + } else { + callback() + } +} + +/** + * 如果值不存在就 push 进数组,反之不处理 + * @param array 要操作的数据 + * @param value 要添加的值 + * @param key 可空,如果比较的是对象,可能存在地址不一样但值实际上是一样的情况,可以传此字段判断对象中唯一的字段,例如 id。不传则直接比较实际值 + * @returns {boolean} 成功 push 返回 true,不处理返回 false + */ +export function pushIfNotExist(array, value, key) { + for (let item of array) { + if (key && (item[key] === value[key])) { + return false + } else if (item === value) { + return false + } + } + array.push(value) + return true +} + +/** + * 可用于判断是否成功 + * @type {symbol} + */ +export const succeedSymbol = Symbol() +/** + * 可用于判断是否失败 + * @type {symbol} + */ +export const failedSymbol = Symbol() + +/** + * 使 promise 无论如何都会 resolve,除非传入的参数不是一个Promise对象或返回Promise对象的方法 + * 一般用在 Promise.all 中 + * + * @param promise 可传Promise对象或返回Promise对象的方法 + * @returns {Promise} + */ +export function alwaysResolve(promise) { + return new Promise((resolve, reject) => { + let p = promise + if (typeof promise === 'function') { + p = promise() + } + if (p instanceof Promise) { + p.then(data => { + resolve({ type: succeedSymbol, data }) + }).catch(error => { + resolve({ type: failedSymbol, error }) + }) + } else { + reject('alwaysResolve: 传入的参数不是一个Promise对象或返回Promise对象的方法') + } + }) +} + +/** + * 简单实现防抖方法 + * + * 防抖(debounce)函数在第一次触发给定的函数时,不立即执行函数,而是给出一个期限值(delay),比如100ms。 + * 如果100ms内再次执行函数,就重新开始计时,直到计时结束后再真正执行函数。 + * 这样做的好处是如果短时间内大量触发同一事件,只会执行一次函数。 + * + * @param fn 要防抖的函数 + * @param delay 防抖的毫秒数 + * @returns {Function} + */ +export function simpleDebounce(fn, delay = 100) { + let timer = null + return function () { + let args = arguments + if (timer) { + clearTimeout(timer) + } + timer = setTimeout(() => { + fn.apply(this, args) + }, delay) + } +} + +/** + * 不用正则的方式替换所有值 + * @param text 被替换的字符串 + * @param checker 替换前的内容 + * @param replacer 替换后的内容 + * @returns {String} 替换后的字符串 + */ +export function replaceAll(text, checker, replacer) { + let lastText = text + text = text.replace(checker, replacer) + if (lastText !== text) { + return replaceAll(text, checker, replacer) + } + return text +} + +/** + * 获取事件冒泡路径,兼容 IE11,Edge,Chrome,Firefox,Safari + * 目前使用的地方:JEditableTable Span模式 + */ +export function getEventPath(event) { + let target = event.target + let path = (event.composedPath && event.composedPath()) || event.path + + if (path != null) { + return (path.indexOf(window) < 0) ? path.concat(window) : path + } + + if (target === window) { + return [window] + } + + let getParents = (node, memo) => { + memo = memo || [] + const parentNode = node.parentNode + + if (!parentNode) { + return memo + } else { + return getParents(parentNode, memo.concat(parentNode)) + } + } + return [target].concat(getParents(target), window) +} + +/** + * 根据组件名获取父级 + * @param vm + * @param name + * @returns {Vue | null|null|Vue} + */ +export function getVmParentByName(vm, name) { + let parent = vm.$parent + if (parent && parent.$options) { + if (parent.$options.name === name) { + return parent + } else { + let res = getVmParentByName(parent, name) + if (res) { + return res + } + } + } + return null +} + +/** + * 使一个值永远不会为(null | undefined) + * + * @param value 要处理的值 + * @param def 默认值,如果value为(null | undefined)则返回的默认值,可不传,默认为'' + */ +export function neverNull(value, def) { + return value == null ? (neverNull(def, '')) : value +} + +/** + * 根据元素值移除数组中的一个元素 + * @param array 数组 + * @param prod 属性名 + * @param value 属性值 + * @returns {string} + */ +export function removeArrayElement(array, prod, value) { + let index = -1 + for(let i = 0;i=0){ + array.splice(index, 1); + } } \ No newline at end of file diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/ZyOrdersMapper.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/ZyOrdersMapper.java index 3e6f5aac..daf90ba0 100644 --- a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/ZyOrdersMapper.java +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/ZyOrdersMapper.java @@ -1,23 +1,29 @@ -package org.jeecg.modules.demo.zyorders.mapper; - -import java.util.List; - -import org.apache.ibatis.annotations.Param; -import org.jeecg.modules.demo.zyorders.entity.ZyOrders; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.jeecg.modules.orderbymakeclothplan.vo.TodayOrderAndQIriVo; - -/** - * @Description: 订单基本信息管理 - * @Author: jeecg-boot - * @Date: 2022-12-26 - * @Version: V1.0 - */ -public interface ZyOrdersMapper extends BaseMapper { - - /** - * 获取今日订单及七日订单 - * @return - */ - TodayOrderAndQIriVo getTotalOrderAndWeek(); -} +package org.jeecg.modules.demo.zyorders.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import org.jeecg.modules.demo.zyorders.entity.ZyOrders; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.jeecg.modules.demo.zyorders.vo.ZyNameAndPayMoney; +import org.jeecg.modules.demo.zyorders.vo.ZyOrderPayAndTime; +import org.jeecg.modules.orderbymakeclothplan.vo.TodayOrderAndQIriVo; + +/** + * @Description: 订单基本信息管理 + * @Author: jeecg-boot + * @Date: 2022-12-26 + * @Version: V1.0 + */ +public interface ZyOrdersMapper extends BaseMapper { + + /** + * 获取今日订单及七日订单 + * @return + */ + TodayOrderAndQIriVo getTotalOrderAndWeek(); + + List selectAllShopSalesVolumeByLastM( @Param("start_time") String start_time,@Param("end_time") String end_time,@Param("org_code") String org_code); + + List selectCurrentSales(@Param("id")String id, @Param("start_time")String start_time, @Param("end_time")String end_time); +} diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/xml/ZyOrdersMapper.xml b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/xml/ZyOrdersMapper.xml index 10a898bf..6364e39b 100644 --- a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/xml/ZyOrdersMapper.xml +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/mapper/xml/ZyOrdersMapper.xml @@ -18,4 +18,32 @@ WHERE DATE_SUB( CURDATE(), INTERVAL 7 DAY ) <= DATE( payment_time ) and payment_status=1 and ischild=0 ) b) + + + + + + diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/IZyOrdersService.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/IZyOrdersService.java index 7dc02279..62367174 100644 --- a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/IZyOrdersService.java +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/IZyOrdersService.java @@ -1,34 +1,49 @@ -package org.jeecg.modules.demo.zyorders.service; - -import org.jeecg.common.api.vo.Result; -import org.jeecg.modules.demo.ordergoods.entity.OrderGoodsJk; -import org.jeecg.modules.demo.zyorders.entity.ZyOrders; -import com.baomidou.mybatisplus.extension.service.IService; -import org.jeecg.modules.demo.zyorders.entity.ZyOrdersJk; -import org.jeecg.modules.orderbymakeclothplan.vo.TodayOrderAndQIriVo; - -import java.util.List; - -/** - * @Description: 订单基本信息管理 - * @Author: jeecg-boot - * @Date: 2022-12-26 - * @Version: V1.0 - */ -public interface IZyOrdersService extends IService { - - //大屏数据-获取订单的状态 - List getOrderStatus(); - //大屏数据-获取历史订单 - List getOldOrder(); - //大屏数据-获取今日订单及七日订单 - TodayOrderAndQIriVo getOrder(); - - /** - *订单和订单商品接口 - * @param ordersJk - * @param ogjkList - * @return - */ - List orderJk(ZyOrdersJk ordersJk, List ogjkList); -} +package org.jeecg.modules.demo.zyorders.service; + +import org.jeecg.common.api.vo.Result; +import org.jeecg.modules.demo.ordergoods.entity.OrderGoodsJk; +import org.jeecg.modules.demo.zyorders.entity.ZyOrders; +import com.baomidou.mybatisplus.extension.service.IService; +import org.jeecg.modules.demo.zyorders.entity.ZyOrdersJk; +import org.jeecg.modules.largeScreen.vo.Type; +import org.jeecg.modules.orderbymakeclothplan.vo.TodayOrderAndQIriVo; + +import java.util.List; +import java.util.Map; + +/** + * @Description: 订单基本信息管理 + * @Author: jeecg-boot + * @Date: 2022-12-26 + * @Version: V1.0 + */ +public interface IZyOrdersService extends IService { + + //大屏数据-获取订单的状态 + List getOrderStatus(); + //大屏数据-获取历史订单 + List getOldOrder(); + //大屏数据-获取今日订单及七日订单 + TodayOrderAndQIriVo getOrder(); + + /** + *订单和订单商品接口 + * @param ordersJk + * @param ogjkList + * @return + */ + List orderJk(ZyOrdersJk ordersJk, List ogjkList); + + /** + * + * @param org_code 店铺类型 + * @return + */ + List> selectAllShopSalesVolumeByLastM(String org_code); + + /** + *查询所有店铺前十二个月的月销售额 + * @return + */ + List getsales12Month(); +} diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/impl/ZyOrdersServiceImpl.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/impl/ZyOrdersServiceImpl.java index 20cf5508..3d81e8a1 100644 --- a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/impl/ZyOrdersServiceImpl.java +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/service/impl/ZyOrdersServiceImpl.java @@ -28,19 +28,24 @@ import org.jeecg.modules.demo.zyorders.entity.ZyOrders; import org.jeecg.modules.demo.zyorders.entity.ZyOrdersJk; import org.jeecg.modules.demo.zyorders.mapper.ZyOrdersMapper; import org.jeecg.modules.demo.zyorders.service.IZyOrdersService; +import org.jeecg.modules.demo.zyorders.vo.ZyNameAndPayMoney; +import org.jeecg.modules.demo.zyorders.vo.ZyOrderPayAndTime; +import org.jeecg.modules.largeScreen.vo.Type; +import org.jeecg.modules.largeScreen.vo.ZyShopSales; import org.jeecg.modules.message.entity.ZySpeechMessage; import org.jeecg.modules.message.mapper.ZySpeechMessageMapper; import org.jeecg.modules.orderbymakeclothplan.vo.TodayOrderAndQIriVo; +import org.jeecg.modules.shop.utils.GetTime; +import org.jeecg.modules.shop.utils.mapSort; +import org.jeecg.modules.system.entity.SysDepart; +import org.jeecg.modules.system.service.ISysDepartService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; +import java.util.*; import java.util.stream.Collectors; /** @@ -105,6 +110,10 @@ public class ZyOrdersServiceImpl extends ServiceImpl i @Autowired private IZyClothsTypeService zyClothsTypeService; + //店铺/部门 + @Autowired + private ISysDepartService sysDepartService; + /** * 大屏数据-获取订单的状态 * @@ -343,6 +352,98 @@ public class ZyOrdersServiceImpl extends ServiceImpl i return ids; } + @Override + public List> selectAllShopSalesVolumeByLastM(String org_code) { + Map map = new HashMap<>(); + String beginOfMonth = GetTime.beginOfMonth(); + String endOfMonth = GetTime.endOfMonth(); + List list = baseMapper.selectAllShopSalesVolumeByLastM(beginOfMonth, endOfMonth,org_code); + //将list转换成map,同时将所有相同店铺名称的销售额相加 + if (list.isEmpty()) { + return null; + } else { + map.put(list.get(0).getName(), list.get(0).getTotalMoney()); + } + for (int i = 1; i < list.size(); i++) { + if (map.containsKey(list.get(i).getName())) { + int y = map.get(list.get(i).getName()) + list.get(i).getTotalMoney(); + map.put(list.get(i).getName(), y); + } else { + map.put(list.get(i).getName(), list.get(i).getTotalMoney()); + } + } + List> list1 = mapSort.sortMapByValue(map); + return list1; + } + + /** + * 查询所有店铺前十二个月的月销售额 + * @return + */ + @Override + public List getsales12Month() { + Calendar calendar = Calendar.getInstance(); + String start_time = GetTime.getLastTwelveMonths(); + String end_time = GetTime.getLastMonthEnd(); + QueryWrapper depWra=new QueryWrapper(); + String[] a3 = {"4","5"}; + depWra.in("org_category",a3); + List depList = sysDepartService.list(depWra); + List ls = new ArrayList<>(); + for (int i = 0; i < depList.size(); i++) { + SysDepart item = depList.get(i); + Type type = new Type(); + List list = baseMapper.selectCurrentSales(item.getId(), start_time, end_time); + HashMap map1 = new HashMap<>(); + List salesList = new ArrayList<>(); + int lastmonths = calendar.get(Calendar.MONTH); + int lastTwelveMonths = 12 - (12 - lastmonths) + 1; + for (int sw = lastTwelveMonths; sw <= 12; sw++) { + ZyShopSales zyShopSales = new ZyShopSales(); + zyShopSales.setMonthDay(sw); + zyShopSales.setMoney(0); + salesList.add(zyShopSales); + } + for (int ws = 1; ws <= lastmonths; ws++) { + ZyShopSales zyShopSales = new ZyShopSales(); + zyShopSales.setMonthDay(ws); + zyShopSales.setMoney(0); + salesList.add(zyShopSales); + } + if (!list.isEmpty()) { + Integer totalMoney = list.get(0).getTotalMoney(); + Date payTime1 = list.get(0).getPayTime(); + String format1 = String.format("%tm", payTime1); + int b = Integer.parseInt(format1); + map1.put(b, totalMoney); + } + for (int j = 1; j < list.size(); j++) { + Date payTime = list.get(j).getPayTime(); + String format = String.format("%tm", payTime); + int a = Integer.parseInt(format); + if (map1.containsKey(a)) { + int money = map1.get(a) + list.get(j).getTotalMoney(); + map1.put(a, money); + } else { + map1.put(a, list.get(j).getTotalMoney()); + } + } + for (Integer key : map1.keySet()) { + for (int w = 0; w < salesList.size(); w++) { + Integer monthDay = salesList.get(w).getMonthDay(); + if (monthDay.equals(key)) { + salesList.get(w).setMoney(map1.get(key)); + } + } + } + + type.setName(item.getDepartName()); + type.setLs(salesList); + ls.add(type); + } + return ls; + } + /** * 生成订单编号 diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/vo/ZyNameAndPayMoney.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/vo/ZyNameAndPayMoney.java new file mode 100644 index 00000000..bb86837f --- /dev/null +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/vo/ZyNameAndPayMoney.java @@ -0,0 +1,24 @@ +package org.jeecg.modules.demo.zyorders.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.jeecgframework.poi.excel.annotation.Excel; + +@Data +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@ApiModel(value="ZyShopNameAndPayMoney对象", description="ZyShopNameAndPayMoney对象") +public class ZyNameAndPayMoney { + /**店名*/ + @Excel(name = "店名", width = 15) + @ApiModelProperty(value = "店名") + private String name; + //金额 + @Excel(name = "金额", width = 15) + @ApiModelProperty(value = "金额") + private Integer totalMoney; + +} diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/vo/ZyOrderPayAndTime.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/vo/ZyOrderPayAndTime.java new file mode 100644 index 00000000..36498626 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/demo/zyorders/vo/ZyOrderPayAndTime.java @@ -0,0 +1,13 @@ +package org.jeecg.modules.demo.zyorders.vo; + +import lombok.Data; + +import java.util.Date; + +@Data +public class ZyOrderPayAndTime { + + private Integer totalMoney; + + private Date payTime; +} diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/hangerlocation/service/impl/HangerLocationServiceImpl.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/hangerlocation/service/impl/HangerLocationServiceImpl.java index b55b2166..1b64ca2b 100644 --- a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/hangerlocation/service/impl/HangerLocationServiceImpl.java +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/hangerlocation/service/impl/HangerLocationServiceImpl.java @@ -317,8 +317,9 @@ public class HangerLocationServiceImpl extends ServiceImpl selectAllShopSalesVolumeByThisD() { + List list = zyOrdersService.selectAllShopSalesVolumeByLastM("4"); + return Result.OK(list); + } + + @AutoLog(value = "查询网店店铺本月销售额") + @ApiOperation(value = "查询网店店铺本月销售额", notes = "查询网店店铺本月销售额") + @GetMapping("/selectAllShopSalesVolumeByThisW") + public Result selectAllShopSalesVolumeByThisW() { + List list = zyOrdersService.selectAllShopSalesVolumeByLastM("5"); + return Result.OK(list); + } + @AutoLog(value = "查询所有店铺前十二个月的月销售额") + @ApiOperation(value = "查询所有店铺前十二个月的月销售额", notes = "查询所有店铺前十二个月的月销售额") + @GetMapping("/getsales12Month") + public Result getsales12Month() { + List list = zyOrdersService.getsales12Month(); + if (list.isEmpty()){ + return Result.OK("未查询到结果"); + } + return Result.OK(list); + } } diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/largeScreen/vo/Type.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/largeScreen/vo/Type.java new file mode 100644 index 00000000..027818f5 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/largeScreen/vo/Type.java @@ -0,0 +1,11 @@ +package org.jeecg.modules.largeScreen.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class Type { + private String name; + List ls; +} diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/largeScreen/vo/ZyShopSales.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/largeScreen/vo/ZyShopSales.java new file mode 100644 index 00000000..e495dc46 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/largeScreen/vo/ZyShopSales.java @@ -0,0 +1,12 @@ +package org.jeecg.modules.largeScreen.vo; + +import lombok.Data; + +@Data +public class ZyShopSales { + + private Integer monthDay; + + private Integer money; + +} diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/ISysDepartService.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/ISysDepartService.java index 33a59d7e..a6ef89cc 100644 --- a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/ISysDepartService.java +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/ISysDepartService.java @@ -1,145 +1,146 @@ -package org.jeecg.modules.system.service; - -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.extension.service.IService; -import org.jeecg.modules.system.entity.SysDepart; -import org.jeecg.modules.system.model.DepartIdModel; -import org.jeecg.modules.system.model.SysDepartTreeModel; -import java.util.List; - -/** - *

- * 部门表 服务实现类 - *

- * - * @Author:Steve - * @Since: 2019-01-22 - */ -public interface ISysDepartService extends IService{ - - /** - * 查询我的部门信息,并分节点进行显示 - * @return - */ - List queryMyDeptTreeList(String departIds); - - /** - * 查询所有部门信息,并分节点进行显示 - * @return - */ - List queryTreeList(); - /** - * 查询所有部门信息,并分节点进行显示 - * @return - */ - List queryTreeList1(); - - /** - * 查询所有部门DepartId信息,并分节点进行显示 - * @return - */ - public List queryDepartIdTreeList(); - - /** - * 保存部门数据 - * @param sysDepart - */ - void saveDepartData(SysDepart sysDepart,String username); - - /** - * 更新depart数据 - * @param sysDepart - * @return - */ - Boolean updateDepartDataById(SysDepart sysDepart,String username); - - /** - * 删除depart数据 - * @param id - * @return - */ - /* boolean removeDepartDataById(String id); */ - - /** - * 根据关键字搜索相关的部门数据 - * @param keyWord - * @return - */ - List searhBy(String keyWord,String myDeptSearch,String departIds); - - /** - * 根据部门id删除并删除其可能存在的子级部门 - * @param id - * @return - */ - boolean delete(String id); - - /** - * 查询SysDepart集合 - * @param userId - * @return - */ - public List queryUserDeparts(String userId); - - /** - * 根据用户名查询部门 - * - * @param username - * @return - */ - List queryDepartsByUsername(String username); - - /** - * 根据部门id批量删除并删除其可能存在的子级部门 - * @param id - * @return - */ - void deleteBatchWithChildren(List ids); - - /** - * 根据部门Id查询,当前和下级所有部门IDS - * @param departId - * @return - */ - List getSubDepIdsByDepId(String departId); - - /** - * 获取我的部门下级所有部门IDS - * @return - */ - List getMySubDepIdsByDepId(String departIds); - /** - * 根据关键字获取部门信息(通讯录) - * @return - */ - List queryTreeByKeyWord(String keyWord); - /** - * 获取我的部门下级所有部门 - * @return - */ - List queryTreeListByPid(String parentId); - - /** - * 获取某个部门的所有父级部门的ID - * - * @param departId 根据departId查 - */ - JSONObject queryAllParentIdByDepartId(String departId); - - /** - * 获取某个部门的所有父级部门的ID - * - * @param orgCode 根据orgCode查 - */ - JSONObject queryAllParentIdByOrgCode(String orgCode); - /** - * 获取公司信息 - * @return - */ - SysDepart queryCompByOrgCode(String orgCode); - /** - * 获取下级部门 - * @return - */ - List queryDeptByPid(String pid); -} +package org.jeecg.modules.system.service; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.service.IService; +import org.jeecg.modules.system.entity.SysDepart; +import org.jeecg.modules.system.model.DepartIdModel; +import org.jeecg.modules.system.model.SysDepartTreeModel; +import java.util.List; + +/** + *

+ * 部门表 服务实现类 + *

+ * + * @Author:Steve + * @Since: 2019-01-22 + */ +public interface ISysDepartService extends IService{ + + /** + * 查询我的部门信息,并分节点进行显示 + * @return + */ + List queryMyDeptTreeList(String departIds); + + /** + * 查询所有部门信息,并分节点进行显示 + * @return + */ + List queryTreeList(); + /** + * 查询所有部门信息,并分节点进行显示 + * @return + */ + List queryTreeList1(); + + /** + * 查询所有部门DepartId信息,并分节点进行显示 + * @return + */ + public List queryDepartIdTreeList(); + + /** + * 保存部门数据 + * @param sysDepart + */ + void saveDepartData(SysDepart sysDepart,String username); + + /** + * 更新depart数据 + * @param sysDepart + * @return + */ + Boolean updateDepartDataById(SysDepart sysDepart,String username); + + /** + * 删除depart数据 + * @param id + * @return + */ + /* boolean removeDepartDataById(String id); */ + + /** + * 根据关键字搜索相关的部门数据 + * @param keyWord + * @return + */ + List searhBy(String keyWord,String myDeptSearch,String departIds); + + /** + * 根据部门id删除并删除其可能存在的子级部门 + * @param id + * @return + */ + boolean delete(String id); + + /** + * 查询SysDepart集合 + * @param userId + * @return + */ + public List queryUserDeparts(String userId); + + /** + * 根据用户名查询部门 + * + * @param username + * @return + */ + List queryDepartsByUsername(String username); + + /** + * 根据部门id批量删除并删除其可能存在的子级部门 + * @param id + * @return + */ + void deleteBatchWithChildren(List ids); + + /** + * 根据部门Id查询,当前和下级所有部门IDS + * @param departId + * @return + */ + List getSubDepIdsByDepId(String departId); + + /** + * 获取我的部门下级所有部门IDS + * @return + */ + List getMySubDepIdsByDepId(String departIds); + /** + * 根据关键字获取部门信息(通讯录) + * @return + */ + List queryTreeByKeyWord(String keyWord); + /** + * 获取我的部门下级所有部门 + * @return + */ + List queryTreeListByPid(String parentId); + + /** + * 获取某个部门的所有父级部门的ID + * + * @param departId 根据departId查 + */ + JSONObject queryAllParentIdByDepartId(String departId); + + /** + * 获取某个部门的所有父级部门的ID + * + * @param orgCode 根据orgCode查 + */ + JSONObject queryAllParentIdByOrgCode(String orgCode); + /** + * 获取公司信息 + * @return + */ + SysDepart queryCompByOrgCode(String orgCode); + /** + * 获取下级部门 + * @return + */ + List queryDeptByPid(String pid); + +} diff --git a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/impl/SysDepartServiceImpl.java b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/impl/SysDepartServiceImpl.java index 4915de3d..e797e9a9 100644 --- a/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/impl/SysDepartServiceImpl.java +++ b/jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/service/impl/SysDepartServiceImpl.java @@ -1,580 +1,580 @@ -package org.jeecg.modules.system.service.impl; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import io.netty.util.internal.StringUtil; -import org.apache.commons.lang.StringUtils; -import org.jeecg.common.constant.CacheConstant; -import org.jeecg.common.constant.CommonConstant; -import org.jeecg.common.constant.FillRuleConstant; -import org.jeecg.common.util.FillRuleUtil; -import org.jeecg.common.util.YouBianCodeUtil; -import org.jeecg.common.util.oConvertUtils; -import org.jeecg.modules.system.entity.*; -import org.jeecg.modules.system.mapper.*; -import org.jeecg.modules.system.model.DepartIdModel; -import org.jeecg.modules.system.model.SysDepartTreeModel; -import org.jeecg.modules.system.service.ISysDepartService; -import org.jeecg.modules.system.util.FindsDepartsChildrenUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.*; - -/** - *

- * 部门表 服务实现类 - *

- * - * @Author Steve - * @Since 2019-01-22 - */ -@Service -public class SysDepartServiceImpl extends ServiceImpl implements ISysDepartService { - - @Autowired - private SysUserDepartMapper userDepartMapper; - @Autowired - private SysDepartRoleMapper sysDepartRoleMapper; - @Autowired - private SysDepartPermissionMapper departPermissionMapper; - @Autowired - private SysDepartRolePermissionMapper departRolePermissionMapper; - @Autowired - private SysDepartRoleUserMapper departRoleUserMapper; - @Autowired - private SysUserMapper sysUserMapper; - - @Override - public List queryMyDeptTreeList(String departIds) { - //根据部门id获取所负责部门 - LambdaQueryWrapper query = new LambdaQueryWrapper(); - String[] codeArr = this.getMyDeptParentOrgCode(departIds); - for(int i=0;i listDepts = this.list(query); - for(int i=0;i listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(listDepts); - return listResult; - } - - /** - * queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端 - */ -// @Cacheable(value = CacheConstant.SYS_DEPARTS_CACHE)//缓存 - @Override - public List queryTreeList() { - LambdaQueryWrapper query = new LambdaQueryWrapper(); - query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); - query.orderByAsc(SysDepart::getDepartOrder); - List list = this.list(query); - // 调用wrapTreeDataToTreeList方法生成树状数据 - List listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list); - return listResult; - } - /** - * queryTreeList1 对应 queryTreeList1 查询所有的部门数据,以树结构形式响应给前端 - */ - @Override - public List queryTreeList1() { - LambdaQueryWrapper query = new LambdaQueryWrapper(); - query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); - query.in(SysDepart::getOrgCategory,4,5); - query.orderByAsc(SysDepart::getDepartOrder); - List list = this.list(query); - // 调用wrapTreeDataToTreeList方法生成树状数据 - List listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list); - return listResult; - } - - @Cacheable(value = CacheConstant.SYS_DEPART_IDS_CACHE) - @Override - public List queryDepartIdTreeList() { - LambdaQueryWrapper query = new LambdaQueryWrapper(); - query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); - query.orderByAsc(SysDepart::getDepartOrder); - List list = this.list(query); - // 调用wrapTreeDataToTreeList方法生成树状数据 - List listResult = FindsDepartsChildrenUtil.wrapTreeDataToDepartIdTreeList(list); - return listResult; - } - - /** - * saveDepartData 对应 add 保存用户在页面添加的新的部门对象数据 - */ - @Override - @Transactional - public void saveDepartData(SysDepart sysDepart, String username) { - if (sysDepart != null && username != null) { - if (sysDepart.getParentId() == null) { - sysDepart.setParentId(""); - } - String s = UUID.randomUUID().toString().replace("-", ""); - sysDepart.setId(s); - // 先判断该对象有无父级ID,有则意味着不是最高级,否则意味着是最高级 - // 获取父级ID - String parentId = sysDepart.getParentId(); - //update-begin--Author:baihailong Date:20191209 for:部门编码规则生成器做成公用配置 - JSONObject formData = new JSONObject(); - formData.put("parentId",parentId); - String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.DEPART,formData); - //update-end--Author:baihailong Date:20191209 for:部门编码规则生成器做成公用配置 - sysDepart.setOrgCode(codeArray[0]); - String orgType = codeArray[1]; - sysDepart.setOrgType(String.valueOf(orgType)); - sysDepart.setCreateTime(new Date()); - sysDepart.setDelFlag(CommonConstant.DEL_FLAG_0.toString()); - this.save(sysDepart); - } - - } - - /** - * saveDepartData 的调用方法,生成部门编码和部门类型(作废逻辑) - * @deprecated - * @param parentId - * @return - */ - private String[] generateOrgCode(String parentId) { - //update-begin--Author:Steve Date:20190201 for:组织机构添加数据代码调整 - LambdaQueryWrapper query = new LambdaQueryWrapper(); - LambdaQueryWrapper query1 = new LambdaQueryWrapper(); - String[] strArray = new String[2]; - // 创建一个List集合,存储查询返回的所有SysDepart对象 - List departList = new ArrayList<>(); - // 定义新编码字符串 - String newOrgCode = ""; - // 定义旧编码字符串 - String oldOrgCode = ""; - // 定义部门类型 - String orgType = ""; - // 如果是最高级,则查询出同级的org_code, 调用工具类生成编码并返回 - if (StringUtil.isNullOrEmpty(parentId)) { - // 线判断数据库中的表是否为空,空则直接返回初始编码 - query1.eq(SysDepart::getParentId, "").or().isNull(SysDepart::getParentId); - query1.orderByDesc(SysDepart::getOrgCode); - departList = this.list(query1); - if(departList == null || departList.size() == 0) { - strArray[0] = YouBianCodeUtil.getNextYouBianCode(null); - strArray[1] = "1"; - return strArray; - }else { - SysDepart depart = departList.get(0); - oldOrgCode = depart.getOrgCode(); - orgType = depart.getOrgType(); - newOrgCode = YouBianCodeUtil.getNextYouBianCode(oldOrgCode); - } - } else { // 反之则查询出所有同级的部门,获取结果后有两种情况,有同级和没有同级 - // 封装查询同级的条件 - query.eq(SysDepart::getParentId, parentId); - // 降序排序 - query.orderByDesc(SysDepart::getOrgCode); - // 查询出同级部门的集合 - List parentList = this.list(query); - // 查询出父级部门 - SysDepart depart = this.getById(parentId); - // 获取父级部门的Code - String parentCode = depart.getOrgCode(); - // 根据父级部门类型算出当前部门的类型 - orgType = String.valueOf(Integer.valueOf(depart.getOrgType()) + 1); - // 处理同级部门为null的情况 - if (parentList == null || parentList.size() == 0) { - // 直接生成当前的部门编码并返回 - newOrgCode = YouBianCodeUtil.getSubYouBianCode(parentCode, null); - } else { //处理有同级部门的情况 - // 获取同级部门的编码,利用工具类 - String subCode = parentList.get(0).getOrgCode(); - // 返回生成的当前部门编码 - newOrgCode = YouBianCodeUtil.getSubYouBianCode(parentCode, subCode); - } - } - // 返回最终封装了部门编码和部门类型的数组 - strArray[0] = newOrgCode; - strArray[1] = orgType; - return strArray; - //update-end--Author:Steve Date:20190201 for:组织机构添加数据代码调整 - } - - - /** - * removeDepartDataById 对应 delete方法 根据ID删除相关部门数据 - * - */ - /* - * @Override - * - * @Transactional public boolean removeDepartDataById(String id) { - * System.out.println("要删除的ID 为=============================>>>>>"+id); boolean - * flag = this.removeById(id); return flag; } - */ - - /** - * updateDepartDataById 对应 edit 根据部门主键来更新对应的部门数据 - */ - @Override - @Transactional - public Boolean updateDepartDataById(SysDepart sysDepart, String username) { - if (sysDepart != null && username != null) { - sysDepart.setUpdateTime(new Date()); - sysDepart.setUpdateBy(username); - this.updateById(sysDepart); - return true; - } else { - return false; - } - - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void deleteBatchWithChildren(List ids) { - List idList = new ArrayList(); - for(String id: ids) { - idList.add(id); - this.checkChildrenExists(id, idList); - } - this.removeByIds(idList); - //根据部门id获取部门角色id - List roleIdList = new ArrayList<>(); - LambdaQueryWrapper query = new LambdaQueryWrapper<>(); - query.select(SysDepartRole::getId).in(SysDepartRole::getDepartId, idList); - List depRoleList = sysDepartRoleMapper.selectList(query); - for(SysDepartRole deptRole : depRoleList){ - roleIdList.add(deptRole.getId()); - } - //根据部门id删除用户与部门关系 - userDepartMapper.delete(new LambdaQueryWrapper().in(SysUserDepart::getDepId,idList)); - //根据部门id删除部门授权 - departPermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartPermission::getDepartId,idList)); - //根据部门id删除部门角色 - sysDepartRoleMapper.delete(new LambdaQueryWrapper().in(SysDepartRole::getDepartId,idList)); - if(roleIdList != null && roleIdList.size()>0){ - //根据角色id删除部门角色授权 - departRolePermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartRolePermission::getRoleId,roleIdList)); - //根据角色id删除部门角色用户信息 - departRoleUserMapper.delete(new LambdaQueryWrapper().in(SysDepartRoleUser::getDroleId,roleIdList)); - } - } - - @Override - public List getSubDepIdsByDepId(String departId) { - return this.baseMapper.getSubDepIdsByDepId(departId); - } - - @Override - public List getMySubDepIdsByDepId(String departIds) { - //根据部门id获取所负责部门 - String[] codeArr = this.getMyDeptParentOrgCode(departIds); - return this.baseMapper.getSubDepIdsByOrgCodes(codeArr); - } - - /** - *

- * 根据关键字搜索相关的部门数据 - *

- */ - @Override - public List searhBy(String keyWord,String myDeptSearch,String departIds) { - LambdaQueryWrapper query = new LambdaQueryWrapper(); - List newList = new ArrayList<>(); - //myDeptSearch不为空时为我的部门搜索,只搜索所负责部门 - if(!StringUtil.isNullOrEmpty(myDeptSearch)){ - //departIds 为空普通用户或没有管理部门 - if(StringUtil.isNullOrEmpty(departIds)){ - return newList; - } - //根据部门id获取所负责部门 - String[] codeArr = this.getMyDeptParentOrgCode(departIds); - for(int i=0;i departList = this.list(query); - if(departList.size() > 0) { - for(SysDepart depart : departList) { - model = new SysDepartTreeModel(depart); - model.setChildren(null); - //update-end--Author:huangzhilin Date:20140417 for:[bugfree号]组织机构搜索功回显优化---------------------- - newList.add(model); - } - return newList; - } - return null; - } - - /** - * 根据部门id删除并且删除其可能存在的子级任何部门 - */ - @Override - @Transactional(rollbackFor = Exception.class) - public boolean delete(String id) { - List idList = new ArrayList<>(); - idList.add(id); - this.checkChildrenExists(id, idList); - //清空部门树内存 - //FindsDepartsChildrenUtil.clearDepartIdModel(); - boolean ok = this.removeByIds(idList); - //根据部门id获取部门角色id - List roleIdList = new ArrayList<>(); - LambdaQueryWrapper query = new LambdaQueryWrapper<>(); - query.select(SysDepartRole::getId).in(SysDepartRole::getDepartId, idList); - List depRoleList = sysDepartRoleMapper.selectList(query); - for(SysDepartRole deptRole : depRoleList){ - roleIdList.add(deptRole.getId()); - } - //根据部门id删除用户与部门关系 - userDepartMapper.delete(new LambdaQueryWrapper().in(SysUserDepart::getDepId,idList)); - //根据部门id删除部门授权 - departPermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartPermission::getDepartId,idList)); - //根据部门id删除部门角色 - sysDepartRoleMapper.delete(new LambdaQueryWrapper().in(SysDepartRole::getDepartId,idList)); - if(roleIdList != null && roleIdList.size()>0){ - //根据角色id删除部门角色授权 - departRolePermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartRolePermission::getRoleId,roleIdList)); - //根据角色id删除部门角色用户信息 - departRoleUserMapper.delete(new LambdaQueryWrapper().in(SysDepartRoleUser::getDroleId,roleIdList)); - } - return ok; - } - - /** - * delete 方法调用 - * @param id - * @param idList - */ - private void checkChildrenExists(String id, List idList) { - LambdaQueryWrapper query = new LambdaQueryWrapper(); - query.eq(SysDepart::getParentId,id); - List departList = this.list(query); - if(departList != null && departList.size() > 0) { - for(SysDepart depart : departList) { - idList.add(depart.getId()); - this.checkChildrenExists(depart.getId(), idList); - } - } - } - - @Override - public List queryUserDeparts(String userId) { - return baseMapper.queryUserDeparts(userId); - } - - @Override - public List queryDepartsByUsername(String username) { - return baseMapper.queryDepartsByUsername(username); - } - - /** - * 根据用户所负责部门ids获取父级部门编码 - * @param departIds - * @return - */ - private String[] getMyDeptParentOrgCode(String departIds){ - //根据部门id查询所负责部门 - LambdaQueryWrapper query = new LambdaQueryWrapper(); - query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); - query.in(SysDepart::getId, Arrays.asList(departIds.split(","))); - query.orderByAsc(SysDepart::getOrgCode); - List list = this.list(query); - //查找根部门 - if(list == null || list.size()==0){ - return null; - } - String orgCode = this.getMyDeptParentNode(list); - String[] codeArr = orgCode.split(","); - return codeArr; - } - - /** - * 获取负责部门父节点 - * @param list - * @return - */ - private String getMyDeptParentNode(List list){ - Map map = new HashMap<>(); - //1.先将同一公司归类 - for(SysDepart dept : list){ - String code = dept.getOrgCode().substring(0,3); - if(map.containsKey(code)){ - String mapCode = map.get(code)+","+dept.getOrgCode(); - map.put(code,mapCode); - }else{ - map.put(code,dept.getOrgCode()); - } - } - StringBuffer parentOrgCode = new StringBuffer(); - //2.获取同一公司的根节点 - for(String str : map.values()){ - String[] arrStr = str.split(","); - parentOrgCode.append(",").append(this.getMinLengthNode(arrStr)); - } - return parentOrgCode.substring(1); - } - - /** - * 获取同一公司中部门编码长度最小的部门 - * @param str - * @return - */ - private String getMinLengthNode(String[] str){ - int min =str[0].length(); - String orgCode = str[0]; - for(int i =1;i queryTreeByKeyWord(String keyWord) { - LambdaQueryWrapper query = new LambdaQueryWrapper(); - query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); - query.orderByAsc(SysDepart::getDepartOrder); - List list = this.list(query); - // 调用wrapTreeDataToTreeList方法生成树状数据 - List listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list); - List treelist =new ArrayList<>(); - if(StringUtils.isNotBlank(keyWord)){ - this.getTreeByKeyWord(keyWord,listResult,treelist); - }else{ - return listResult; - } - return treelist; - } - - /** - * 根据parentId查询部门树 - * @param parentId - * @return - */ - @Override - public List queryTreeListByPid(String parentId) { - List list = this.baseMapper.queryTreeListByPid(parentId); - List records = new ArrayList<>(); - for (int i = 0; i < list.size(); i++) { - SysDepart depart = list.get(i); - SysDepartTreeModel treeModel = new SysDepartTreeModel(depart); - //TODO 异步树加载key拼接__+时间戳,以便于每次展开节点会刷新数据 - //treeModel.setKey(treeModel.getKey()+"__"+System.currentTimeMillis()); - treeModel.setKey(treeModel.getKey()); - Integer count=this.baseMapper.queryCountByPid(depart.getId()); - if(count>0){ - treeModel.setIsLeaf(false); - }else{ - treeModel.setIsLeaf(true); - } - records.add(treeModel); - } - return records; - } - - @Override - public JSONObject queryAllParentIdByDepartId(String departId) { - JSONObject result = new JSONObject(); - for (String id : departId.split(",")) { - JSONObject all = this.queryAllParentId("id", id); - result.put(id, all); - } - return result; - } - - @Override - public JSONObject queryAllParentIdByOrgCode(String orgCode) { - JSONObject result = new JSONObject(); - for (String code : orgCode.split(",")) { - JSONObject all = this.queryAllParentId("org_code", code); - result.put(code, all); - } - return result; - } - - /** - * 查询某个部门的所有父ID信息 - * - * @param fieldName 字段名 - * @param value 值 - */ - private JSONObject queryAllParentId(String fieldName, String value) { - JSONObject data = new JSONObject(); - // 父ID集合,有序 - data.put("parentIds", new JSONArray()); - // 父ID的部门数据,key是id,value是数据 - data.put("parentMap", new JSONObject()); - this.queryAllParentIdRecursion(fieldName, value, data); - return data; - } - - /** - * 递归调用查询父部门接口 - */ - private void queryAllParentIdRecursion(String fieldName, String value, JSONObject data) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq(fieldName, value); - SysDepart depart = super.getOne(queryWrapper); - if (depart != null) { - data.getJSONArray("parentIds").add(0, depart.getId()); - data.getJSONObject("parentMap").put(depart.getId(), depart); - if (oConvertUtils.isNotEmpty(depart.getParentId())) { - this.queryAllParentIdRecursion("id", depart.getParentId(), data); - } - } - } - - @Override - public SysDepart queryCompByOrgCode(String orgCode) { - int length = YouBianCodeUtil.zhanweiLength; - String compyOrgCode = orgCode.substring(0,length); - return this.baseMapper.queryCompByOrgCode(compyOrgCode); - } - /** - * 根据id查询下级部门 - * @param pid - * @return - */ - @Override - public List queryDeptByPid(String pid) { - return this.baseMapper.queryDeptByPid(pid); - } - /** - * 根据关键字筛选部门信息 - * @param keyWord - * @return - */ - public void getTreeByKeyWord(String keyWord,List allResult,List newResult){ - for (SysDepartTreeModel model:allResult) { - if (model.getDepartName().contains(keyWord)){ - newResult.add(model); - continue; - }else if(model.getChildren()!=null){ - getTreeByKeyWord(keyWord,model.getChildren(),newResult); - } - } - } -} +package org.jeecg.modules.system.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import io.netty.util.internal.StringUtil; +import org.apache.commons.lang.StringUtils; +import org.jeecg.common.constant.CacheConstant; +import org.jeecg.common.constant.CommonConstant; +import org.jeecg.common.constant.FillRuleConstant; +import org.jeecg.common.util.FillRuleUtil; +import org.jeecg.common.util.YouBianCodeUtil; +import org.jeecg.common.util.oConvertUtils; +import org.jeecg.modules.system.entity.*; +import org.jeecg.modules.system.mapper.*; +import org.jeecg.modules.system.model.DepartIdModel; +import org.jeecg.modules.system.model.SysDepartTreeModel; +import org.jeecg.modules.system.service.ISysDepartService; +import org.jeecg.modules.system.util.FindsDepartsChildrenUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; + +/** + *

+ * 部门表 服务实现类 + *

+ * + * @Author Steve + * @Since 2019-01-22 + */ +@Service +public class SysDepartServiceImpl extends ServiceImpl implements ISysDepartService { + + @Autowired + private SysUserDepartMapper userDepartMapper; + @Autowired + private SysDepartRoleMapper sysDepartRoleMapper; + @Autowired + private SysDepartPermissionMapper departPermissionMapper; + @Autowired + private SysDepartRolePermissionMapper departRolePermissionMapper; + @Autowired + private SysDepartRoleUserMapper departRoleUserMapper; + @Autowired + private SysUserMapper sysUserMapper; + + @Override + public List queryMyDeptTreeList(String departIds) { + //根据部门id获取所负责部门 + LambdaQueryWrapper query = new LambdaQueryWrapper(); + String[] codeArr = this.getMyDeptParentOrgCode(departIds); + for(int i=0;i listDepts = this.list(query); + for(int i=0;i listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(listDepts); + return listResult; + } + + /** + * queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端 + */ +// @Cacheable(value = CacheConstant.SYS_DEPARTS_CACHE)//缓存 + @Override + public List queryTreeList() { + LambdaQueryWrapper query = new LambdaQueryWrapper(); + query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); + query.orderByAsc(SysDepart::getDepartOrder); + List list = this.list(query); + // 调用wrapTreeDataToTreeList方法生成树状数据 + List listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list); + return listResult; + } + /** + * queryTreeList1 对应 queryTreeList1 查询所有的部门数据,以树结构形式响应给前端 + */ + @Override + public List queryTreeList1() { + LambdaQueryWrapper query = new LambdaQueryWrapper(); + query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); + query.in(SysDepart::getOrgCategory,4,5); + query.orderByAsc(SysDepart::getDepartOrder); + List list = this.list(query); + // 调用wrapTreeDataToTreeList方法生成树状数据 + List listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list); + return listResult; + } + + @Cacheable(value = CacheConstant.SYS_DEPART_IDS_CACHE) + @Override + public List queryDepartIdTreeList() { + LambdaQueryWrapper query = new LambdaQueryWrapper(); + query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); + query.orderByAsc(SysDepart::getDepartOrder); + List list = this.list(query); + // 调用wrapTreeDataToTreeList方法生成树状数据 + List listResult = FindsDepartsChildrenUtil.wrapTreeDataToDepartIdTreeList(list); + return listResult; + } + + /** + * saveDepartData 对应 add 保存用户在页面添加的新的部门对象数据 + */ + @Override + @Transactional + public void saveDepartData(SysDepart sysDepart, String username) { + if (sysDepart != null && username != null) { + if (sysDepart.getParentId() == null) { + sysDepart.setParentId(""); + } + String s = UUID.randomUUID().toString().replace("-", ""); + sysDepart.setId(s); + // 先判断该对象有无父级ID,有则意味着不是最高级,否则意味着是最高级 + // 获取父级ID + String parentId = sysDepart.getParentId(); + //update-begin--Author:baihailong Date:20191209 for:部门编码规则生成器做成公用配置 + JSONObject formData = new JSONObject(); + formData.put("parentId",parentId); + String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.DEPART,formData); + //update-end--Author:baihailong Date:20191209 for:部门编码规则生成器做成公用配置 + sysDepart.setOrgCode(codeArray[0]); + String orgType = codeArray[1]; + sysDepart.setOrgType(String.valueOf(orgType)); + sysDepart.setCreateTime(new Date()); + sysDepart.setDelFlag(CommonConstant.DEL_FLAG_0.toString()); + this.save(sysDepart); + } + + } + + /** + * saveDepartData 的调用方法,生成部门编码和部门类型(作废逻辑) + * @deprecated + * @param parentId + * @return + */ + private String[] generateOrgCode(String parentId) { + //update-begin--Author:Steve Date:20190201 for:组织机构添加数据代码调整 + LambdaQueryWrapper query = new LambdaQueryWrapper(); + LambdaQueryWrapper query1 = new LambdaQueryWrapper(); + String[] strArray = new String[2]; + // 创建一个List集合,存储查询返回的所有SysDepart对象 + List departList = new ArrayList<>(); + // 定义新编码字符串 + String newOrgCode = ""; + // 定义旧编码字符串 + String oldOrgCode = ""; + // 定义部门类型 + String orgType = ""; + // 如果是最高级,则查询出同级的org_code, 调用工具类生成编码并返回 + if (StringUtil.isNullOrEmpty(parentId)) { + // 线判断数据库中的表是否为空,空则直接返回初始编码 + query1.eq(SysDepart::getParentId, "").or().isNull(SysDepart::getParentId); + query1.orderByDesc(SysDepart::getOrgCode); + departList = this.list(query1); + if(departList == null || departList.size() == 0) { + strArray[0] = YouBianCodeUtil.getNextYouBianCode(null); + strArray[1] = "1"; + return strArray; + }else { + SysDepart depart = departList.get(0); + oldOrgCode = depart.getOrgCode(); + orgType = depart.getOrgType(); + newOrgCode = YouBianCodeUtil.getNextYouBianCode(oldOrgCode); + } + } else { // 反之则查询出所有同级的部门,获取结果后有两种情况,有同级和没有同级 + // 封装查询同级的条件 + query.eq(SysDepart::getParentId, parentId); + // 降序排序 + query.orderByDesc(SysDepart::getOrgCode); + // 查询出同级部门的集合 + List parentList = this.list(query); + // 查询出父级部门 + SysDepart depart = this.getById(parentId); + // 获取父级部门的Code + String parentCode = depart.getOrgCode(); + // 根据父级部门类型算出当前部门的类型 + orgType = String.valueOf(Integer.valueOf(depart.getOrgType()) + 1); + // 处理同级部门为null的情况 + if (parentList == null || parentList.size() == 0) { + // 直接生成当前的部门编码并返回 + newOrgCode = YouBianCodeUtil.getSubYouBianCode(parentCode, null); + } else { //处理有同级部门的情况 + // 获取同级部门的编码,利用工具类 + String subCode = parentList.get(0).getOrgCode(); + // 返回生成的当前部门编码 + newOrgCode = YouBianCodeUtil.getSubYouBianCode(parentCode, subCode); + } + } + // 返回最终封装了部门编码和部门类型的数组 + strArray[0] = newOrgCode; + strArray[1] = orgType; + return strArray; + //update-end--Author:Steve Date:20190201 for:组织机构添加数据代码调整 + } + + + /** + * removeDepartDataById 对应 delete方法 根据ID删除相关部门数据 + * + */ + /* + * @Override + * + * @Transactional public boolean removeDepartDataById(String id) { + * System.out.println("要删除的ID 为=============================>>>>>"+id); boolean + * flag = this.removeById(id); return flag; } + */ + + /** + * updateDepartDataById 对应 edit 根据部门主键来更新对应的部门数据 + */ + @Override + @Transactional + public Boolean updateDepartDataById(SysDepart sysDepart, String username) { + if (sysDepart != null && username != null) { + sysDepart.setUpdateTime(new Date()); + sysDepart.setUpdateBy(username); + this.updateById(sysDepart); + return true; + } else { + return false; + } + + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteBatchWithChildren(List ids) { + List idList = new ArrayList(); + for(String id: ids) { + idList.add(id); + this.checkChildrenExists(id, idList); + } + this.removeByIds(idList); + //根据部门id获取部门角色id + List roleIdList = new ArrayList<>(); + LambdaQueryWrapper query = new LambdaQueryWrapper<>(); + query.select(SysDepartRole::getId).in(SysDepartRole::getDepartId, idList); + List depRoleList = sysDepartRoleMapper.selectList(query); + for(SysDepartRole deptRole : depRoleList){ + roleIdList.add(deptRole.getId()); + } + //根据部门id删除用户与部门关系 + userDepartMapper.delete(new LambdaQueryWrapper().in(SysUserDepart::getDepId,idList)); + //根据部门id删除部门授权 + departPermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartPermission::getDepartId,idList)); + //根据部门id删除部门角色 + sysDepartRoleMapper.delete(new LambdaQueryWrapper().in(SysDepartRole::getDepartId,idList)); + if(roleIdList != null && roleIdList.size()>0){ + //根据角色id删除部门角色授权 + departRolePermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartRolePermission::getRoleId,roleIdList)); + //根据角色id删除部门角色用户信息 + departRoleUserMapper.delete(new LambdaQueryWrapper().in(SysDepartRoleUser::getDroleId,roleIdList)); + } + } + + @Override + public List getSubDepIdsByDepId(String departId) { + return this.baseMapper.getSubDepIdsByDepId(departId); + } + + @Override + public List getMySubDepIdsByDepId(String departIds) { + //根据部门id获取所负责部门 + String[] codeArr = this.getMyDeptParentOrgCode(departIds); + return this.baseMapper.getSubDepIdsByOrgCodes(codeArr); + } + + /** + *

+ * 根据关键字搜索相关的部门数据 + *

+ */ + @Override + public List searhBy(String keyWord,String myDeptSearch,String departIds) { + LambdaQueryWrapper query = new LambdaQueryWrapper(); + List newList = new ArrayList<>(); + //myDeptSearch不为空时为我的部门搜索,只搜索所负责部门 + if(!StringUtil.isNullOrEmpty(myDeptSearch)){ + //departIds 为空普通用户或没有管理部门 + if(StringUtil.isNullOrEmpty(departIds)){ + return newList; + } + //根据部门id获取所负责部门 + String[] codeArr = this.getMyDeptParentOrgCode(departIds); + for(int i=0;i departList = this.list(query); + if(departList.size() > 0) { + for(SysDepart depart : departList) { + model = new SysDepartTreeModel(depart); + model.setChildren(null); + //update-end--Author:huangzhilin Date:20140417 for:[bugfree号]组织机构搜索功回显优化---------------------- + newList.add(model); + } + return newList; + } + return null; + } + + /** + * 根据部门id删除并且删除其可能存在的子级任何部门 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean delete(String id) { + List idList = new ArrayList<>(); + idList.add(id); + this.checkChildrenExists(id, idList); + //清空部门树内存 + //FindsDepartsChildrenUtil.clearDepartIdModel(); + boolean ok = this.removeByIds(idList); + //根据部门id获取部门角色id + List roleIdList = new ArrayList<>(); + LambdaQueryWrapper query = new LambdaQueryWrapper<>(); + query.select(SysDepartRole::getId).in(SysDepartRole::getDepartId, idList); + List depRoleList = sysDepartRoleMapper.selectList(query); + for(SysDepartRole deptRole : depRoleList){ + roleIdList.add(deptRole.getId()); + } + //根据部门id删除用户与部门关系 + userDepartMapper.delete(new LambdaQueryWrapper().in(SysUserDepart::getDepId,idList)); + //根据部门id删除部门授权 + departPermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartPermission::getDepartId,idList)); + //根据部门id删除部门角色 + sysDepartRoleMapper.delete(new LambdaQueryWrapper().in(SysDepartRole::getDepartId,idList)); + if(roleIdList != null && roleIdList.size()>0){ + //根据角色id删除部门角色授权 + departRolePermissionMapper.delete(new LambdaQueryWrapper().in(SysDepartRolePermission::getRoleId,roleIdList)); + //根据角色id删除部门角色用户信息 + departRoleUserMapper.delete(new LambdaQueryWrapper().in(SysDepartRoleUser::getDroleId,roleIdList)); + } + return ok; + } + + /** + * delete 方法调用 + * @param id + * @param idList + */ + private void checkChildrenExists(String id, List idList) { + LambdaQueryWrapper query = new LambdaQueryWrapper(); + query.eq(SysDepart::getParentId,id); + List departList = this.list(query); + if(departList != null && departList.size() > 0) { + for(SysDepart depart : departList) { + idList.add(depart.getId()); + this.checkChildrenExists(depart.getId(), idList); + } + } + } + + @Override + public List queryUserDeparts(String userId) { + return baseMapper.queryUserDeparts(userId); + } + + @Override + public List queryDepartsByUsername(String username) { + return baseMapper.queryDepartsByUsername(username); + } + + /** + * 根据用户所负责部门ids获取父级部门编码 + * @param departIds + * @return + */ + private String[] getMyDeptParentOrgCode(String departIds){ + //根据部门id查询所负责部门 + LambdaQueryWrapper query = new LambdaQueryWrapper(); + query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); + query.in(SysDepart::getId, Arrays.asList(departIds.split(","))); + query.orderByAsc(SysDepart::getOrgCode); + List list = this.list(query); + //查找根部门 + if(list == null || list.size()==0){ + return null; + } + String orgCode = this.getMyDeptParentNode(list); + String[] codeArr = orgCode.split(","); + return codeArr; + } + + /** + * 获取负责部门父节点 + * @param list + * @return + */ + private String getMyDeptParentNode(List list){ + Map map = new HashMap<>(); + //1.先将同一公司归类 + for(SysDepart dept : list){ + String code = dept.getOrgCode().substring(0,3); + if(map.containsKey(code)){ + String mapCode = map.get(code)+","+dept.getOrgCode(); + map.put(code,mapCode); + }else{ + map.put(code,dept.getOrgCode()); + } + } + StringBuffer parentOrgCode = new StringBuffer(); + //2.获取同一公司的根节点 + for(String str : map.values()){ + String[] arrStr = str.split(","); + parentOrgCode.append(",").append(this.getMinLengthNode(arrStr)); + } + return parentOrgCode.substring(1); + } + + /** + * 获取同一公司中部门编码长度最小的部门 + * @param str + * @return + */ + private String getMinLengthNode(String[] str){ + int min =str[0].length(); + String orgCode = str[0]; + for(int i =1;i queryTreeByKeyWord(String keyWord) { + LambdaQueryWrapper query = new LambdaQueryWrapper(); + query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString()); + query.orderByAsc(SysDepart::getDepartOrder); + List list = this.list(query); + // 调用wrapTreeDataToTreeList方法生成树状数据 + List listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list); + List treelist =new ArrayList<>(); + if(StringUtils.isNotBlank(keyWord)){ + this.getTreeByKeyWord(keyWord,listResult,treelist); + }else{ + return listResult; + } + return treelist; + } + + /** + * 根据parentId查询部门树 + * @param parentId + * @return + */ + @Override + public List queryTreeListByPid(String parentId) { + List list = this.baseMapper.queryTreeListByPid(parentId); + List records = new ArrayList<>(); + for (int i = 0; i < list.size(); i++) { + SysDepart depart = list.get(i); + SysDepartTreeModel treeModel = new SysDepartTreeModel(depart); + //TODO 异步树加载key拼接__+时间戳,以便于每次展开节点会刷新数据 + //treeModel.setKey(treeModel.getKey()+"__"+System.currentTimeMillis()); + treeModel.setKey(treeModel.getKey()); + Integer count=this.baseMapper.queryCountByPid(depart.getId()); + if(count>0){ + treeModel.setIsLeaf(false); + }else{ + treeModel.setIsLeaf(true); + } + records.add(treeModel); + } + return records; + } + + @Override + public JSONObject queryAllParentIdByDepartId(String departId) { + JSONObject result = new JSONObject(); + for (String id : departId.split(",")) { + JSONObject all = this.queryAllParentId("id", id); + result.put(id, all); + } + return result; + } + + @Override + public JSONObject queryAllParentIdByOrgCode(String orgCode) { + JSONObject result = new JSONObject(); + for (String code : orgCode.split(",")) { + JSONObject all = this.queryAllParentId("org_code", code); + result.put(code, all); + } + return result; + } + + /** + * 查询某个部门的所有父ID信息 + * + * @param fieldName 字段名 + * @param value 值 + */ + private JSONObject queryAllParentId(String fieldName, String value) { + JSONObject data = new JSONObject(); + // 父ID集合,有序 + data.put("parentIds", new JSONArray()); + // 父ID的部门数据,key是id,value是数据 + data.put("parentMap", new JSONObject()); + this.queryAllParentIdRecursion(fieldName, value, data); + return data; + } + + /** + * 递归调用查询父部门接口 + */ + private void queryAllParentIdRecursion(String fieldName, String value, JSONObject data) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq(fieldName, value); + SysDepart depart = super.getOne(queryWrapper); + if (depart != null) { + data.getJSONArray("parentIds").add(0, depart.getId()); + data.getJSONObject("parentMap").put(depart.getId(), depart); + if (oConvertUtils.isNotEmpty(depart.getParentId())) { + this.queryAllParentIdRecursion("id", depart.getParentId(), data); + } + } + } + + @Override + public SysDepart queryCompByOrgCode(String orgCode) { + int length = YouBianCodeUtil.zhanweiLength; + String compyOrgCode = orgCode.substring(0,length); + return this.baseMapper.queryCompByOrgCode(compyOrgCode); + } + /** + * 根据id查询下级部门 + * @param pid + * @return + */ + @Override + public List queryDeptByPid(String pid) { + return this.baseMapper.queryDeptByPid(pid); + } + /** + * 根据关键字筛选部门信息 + * @param keyWord + * @return + */ + public void getTreeByKeyWord(String keyWord,List allResult,List newResult){ + for (SysDepartTreeModel model:allResult) { + if (model.getDepartName().contains(keyWord)){ + newResult.add(model); + continue; + }else if(model.getChildren()!=null){ + getTreeByKeyWord(keyWord,model.getChildren(),newResult); + } + } + } +}