king
2020-04-17 bf772e586c29b4858366dbad143b1eaeca3c46ed
src/utils/utils.js
@@ -54,7 +54,7 @@
   * @description sql加密
   * @return {String}  value
   */
  static formatOptions (value) {
  static formatOptions (value, isUnFormat = false) {
    if (!value) return ''
    let salt = 'minKe' // 盐值
@@ -157,25 +157,43 @@
      value: ' mrlbkk '
    }]
    // 替换关键字
    format.forEach(item => {
      let reg  =  new RegExp('(^|\\s)' + item.key + '(\\s|$)', 'ig')
      value = value.replace(reg, item.value)
    })
    if (!isUnFormat) { // 加密
      // 替换关键字
      format.forEach(item => {
        let reg = new RegExp('(^|\\s)' + item.key + '(\\s|$)', 'ig')
        value = value.replace(reg, item.value)
      })
      // 1、替换%符(数据库中解析后sql报错)
      value = value.replace(/%/ig, ' mpercent ')
      // 1、encode编码(中文字符超出base64加密范围),2、base64加密
      value = window.btoa(window.encodeURIComponent(value))
      // 插入字符
      let index = Math.floor(value.length / 2)
      value = value.slice(0, index) + salt + value.slice(index)
      // base64加密
      value = window.btoa(value)
    } else { // 解密
      try {
        value = window.atob(value)
        value = value.replace(salt, '')
        value = window.decodeURIComponent(window.atob(value))
        value = value.replace(/\smpercent\s/g, '%')
    // 1、替换%符(数据库中解析后sql报错),2、去除收尾多余空格
    value = value.replace(/%/ig, 'mpercent')
    value = value.replace(/(^\s|\s$)/ig, '')
    // 1、encode编码(中文字符超出base64加密范围),2、base64加密
    value = window.btoa(window.encodeURIComponent(value))
    // 插入字符
    let index = Math.floor(value.length / 2)
    value = value.slice(0, index) + salt + value.slice(index)
    // base64加密
    value = window.btoa(value)
        format.forEach(item => {
          let reg = new RegExp(item.value, 'g')
          value = value.replace(reg, ' ' + item.key + ' ')
        })
        value = value.replace(/(^\s+|\s+$)/ig, '')
      } catch {
        console.warn('UnFormat Failure')
        value = ''
      }
    }
    return value
  }
@@ -194,7 +212,9 @@
        key: search.field,
        match: search.match,
        type: search.type,
        value: search.initval
        label: search.label,
        value: search.initval,
        required: search.required === 'true'
      }
      if (item.type === 'date') {
        item.value = item.value ? moment().subtract(item.value, 'days').format('YYYY-MM-DD') : ''
@@ -289,6 +309,12 @@
        newsearches[item.key] = item.value
      }
    })
    Object.keys(newsearches).forEach(key => {
      if (!newsearches[key]) {
        delete newsearches[key]
      }
    })
    
    return newsearches
  }
@@ -318,12 +344,8 @@
        searchText += item.key + ' ' + item.match + ' \'' + str + item.value + str + '\''
      } else if (item.type === 'multiselect') {
        let str = item.match === '=' ? '' : '%'
        let options = item.value.map(val => {
          return item.key + ' ' + item.match + ' \'' + str + val + str + '\''
        })
        searchText += '(' + options.join(' OR ') + ')'
        searchText += `'${item.value}' ` + item.match + ' \'%\'+' + item.key + '+\'%\''
      } else if (item.type === 'date') {
        let _val = item.value
        let timetail = ' 00:00:00.000'
@@ -356,6 +378,7 @@
        searchText += '(' + item.key + ' ' + item.match + ' \'' + item.value + '\')'
      }
    })
    return searchText
  }
@@ -472,6 +495,11 @@
    let errors = []
    let _topline = btn.range || 0
    let upId = this.getuuid()
    if (btn.scripts && btn.scripts.length > 0) {
      btn.scripts = btn.scripts.filter(item => item.status !== 'false')
    }
    let _Ltext = data.map((item, lindex) => {
      let vals = btn.columns.map((col, cindex) => {
        let val = item[col.Column] !== undefined ? item[col.Column] : ''
@@ -500,7 +528,7 @@
            })
          }
        } else if (/^int/ig.test(col.type)) {
          if (!val) {
          if (!val && val !== 0) {
            let _error =  _position + dict['main.excel.content.emptyerror']
            errors.push(_error)
          } else {
@@ -518,7 +546,7 @@
            }
          }
        } else if (/^Decimal/ig.test(col.type)) {
          if (!val) {
          if (!val && val !== 0) {
            let _error =  _position + dict['main.excel.content.emptyerror']
            errors.push(_error)
          } else {
@@ -560,6 +588,48 @@
    let _sql = ''
    if (item.intertype === 'inner' && !item.innerFunc) {
      let _uniquesql = ''
      if (btn.uniques && btn.uniques.length > 0) {
        btn.uniques.forEach(unique => {
          if (unique.status === 'false') return
          let _fields = unique.field.split(',')
          let _fields_ = _fields.map(_field => {
            return `a.${_field}=b.${_field}`
          })
          _fields_ = _fields_.join(' and ')
          if (unique.verifyType !== 'physical') {
            _fields_ += ' and b.deleted=0'
          }
          _uniquesql += `
          Set @tbid=''
          Select top 1 @tbid=${_fields.join('+\' \'+')} from (select 1 as n,${unique.field} from @${item.sheet} ) a group by ${unique.field} having sum(n)>1
          If @tbid!=''
          Begin
            select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 重复'
            goto aaa
          end
          Set @tbid=''
          Select top 1 @tbid=${_fields.join('+\' \'+')} from  @${item.sheet} a
          Inner join ${item.sheet} b on ${_fields_}
          If @tbid!=''
          Begin
            select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 与已有数据重复'
            goto aaa
          end
          `
        })
        if (_uniquesql) {
          _uniquesql = 'Declare @tbid Nvarchar(512)' + _uniquesql
        }
      }
      let declarefields = []
      let fields = []
@@ -572,6 +642,16 @@
      let _insert = ''
      if (btn.scripts && btn.scripts.length > 0) {
        btn.scripts.forEach(script => {
          if (script.position !== 'front') return
          _insert += `
          ${script.sql}
          `
        })
      }
      if (btn.default !== 'false') {
        _insert = `
        Insert into ${item.sheet} (${fields},createuserid,createuser,createstaff,bid) 
@@ -581,7 +661,7 @@
      if (btn.scripts && btn.scripts.length > 0) {
        btn.scripts.forEach(script => {
          if (script.status === 'false') return
          if (script.position === 'front') return
          _insert += `
          ${script.sql}
@@ -598,6 +678,7 @@
      
      Insert into  @${item.sheet} (${fields},jskey)
      ${_Ltext}
      ${_uniquesql}
      ${_insert}
      Delete @${item.sheet}
@@ -619,14 +700,19 @@
   * @return {String} type   执行类型
   * @return {String} table  表名
   */
  static getSysDefaultSql (btn, setting, formdata, param, data, logcolumns) {
  static getSysDefaultSql (btn, setting, formdata, param, data, logcolumns, tab) {
    let primaryId = param.ID
    let BID = param.BID
    let verify = btn.verify || {}
    let _formFieldValue = {}
    let _actionType = null
    if (verify.default !== 'false') { // 判断是否使用默认sql
      _actionType = btn.sqlType
    }
    // 需要声明的变量集
    // let _vars = ['tbid', 'ErrorCode', 'retmsg', 'BillCode', 'BVoucher', 'FIBVoucherDate', 'FiYear', 'UserName', 'FullName', 'ID', 'BID', 'LoginUID', 'SessionUid', 'UserID', 'Appkey']
    // let _vars = ['tbid', 'errorcode', 'retmsg', 'billcode', 'bvoucher', 'fibvoucherdate', 'fiyear', 'username', 'fullname', 'id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey']
    let _vars = ['tbid', 'errorcode', 'retmsg', 'billcode', 'bvoucher', 'fibvoucherdate', 'fiyear', 'username', 'fullname', 'modulardetailcode']
    // 主键字段
@@ -637,7 +723,6 @@
      `
    // let _initvars = ['ID', 'BID', 'LoginUID', 'SessionUid', 'UserID', 'Appkey'] // 已赋值字段集
    // let _initvars = ['id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey'] // 已赋值字段集
    let _initvars = [] // 已赋值字段集
    let _initfields = []
    let _declarefields = []
@@ -660,6 +745,10 @@
        
        if (!_vars.includes(_key)) {
          _vars.push(_key)
          if (form.fieldlen && form.fieldlen > 2048) {
            form.fieldlen = 'max'
          }
          let _type = `nvarchar(${form.fieldlen})`
@@ -696,6 +785,10 @@
          
          if (!_vars.includes(_key)) {
            _vars.push(_key)
            if (col.fieldlength && col.fieldlength > 2048) {
              col.fieldlength = 'max'
            }
  
            let _type = `nvarchar(${col.fieldlength || 50})`
@@ -726,11 +819,6 @@
        `
    }
    // 添加时主键为空 改为前台生成
    // if (btn.sqlType === 'insert') {
    //   primaryId = ''
    // }
    // 去除禁用的验证
    if (verify.contrasts) {
      verify.contrasts = verify.contrasts.filter(item => item.status !== 'false')
@@ -748,8 +836,16 @@
      verify.scripts = verify.scripts.filter(item => item.status !== 'false')
    }
    // 初始化凭证字段
    _sql += `select @BVoucher='',@FIBVoucherDate='',@FiYear='',@ErrorCode='',@retmsg=''
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
    // 初始化凭证及用户信息字段
    _sql += `select @BVoucher='',@FIBVoucherDate='',@FiYear='',@ErrorCode='',@retmsg='',@UserName='${userName}', @FullName='${fullName}'
      `
    // 启用账期验证
@@ -801,6 +897,7 @@
        let _fieldValue = []                     // 表单键值对field=value
        let _value = []                          // 表单值,用于错误提示
        let _labels = item.fieldlabel.split(',') // 表单提示文字
        let arr = [] // 验证主键
        item.field.split(',').forEach((_field, index) => {
          let _fval = `'${_formFieldValue[_field]}'`
@@ -810,6 +907,8 @@
          if (_field.toLowerCase() === 'bid' && !hasBid) { // 表单中没有bid则使用系统bid变量
            _fval = '@BID@'
          }
          arr.push(_field.toLowerCase())
          _fieldValue.push(`${_field}=${_fval}`)
          _value.push(`${_labels[index] || ''}:${_formFieldValue[_field] || ''}`)
        })
@@ -819,8 +918,12 @@
          _verifyType = ' and deleted=0'
        }
        if (!arr.includes(primaryKey.toLowerCase())) {
          _fieldValue.push(`${primaryKey} !='${primaryId}'`)
        }
        _sql += `select @tbid='', @ErrorCode='',@retmsg=''
          select @tbid='X' from ${btn.sql} where ${_fieldValue.join(' and ')} and ${primaryKey} !='${primaryId}'${_verifyType}
          select @tbid='X' from ${btn.sql} where ${_fieldValue.join(' and ')}${_verifyType}
          If @tbid!=''
          Begin
            select @ErrorCode='${item.errorCode}',@retmsg='${_value.join(', ')} 已存在'
@@ -832,7 +935,7 @@
    
    // 自定义验证
    if (verify.customverifys && verify.customverifys.length > 0) {
      verify.customverifys.forEach(item => {
      verify.customverifys.forEach(item => {
        _sql += `select @tbid='', @ErrorCode='',@retmsg=''
          select top 1 @tbid='X' from (${item.sql}) a
          If @tbid ${item.result === 'true' ? '!=' : '='}''
@@ -845,15 +948,16 @@
    }
    // 单号生成,使用上级id(BID)或列表数据,声明变量(检验)
    let _billcodesSql  = ''
    if (verify.billcodes && verify.billcodes.length > 0) {
      verify.billcodes.forEach(item => {
        let _ModularDetailCode = ''
        let _lpline = ''
        if (item.TypeCharOne === 'Lp') {
          if (item.linkField === 'BID' && BID) { // 替换bid
            _lpline = `set @ModularDetailCode= 'Lp'+ right('${btn.uuid}'+@BID@,48)`
            _lpline = `set @ModularDetailCode= 'Lp'+ right('${item.mark || btn.uuid}'+@BID@,48)`
          } else {
            _lpline = `set @ModularDetailCode= 'Lp'+ right('${btn.uuid}'+@${item.linkField},48)`
            _lpline = `set @ModularDetailCode= 'Lp'+ right('${item.mark || btn.uuid}'+@${item.linkField},48)`
          }
          _ModularDetailCode = '@ModularDetailCode'
        } else if (item.TypeCharOne === 'BN') {
@@ -876,7 +980,7 @@
          _vars.push(_key)
        }
        _sql += `${_declare}
        _billcodesSql += `${_declare}
          select @BillCode='', @${_key}='', @ModularDetailCode=''
          ${_lpline}
          exec s_get_BillCode
@@ -892,6 +996,10 @@
          set @${_key}=@BillCode
          `
      })
      if (_actionType !== 'insertOrUpdate') {
        _sql += _billcodesSql
      }
    }
    let hasvoucher = false
@@ -908,6 +1016,9 @@
          @VoucherTypeOne ='${_voucher.VoucherTypeOne}',
          @VoucherTypeTwo ='${_voucher.VoucherTypeTwo}',
          @Type =${_voucher.Type},
          @UserID=@UserID@,
          @Username=@Username,
          @FullName=@FullName,
          @BVoucher =@BVoucher OUTPUT ,
          @FIBVoucherDate =@FIBVoucherDate OUTPUT ,
          @FiYear =@FiYear OUTPUT ,
@@ -918,20 +1029,10 @@
        `
    }
    // 用于取用户信息
    let _user = `select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID@
      `
    let primaryKeyName = ['id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey'].includes(primaryKey.toLowerCase()) ? primaryKey + '@' : primaryKey
    let _actionType = null
    if (verify.default !== 'false') { // 判断是否使用默认sql
      _actionType = btn.sqlType
    }
    // 添加、修改、逻辑删除、物理删除
    if (_actionType === 'insert') {
    let _insertsql = ''
    if (_actionType === 'insert' || _actionType === 'insertOrUpdate') { // 添加语句
      let keys = []
      let values = []
@@ -948,8 +1049,8 @@
        }
      })
      if (!keys.includes(primaryKey)) {
        keys.push(primaryKey)
      if (!keys.includes(primaryKey.toLowerCase())) {
        keys.push(primaryKey.toLowerCase())
        values.push('\'' + primaryId + '\'')
      }
      if (!keys.includes('createuserid')) {
@@ -965,15 +1066,24 @@
        values.push('@fullname')
      }
      if (!keys.includes('bid')) {
        keys.push('bid')
        if (tab && tab.foreignKey && !keys.includes(tab.foreignKey.toLowerCase())) {
          keys.push(tab.foreignKey)
        } else {
          keys.push('bid')
        }
        values.push('@BID@')
      } else if (tab && tab.foreignKey && !keys.includes(tab.foreignKey.toLowerCase())) {
        keys.push(tab.foreignKey)
        values.push('@BID@')
      }
      keys = keys.join(',')
      values = values.join(',')
      _sql += _user
      _sql += `insert into ${btn.sql} (${keys}) select ${values};`
    } else if (_actionType === 'update') {
      _insertsql = `insert into ${btn.sql} (${keys}) select ${values};`
    }
    let _updatesql = ''
    if (_actionType === 'update' || _actionType === 'insertOrUpdate') { // 修改语句
      let _form = []
      let _arr = []
@@ -981,7 +1091,11 @@
        _arr.push(item.key.toLowerCase())
        if (item.type === 'funcvar') {
          _form.push(item.key + '=@' + item.key)
          if (_actionType === 'update') {
            _form.push(item.key + '=@' + item.key)
          } else if (_actionType === 'insertOrUpdate') { // 添加或修改时,函数变量添加表单数值
            _form.push(item.key + '=\'' + item.value + '\'')
          }
        } else if (item.type === 'number') {
          _form.push(item.key + '=' + item.value)
        } else {
@@ -1006,9 +1120,27 @@
          _form.push('FiYear=@FiYear')
        }
      }
      _form = _form.join(',')
      _sql += `update ${btn.sql} set ${_form} where ${primaryKey}=@${primaryKeyName};`
      _updatesql = `update ${btn.sql} set ${_form} where ${primaryKey}=@${primaryKeyName};`
    }
    // 拼接自定义脚本
    if (verify.scripts && verify.scripts.length > 0) {
      let _scripts = ''
      verify.scripts.forEach(item => {
        if (item.position !== 'front') return
        _scripts += `
        ${item.sql}`
      })
      _sql += `${_scripts}`
    }
    // 添加、修改、逻辑删除、物理删除
    if (_actionType === 'insert') {
      _sql += _insertsql
    } else if (_actionType === 'update') {
      _sql += _updatesql
    } else if (_actionType === 'LogicDelete') { // 逻辑删除
      _sql += `update ${btn.sql} set deleted=1,modifydate=getdate(),modifyuserid=@userid@ where ${primaryKey}=@${primaryKeyName};`
    
@@ -1023,14 +1155,28 @@
          }
        })
      }
      _sql += _user
      _sql += `insert into snote (remark,createuserid,CreateUser,CreateStaff) select '删除表:${btn.sql} 数据: ${_msg}${primaryKey}='+@${primaryKeyName},@userid@,@username,@fullname delete ${btn.sql} where ${primaryKey}=@${primaryKeyName};`
      _sql += `insert into snote (remark,createuserid,CreateUser,CreateStaff) select left('删除表:${btn.sql} 数据: ${_msg}${primaryKey}='+@${primaryKeyName},200),@userid@,@username,@fullname delete ${btn.sql} where ${primaryKey}=@${primaryKeyName};`
    } else if (_actionType === 'insertOrUpdate') {
      _sql += `select @tbid=''
        select @tbid='X' from ${btn.sql} where ${primaryKey}=@ID@
        if @tbid=''
          begin
          ${_billcodesSql}
          ${_insertsql}
          end
        else
          begin
          ${_updatesql}
          end
      `
    }
    // 拼接自定义脚本
    if (verify.scripts && verify.scripts.length > 0) {
      let _scripts = ''
      verify.scripts.forEach(item => {
        if (item.position === 'front') return
        _scripts += `
        ${item.sql}`
      })
@@ -1112,6 +1258,7 @@
    let Ltext = `create proc ${param.innerFunc}
    ( /*${menu.MenuName}*/
    @appkey nvarchar(50)='',
    @BID nvarchar(50)='',${formParam}
    @PageIndex nvarchar(50)='',
    @PageSize nvarchar(50)='',
@@ -1242,6 +1389,10 @@
        
        update ${param.name} set ${field3},modifydate=getdate(),modifyuserid=@UserID
      `
    } else if (btn.OpenType === 'prompt' || btn.OpenType === 'exec') {
      form = `
        update ${param.name} set ModifyDate=getdate(),ModifyUserID=@UserID where ${primaryKey}=@${primaryKey}
      `
    }
    if (columns) {
@@ -1277,6 +1428,7 @@
    let Ltext = `create proc ${param.funcName}
    ( /*${menu.MenuName}  ${btn.label}*/
    @appkey nvarchar(50)='',
    @BID nvarchar(50)='',${formParam}
    @sEPTMenuNo nvarchar(50)='${param.menuNo}',
    @lang nvarchar(50)='',
@@ -1357,6 +1509,50 @@
  static getexcelInfunc (param, btn, menu) {
    let _verify = btn.verify
    let _uniquesql = ''
    if (_verify.uniques && _verify.uniques.length > 0) {
      _verify.uniques.forEach(unique => {
        if (unique.status === 'false') return
        let _fields = unique.field.split(',')
        let _fields_ = _fields.map(_field => {
          return `a.${_field}=b.${_field}`
        })
        _fields_ = _fields_.join(' and ')
        if (unique.verifyType !== 'physical') {
          _fields_ += ' and b.deleted=0'
        }
        _uniquesql += `
        Set @tbid=''
        Select top 1 @tbid=${_fields.join('+\' \'+')} from (select 1 as n,${unique.field} from @${btn.sheet} ) a group by ${unique.field} having sum(n)>1
        If @tbid!=''
        Begin
          select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 重复'
          goto aaa
        end
        Set @tbid=''
        Select top 1 @tbid=${_fields.join('+\' \'+')} from  @${btn.sheet} a
        Inner join ${btn.sheet} b on ${_fields_}
        If @tbid!=''
        Begin
          select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 与已有数据重复'
          goto aaa
        end
        `
      })
      if (_uniquesql) {
        _uniquesql = `
        Declare @tbid Nvarchar(512)
        ${_uniquesql}`
      }
    }
    let declarefields = []
    let fields = []
@@ -1376,7 +1572,7 @@
      exec s_KeyWords_Replace
      @LText=@LText, @BID=@BID,@LoginUID=@LoginUID,@SessionUid=@SessionUid,@UserID=@UserID,@ID=@ID
      ${_uniquesql}
      Insert into ${btn.sheet} (${fields},createuserid,createuser,createstaff,bid) 
      Select ${fields},@userid,@username,@fullname,@BID From @${btn.sheet}
@@ -1384,10 +1580,13 @@
    let Ltext = `create proc ${param.funcName}
    ( /*${menu.MenuName}  ${btn.label}*/
      @appkey nvarchar(50)='',
      @ID nvarchar(50)='',
      @BID nvarchar(50)='',
      @Ltext nvarchar(max)='',
      @sEPTMenuNo nvarchar(50)='${param.menuNo}', 
      @secretkey nvarchar(50)='',
      @timestamp nvarchar(50)='',
      @lang nvarchar(50)='',
      @LoginUID nvarchar(50)='',
      @SessionUid nvarchar(50)='',