From aaaf56d7ca060f7c681d6b8a67aac46aa89a4dbc Mon Sep 17 00:00:00 2001
From: king <18310653075@163.com>
Date: 星期六, 09 五月 2020 14:50:39 +0800
Subject: [PATCH] 2020-05-09

---
 src/utils/utils.js |  870 +++++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 615 insertions(+), 255 deletions(-)

diff --git a/src/utils/utils.js b/src/utils/utils.js
index a3abb26..0e1c3a1 100644
--- a/src/utils/utils.js
+++ b/src/utils/utils.js
@@ -51,131 +51,126 @@
   }
 
   /**
+   * @description sql璇硶楠岃瘉
+   * @return {String}  sql    sql璇彞
+   * @return {String}  type   楠岃瘉绫诲瀷
+   */
+  static verifySql (sql, type) {
+    if (!sql) return ''
+    let chars = [
+      {key: 'create', reg: /(^|\s)create\s/ig},
+      {key: 'insert', reg: /(^|\s)insert\s/ig},
+      {key: 'delete', reg: /(^|\s)delete\s/ig},
+      {key: 'update', reg: /(^|\s)update\s/ig},
+      {key: 'set', reg: /(^|\s)set\s/ig},
+      {key: 'drop', reg: /(^|\s)drop\s/ig},
+      {key: 'alter', reg: /(^|\s)alter\s/ig},
+      {key: 'truncate', reg: /(^|\s)truncate\s/ig},
+      {key: 'if', reg: /(^|\s)if\s/ig},
+      {key: 'exec', reg: /exec/ig},
+      {key: 'OBJECT', reg: /object/ig},
+      {key: 'sys.', reg: /sys\./ig},
+      {key: 'kill', reg: /kill/ig}
+    ]
+
+    if (type === 'customscript') {
+      chars = chars.filter(char => !['insert', 'delete', 'update', 'set', 'if', 'exec'].includes(char.key))
+    }
+
+    let error = ''
+    chars.forEach(char => {
+      if (!error && char.reg.test(sql)) {
+        error = char.key
+      }
+    })
+
+    return error
+  }
+
+  /**
    * @description sql鍔犲瘑
    * @return {String}  value
    */
-  static formatOptions (value) {
+  static formatOptions (value, isUnFormat = false) {
     if (!value) return ''
 
     let salt = 'minKe' // 鐩愬��
     // 鍏抽敭瀛楄浆鎹㈣鍒�
-    let format = [{
-      key: 'select',
-      value: ' msltk '
-    }, {
-      key: 'from',
-      value: ' mfrmk '
-    }, {
-      key: 'where',
-      value: ' mwhrk '
-    }, {
-      key: 'order by',
-      value: ' modbk '
-    }, {
-      key: 'asc',
-      value: ' modack '
-    }, {
-      key: 'desc',
-      value: ' moddesk '
-    }, {
-      key: 'top',
-      value: ' mtpk '
-    }, {
-      key: 'like',
-      value: ' mlkk '
-    }, {
-      key: 'not like',
-      value: ' mnlkk '
-    }, {
-      key: 'between',
-      value: ' mbtnk '
-    }, {
-      key: 'and',
-      value: ' madk '
-    }, {
-      key: 'insert',
-      value: ' mistk '
-    }, {
-      key: 'into',
-      value: ' mitk '
-    }, {
-      key: 'update',
-      value: ' muptk '
-    }, {
-      key: 'delete',
-      value: ' mdelk '
-    }, {
-      key: 'begin',
-      value: ' mbgink '
-    }, {
-      key: 'end',
-      value: ' medk '
-    }, {
-      key: 'if',
-      value: ' mefk '
-    }, {
-      key: 'while',
-      value: ' mwilk '
-    }, {
-      key: 'create',
-      value: ' mcrtk '
-    }, {
-      key: 'alter',
-      value: ' matek '
-    }, {
-      key: 'len',
-      value: ' mlnk '
-    }, {
-      key: 'left',
-      value: ' mlftk '
-    }, {
-      key: 'right',
-      value: ' mritk '
-    }, {
-      key: 'union',
-      value: ' munok '
-    }, {
-      key: 'varchar',
-      value: ' mvcrk '
-    }, {
-      key: 'getdate',
-      value: ' mgtdtk '
-    }, {
-      key: 'TRY',
-      value: ' mtryonek '
-    }, {
-      key: 'TRAN',
-      value: ' mtrnk '
-    }, {
-      key: 'goto',
-      value: ' mgtk '
-    }, {
-      key: 'set',
-      value: ' mstk '
-    }, {
-      key: 'ROLLBACK',
-      value: ' mrlbkk '
-    }]
+    let format = [
+      { key: 'select', value: ' msltk ' },
+      { key: 'from', value: ' mfrmk ' },
+      { key: 'where', value: ' mwhrk ' },
+      { key: 'order by', value: ' modbk ' },
+      { key: 'asc', value: ' modack ' },
+      { key: 'desc', value: ' moddesk ' },
+      { key: 'top', value: ' mtpk ' },
+      { key: 'like', value: ' mlkk ' },
+      { key: 'not like', value: ' mnlkk ' },
+      { key: 'between', value: ' mbtnk ' },
+      { key: 'and', value: ' madk ' },
+      { key: 'insert', value: ' mistk ' },
+      { key: 'into', value: ' mitk ' },
+      { key: 'update', value: ' muptk ' },
+      { key: 'delete', value: ' mdelk ' },
+      { key: 'begin', value: ' mbgink ' },
+      { key: 'end', value: ' medk ' },
+      { key: 'if', value: ' mefk ' },
+      { key: 'while', value: ' mwilk ' },
+      { key: 'create', value: ' mcrtk ' },
+      { key: 'alter', value: ' matek ' },
+      { key: 'len', value: ' mlnk ' },
+      { key: 'left', value: ' mlftk ' },
+      { key: 'right', value: ' mritk ' },
+      { key: 'union', value: ' munok ' },
+      { key: 'varchar', value: ' mvcrk ' },
+      { key: 'getdate', value: ' mgtdtk ' },
+      { key: 'TRY', value: ' mtryonek ' },
+      { key: 'TRAN', value: ' mtrnk ' },
+      { key: 'goto', value: ' mgtk ' },
+      { key: 'set', value: ' mstk ' },
+      { key: 'ROLLBACK', value: ' mrlbkk ' }
+    ]
 
-    // 鏇挎崲鍏抽敭瀛�
-    format.forEach(item => {
-      let reg  =  new RegExp('(^|\\s)' + item.key + '(\\s|$)', 'ig')
-      value = value.replace(reg, item.value)
-    })
+    if (!isUnFormat) { // 鍔犲瘑
+      value = value.replace(/\n/ig, ' \n ')
+      // 鏇挎崲鍏抽敭瀛�
+      format.forEach(item => {
+        let reg = new RegExp('(^|\\s)' + item.key + '(\\s|$)', 'ig')
+        value = value.replace(reg, item.value)
+      })
+  
+      // 1銆佹浛鎹�%绗︼紙鏁版嵁搴撲腑瑙f瀽鍚巗ql鎶ラ敊锛�
+      value = value.replace(/%/ig, ' mpercent ')
 
-    // 1銆佹浛鎹�%绗︼紙鏁版嵁搴撲腑瑙f瀽鍚巗ql鎶ラ敊锛夛紝2銆佸幓闄ゆ敹灏惧浣欑┖鏍�
-    value = value.replace(/%/ig, 'mpercent')
-    value = value.replace(/(^\s|\s$)/ig, '')
+      // 1銆乪ncode缂栫爜锛堜腑鏂囧瓧绗﹁秴鍑篵ase64鍔犲瘑鑼冨洿锛夛紝2銆乥ase64鍔犲瘑
+      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 { // 瑙e瘑
+      try {
+        value = window.atob(value)
+        value = value.replace(salt, '')
+        value = window.decodeURIComponent(window.atob(value))
 
-    // 1銆乪ncode缂栫爜锛堜腑鏂囧瓧绗﹁秴鍑篵ase64鍔犲瘑鑼冨洿锛夛紝2銆乥ase64鍔犲瘑
-    value = window.btoa(window.encodeURIComponent(value))
+        value = value.replace(/\smpercent\s/g, '%')
 
-    // 鎻掑叆瀛楃
-    let index = Math.floor(value.length / 2)
-    value = value.slice(0, index) + salt + value.slice(index)
+        format.forEach(item => {
+          let reg = new RegExp(item.value, 'g')
+          value = value.replace(reg, ' ' + item.key + ' ')
+        })
 
-    // base64鍔犲瘑
-    value = window.btoa(value)
+        value = value.replace(/\s\n\s/ig, '\n')
+        value = value.replace(/(^\s+|\s+$)/ig, '')
+      } catch {
+        console.warn('UnFormat Failure')
+        value = ''
+      }
+    }
 
     return value
   }
@@ -198,7 +193,75 @@
         value: search.initval,
         required: search.required === 'true'
       }
-      if (item.type === 'date') {
+
+      if (item.type === 'group') {
+        let copy = JSON.parse(JSON.stringify(item))
+        copy.key = search.datefield
+
+        item.value = search.initval && search.initval[0] ? search.initval[0] : ''
+        item.match = '='
+        
+        copy.type = 'daterange'
+        copy.match = 'between'
+        copy.value = ''
+
+        if (search.initval && search.initval.length > 0) {
+          let _type = search.initval[0]
+          let _val = search.initval[1]
+
+          if (_type === 'day') {
+            copy.value = [moment().subtract(_val, 'days').format('YYYY-MM-DD'),
+              moment().subtract(_val, 'days').format('YYYY-MM-DD')]
+          } else if (_type === 'week') {
+            copy.value = [moment().subtract(_val * 7, 'days').startOf('week').format('YYYY-MM-DD'),
+              moment().subtract(_val * 7, 'days').endOf('week').format('YYYY-MM-DD')]
+          } else if (_type === 'month') {
+            copy.value = [moment().subtract(_val, 'month').startOf('month').format('YYYY-MM-DD'),
+              moment().subtract(_val, 'month').endOf('month').format('YYYY-MM-DD')]
+          } else if (_type === 'quarter') {
+            let _differ = parseInt(moment().format('MM')) % 3
+            let _pdiffer = 0
+            let _ndiffer = 0
+
+            // 宸�艰绠�
+            switch(_differ) {
+              case 0:
+                _pdiffer = 2
+                _ndiffer = 0
+                break
+              case 1:
+                _pdiffer = 0
+                _ndiffer = -2
+                break
+              case 2:
+                _pdiffer = 1
+                _ndiffer = -1
+                break
+              default:
+            }
+
+            copy.value = [moment().subtract(_pdiffer + _val * 3, 'month').startOf('month').format('YYYY-MM-DD'),
+              moment().subtract(_ndiffer + _val * 3, 'month').endOf('month').format('YYYY-MM-DD')]
+          } else if (_type === 'year') {
+            let _year = parseInt(moment().format('YYYY')) - _val
+            copy.value = [_year + '-01-01', _year + '-12-31']
+          } else if (_type === 'customized') {
+            try {
+              _val = JSON.parse(_val)
+            } catch {
+              _val = [0, 0]
+            }
+            copy.value = [moment().subtract(_val[0], 'days').format('YYYY-MM-DD'),
+              moment().subtract(_val[1], 'days').format('YYYY-MM-DD')]
+          }
+        }
+
+        if (search.transfer === 'true') {
+          newsearches.push(item)
+        }
+        newsearches.push(copy)
+        return
+      } else if (item.type === 'date') {
         item.value = item.value ? moment().subtract(item.value, 'days').format('YYYY-MM-DD') : ''
       } else if (item.type === 'datemonth') {
         item.value = item.value ? moment().subtract(item.value, 'month').format('YYYY-MM') : ''
@@ -249,14 +312,14 @@
         }
 
         if (newsearches[item.key]) {
-          newsearches[item.key + '1'] = _val ? _val + timetail : null
+          newsearches[item.key + '1'] = _val ? _val + timetail : ''
         } else {
-          newsearches[item.key] = _val ? _val + timetail : null
+          newsearches[item.key] = _val ? _val + timetail : ''
         }
       } else if (item.type === 'datemonth') {
         // 鏈�-杩囨护鏉′欢锛屼粠鏈堝紑濮嬭嚦缁撴潫
-        let _startval = null
-        let _endval = null
+        let _startval = ''
+        let _endval = ''
 
         if (item.value) {
           _startval = moment(item.value, 'YYYY-MM').startOf('month').format('YYYY-MM-DD') + ' 00:00:00.000'
@@ -271,16 +334,16 @@
           _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
         }
 
-        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : null
-        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : null
+        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : ''
+        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : ''
       } else if (item.type === 'daterange') {
         let _endval = ''
         if (item.value) {
           _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
         }
 
-        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : null
-        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : null
+        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : ''
+        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : ''
       } else if (item.type === 'text') {
         item.key.split(',').forEach(field => { // 缁煎悎鎼滅储锛屾墍瀛楁鎷兼帴
           newsearches[field] = item.value
@@ -326,12 +389,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'
@@ -364,7 +423,97 @@
         searchText += '(' + item.key + ' ' + item.match + ' \'' + item.value + '\')'
       }
     })
+
     return searchText
+  }
+
+  /**
+   * @description 鎷兼帴鎼滅储鏉′欢main
+   * @param {Array}   searches     鎼滅储鏉′欢
+   * @return {String}  searchText  鎷兼帴缁撴灉
+   */
+  static getAllSearchOptions (searches) {
+    if (!searches || searches.length === 0) return []
+
+    let options = []
+    let fieldmap = new Map()
+    searches.forEach(search => {
+      let item = {
+        key: search.key,
+        match: search.match,
+        type: search.type,
+        label: search.label,
+        value: search.value,
+        required: search.required
+      }
+
+      if (fieldmap.has(item.key)) {
+        item.key = item.key + '1'
+      }
+
+      fieldmap.set(item.key, true)
+
+      if (item.type === 'date') {
+        if (['>=', '>'].includes(item.match)) {
+          item.value = item.value ? item.value + ' 00:00:00.000' : '1990-01-01 00:00:00.000'
+        } else if (['<=', '<'].includes(item.match)) {
+          item.value = item.value ? moment(item.value, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2030-01-01 00:00:00.000'
+        }
+
+        options.push(item)
+      } else if (item.type === 'datemonth') {
+        let _startval = item.value ? moment(item.value, 'YYYY-MM').startOf('month').format('YYYY-MM-DD') + ' 00:00:00.000' : '1990-01-01 00:00:00.000'
+        let _endval = item.value ? moment(item.value, 'YYYY-MM').endOf('month').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2030-01-01 00:00:00.000'
+
+        let copy = JSON.parse(JSON.stringify(item))
+        copy.key = copy.key + '1'
+        copy.value = _endval
+        
+        item.value = _startval
+
+        options.push(item)
+        options.push(copy)
+      } else if (item.type === 'dateweek') {
+        let _startval = item.value && item.value[0] ? moment(item.value[0], 'YYYY-MM-DD').format('YYYY-MM-DD') + ' 00:00:00.000' : '1990-01-01 00:00:00.000'
+        let _endval = item.value && item.value[1] ? moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2030-01-01 00:00:00.000'
+
+        let copy = JSON.parse(JSON.stringify(item))
+        copy.key = copy.key + '1'
+        copy.value = _endval
+        
+        item.value = _startval
+
+        options.push(item)
+        options.push(copy)
+      } else if (item.type === 'daterange') {
+        let _startval = item.value && item.value[0] ? item.value[0] + ' 00:00:00.000' : '1990-01-01 00:00:00.000'
+        let _endval = item.value && item.value[1] ? moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2030-01-01 00:00:00.000'
+
+        let copy = JSON.parse(JSON.stringify(item))
+        copy.key = copy.key + '1'
+        copy.value = _endval
+        
+        item.value = _startval
+
+        options.push(item)
+        options.push(copy)
+      } else if (item.type === 'multiselect') {
+        item.value = item.value ? item.value.join(',') : item.value
+
+        options.push(item)
+      } else if (item.type === 'text') {
+        item.key.split(',').forEach(field => { // 缁煎悎鎼滅储锛屾墍瀛楁鎷兼帴
+          let cell = JSON.parse(JSON.stringify(item))
+          cell.key = field
+
+          options.push(item)
+        })
+      } else {
+        options.push(item)
+      }
+    })
+
+    return options
   }
 
   /**
@@ -480,6 +629,31 @@
     let errors = []
     let _topline = btn.range || 0
     let upId = this.getuuid()
+
+    let _initCustomScript = '' // 鍒濆鍖栬剼鏈�
+    let _prevCustomScript = '' // 榛樿sql鍓嶆墽琛岃剼鏈�
+    let _backCustomScript = '' // 榛樿sql鍚庢墽琛岃剼鏈�
+
+    if (btn.scripts) {
+      btn.scripts.forEach(script => {
+        if (script.status === 'false') return
+
+        if (script.position === 'init') {
+          _initCustomScript += `
+          ${script.sql}
+          `
+        } else if (script.position === 'front') {
+          _prevCustomScript += `
+          ${script.sql}
+          `
+        } else {
+          _backCustomScript += `
+          ${script.sql}
+          `
+        }
+      })
+    }
+
     let _Ltext = data.map((item, lindex) => {
       let vals = btn.columns.map((col, cindex) => {
         let val = item[col.Column] !== undefined ? item[col.Column] : ''
@@ -508,7 +682,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 {
@@ -526,7 +700,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 {
@@ -568,6 +742,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 = []
 
@@ -580,21 +796,19 @@
 
       let _insert = ''
 
+      if (_prevCustomScript) {
+        _insert += _prevCustomScript
+      }
+
       if (btn.default !== 'false') {
-        _insert = `
+        _insert += `
         Insert into ${item.sheet} (${fields},createuserid,createuser,createstaff,bid) 
         Select ${fields},@userid@,@username,@fullname,@BID@ From @${item.sheet}
         `
       }
 
-      if (btn.scripts && btn.scripts.length > 0) {
-        btn.scripts.forEach(script => {
-          if (script.status === 'false') return
-
-          _insert += `
-          ${script.sql}
-          `
-        })
+      if (_backCustomScript) {
+        _insert += _backCustomScript
       }
 
       _sql = `declare @${item.sheet} table (${declarefields.join(',')},jskey nvarchar(50) )
@@ -603,9 +817,10 @@
       Select  @ErrorCode='', @retmsg=''
       
       select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID@
-      
+      ${_initCustomScript}
       Insert into  @${item.sheet} (${fields},jskey)
       ${_Ltext}
+      ${_uniquesql}
       ${_insert}
       Delete @${item.sheet}
 
@@ -627,25 +842,55 @@
    * @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 _initCustomScript = '' // 鍒濆鍖栬剼鏈�
+    let _prevCustomScript = '' // 榛樿sql鍓嶆墽琛岃剼鏈�
+    let _backCustomScript = '' // 榛樿sql鍚庢墽琛岃剼鏈�
+
+    verify.scripts && verify.scripts.forEach(item => {
+      if (item.status === 'false') return
+
+      if (item.position === 'init') {
+        _initCustomScript += `
+        /* 鑷畾涔夎剼鏈� */
+        ${item.sql}
+        `
+      } else if (item.position === 'front') {
+        _prevCustomScript += `
+        /* 鑷畾涔夎剼鏈� */
+        ${item.sql}
+        `
+      } else {
+        _backCustomScript += `
+        /* 鑷畾涔夎剼鏈� */
+        ${item.sql}
+        `
+      }
+    })
+
     // 闇�瑕佸0鏄庣殑鍙橀噺闆�
     // 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']
 
     // 涓婚敭瀛楁
     let primaryKey = setting.primaryKey || 'id'
 
     // 绯荤粺鍙橀噺澹版槑涓庤缃垵濮嬪��
-    let _sql = `Declare @tbid nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@BillCode nvarchar(50),@BVoucher nvarchar(50),@FIBVoucherDate nvarchar(50), @FiYear nvarchar(50), @UserName nvarchar(50),@FullName nvarchar(50),@ModularDetailCode nvarchar(50)
+    let _sql = `/* 绯荤粺鐢熸垚 */
+        Declare @tbid nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@BillCode nvarchar(50),@BVoucher nvarchar(50),@FIBVoucherDate nvarchar(50), @FiYear nvarchar(50), @UserName nvarchar(50),@FullName nvarchar(50),@ModularDetailCode nvarchar(50)
       `
 
     // let _initvars = ['ID', 'BID', 'LoginUID', 'SessionUid', 'UserID', 'Appkey'] // 宸茶祴鍊煎瓧娈甸泦
-    // let _initvars = ['id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey'] // 宸茶祴鍊煎瓧娈甸泦
     let _initvars = [] // 宸茶祴鍊煎瓧娈甸泦
     let _initfields = []
     let _declarefields = []
@@ -659,8 +904,15 @@
         if (!_initvars.includes(_key)) {
           _initvars.push(_key)
 
-          if (form.type === 'number' && typeof(form.value) === 'number') {
-            _initfields.push(`@${_key}=${form.value}`)
+          if (form.type === 'number') {
+            let val = form.value
+            if (typeof(val) !== 'number') {
+              val = parseFloat(val)
+              if (isNaN(val)) {
+                val = 0
+              }
+            }
+            _initfields.push(`@${_key}=${val}`)
           } else {
             _initfields.push(`@${_key}='${form.value}'`)
           }
@@ -668,6 +920,10 @@
         
         if (!_vars.includes(_key)) {
           _vars.push(_key)
+
+          if (form.fieldlen && form.fieldlen > 2048) {
+            form.fieldlen = 'max'
+          }
 
           let _type = `nvarchar(${form.fieldlen})`
 
@@ -695,7 +951,13 @@
 
             let _val = data.hasOwnProperty(col.field) ? data[col.field] : ''
 
-            if (col.type === 'number' && typeof(_val) === 'number') {
+            if (col.type === 'number') {
+              if (typeof(_val) !== 'number') {
+                _val = parseFloat(_val)
+                if (isNaN(_val)) {
+                  _val = 0
+                }
+              }
               _initfields.push(`@${_key}=${_val}`)
             } else {
               _initfields.push(`@${_key}='${_val}'`)
@@ -704,6 +966,10 @@
           
           if (!_vars.includes(_key)) {
             _vars.push(_key)
+
+            if (col.fieldlength && col.fieldlength > 2048) {
+              col.fieldlength = 'max'
+            }
   
             let _type = `nvarchar(${col.fieldlength || 50})`
 
@@ -723,8 +989,9 @@
     // 鍙橀噺澹版槑
     _declarefields = _declarefields.join(',')
     if (_declarefields) {
-      _sql += `,${_declarefields}
-        `
+      _sql = `/* 绯荤粺鐢熸垚 */
+        Declare @tbid nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@BillCode nvarchar(50),@BVoucher nvarchar(50),@FIBVoucherDate nvarchar(50), @FiYear nvarchar(50), @UserName nvarchar(50),@FullName nvarchar(50),@ModularDetailCode nvarchar(50),${_declarefields}
+      `
     }
 
     // 鍙橀噺璧嬪��
@@ -733,11 +1000,6 @@
       _sql += `select ${_initfields}
         `
     }
-
-    // 娣诲姞鏃朵富閿负绌� 鏀逛负鍓嶅彴鐢熸垚
-    // if (btn.sqlType === 'insert') {
-    //   primaryId = ''
-    // }
 
     // 鍘婚櫎绂佺敤鐨勯獙璇�
     if (verify.contrasts) {
@@ -752,17 +1014,30 @@
     if (verify.billcodes) {
       verify.billcodes = verify.billcodes.filter(item => item.status !== 'false')
     }
-    if (verify.scripts) {
-      verify.scripts = verify.scripts.filter(item => item.status !== 'false')
+
+    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=''
-      `
+    // 鍒濆鍖栧嚟璇佸強鐢ㄦ埛淇℃伅瀛楁
+    _sql += `
+        /* 鍑瘉鍙婄敤鎴蜂俊鎭垵濮嬪寲璧嬪�� */
+        select @BVoucher='',@FIBVoucherDate='',@FiYear='',@ErrorCode='',@retmsg='',@UserName='${userName}', @FullName='${fullName}'
+        `
+
+    if (_initCustomScript) {
+      _sql += _initCustomScript
+    }
 
     // 鍚敤璐︽湡楠岃瘉
     if (verify.accountdate === 'true') {
-      _sql += `exec s_FIBVoucherDateCheck @ErrorCode=@ErrorCode OUTPUT,@retmsg=@retmsg OUTPUT
+      _sql += `
+        /* 璐︽湡楠岃瘉 */
+        exec s_FIBVoucherDateCheck @ErrorCode=@ErrorCode OUTPUT,@retmsg=@retmsg OUTPUT
         if @ErrorCode!=''
           GOTO aaa
         `
@@ -775,7 +1050,9 @@
         datasource = '(' + datasource + ') tb'
       }
 
-      _sql += `select @tbid='', @ErrorCode='',@retmsg=''
+      _sql += `
+        /* 澶辨晥楠岃瘉 */
+        select @tbid='', @ErrorCode='',@retmsg=''
         select @tbid=${primaryKey} from ${datasource} where ${primaryKey} ='${primaryId}'
         If @tbid=''
         Begin
@@ -788,12 +1065,14 @@
     // 姣旇緝楠岃瘉
     if (verify.contrasts && verify.contrasts.length > 0) {
       verify.contrasts.forEach(item => {
-        _sql += `If ${item.frontfield} ${item.operator} ${item.backfield}
-          Begin
-            select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
-              goto aaa
-          end
-          `
+        _sql += `
+        /* 姣旇緝楠岃瘉 */
+        If ${item.frontfield} ${item.operator} ${item.backfield}
+        Begin
+          select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
+            goto aaa
+        end
+        `
       })
     }
 
@@ -809,6 +1088,7 @@
         let _fieldValue = []                     // 琛ㄥ崟閿�煎field=value
         let _value = []                          // 琛ㄥ崟鍊硷紝鐢ㄤ簬閿欒鎻愮ず
         let _labels = item.fieldlabel.split(',') // 琛ㄥ崟鎻愮ず鏂囧瓧
+        let arr = [] // 楠岃瘉涓婚敭
 
         item.field.split(',').forEach((_field, index) => {
           let _fval = `'${_formFieldValue[_field]}'`
@@ -818,6 +1098,8 @@
           if (_field.toLowerCase() === 'bid' && !hasBid) { // 琛ㄥ崟涓病鏈塨id鍒欎娇鐢ㄧ郴缁焍id鍙橀噺
             _fval = '@BID@'
           }
+          arr.push(_field.toLowerCase())
+
           _fieldValue.push(`${_field}=${_fval}`)
           _value.push(`${_labels[index] || ''}锛�${_formFieldValue[_field] || ''}`)
         })
@@ -827,41 +1109,48 @@
           _verifyType = ' and deleted=0'
         }
 
-        _sql += `select @tbid='', @ErrorCode='',@retmsg=''
-          select @tbid='X' from ${btn.sql} where ${_fieldValue.join(' and ')} and ${primaryKey} !='${primaryId}'${_verifyType}
-          If @tbid!=''
-          Begin
-            select @ErrorCode='${item.errorCode}',@retmsg='${_value.join(', ')} 宸插瓨鍦�'
-            goto aaa
-          end
-          `
+        if (!arr.includes(primaryKey.toLowerCase())) {
+          _fieldValue.push(`${primaryKey} !='${primaryId}'`)
+        }
+
+        _sql += `
+        /* 鍞竴鎬ч獙璇� */
+        select @tbid='', @ErrorCode='',@retmsg=''
+        select @tbid='X' from ${btn.sql} where ${_fieldValue.join(' and ')}${_verifyType}
+        If @tbid!=''
+        Begin
+          select @ErrorCode='${item.errorCode}',@retmsg='${_value.join(', ')} 宸插瓨鍦�'
+          goto aaa
+        end
+        `
       })
     }
     
     // 鑷畾涔夐獙璇�
-    if (verify.customverifys && verify.customverifys.length > 0) {
-      verify.customverifys.forEach(item => {
-        _sql += `select @tbid='', @ErrorCode='',@retmsg=''
-          select top 1 @tbid='X' from (${item.sql}) a
-          If @tbid ${item.result === 'true' ? '!=' : '='}''
-          Begin
-            select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
-            goto aaa
-          end
-          `
-      })
-    }
+    verify.customverifys && verify.customverifys.forEach(item => {        
+      _sql += `
+        /* 鑷畾涔夐獙璇� */
+        select @tbid='', @ErrorCode='',@retmsg=''
+        select top 1 @tbid='X' from (${item.sql}) a
+        If @tbid ${item.result === 'true' ? '!=' : '='}''
+        Begin
+          select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
+          goto aaa
+        end
+        `
+    })
 
     // 鍗曞彿鐢熸垚锛屼娇鐢ㄤ笂绾d锛圔ID锛夋垨鍒楄〃鏁版嵁锛屽0鏄庡彉閲忥紙妫�楠岋級
+    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') {
@@ -884,22 +1173,28 @@
           _vars.push(_key)
         }
 
-        _sql += `${_declare}
-          select @BillCode='', @${_key}='', @ModularDetailCode=''
-          ${_lpline}
-          exec s_get_BillCode
-            @ModularDetailCode=${_ModularDetailCode},
-            @Type=${item.Type},
-            @TypeCharOne='${item.TypeCharOne}',
-            @TypeCharTwo ='${item.TypeCharTwo}',
-            @BillCode =@BillCode output,
-            @ErrorCode =@ErrorCode output, 
-            @retmsg=@retmsg output
-          if @ErrorCode!=''
-            goto aaa
-          set @${_key}=@BillCode
-          `
+        _billcodesSql += `
+        /* 鍗曞彿鐢熸垚 */
+        ${_declare}
+        select @BillCode='', @${_key}='', @ModularDetailCode=''
+        ${_lpline}
+        exec s_get_BillCode
+          @ModularDetailCode=${_ModularDetailCode},
+          @Type=${item.Type},
+          @TypeCharOne='${item.TypeCharOne}',
+          @TypeCharTwo ='${item.TypeCharTwo}',
+          @BillCode =@BillCode output,
+          @ErrorCode =@ErrorCode output, 
+          @retmsg=@retmsg output
+        if @ErrorCode!=''
+          goto aaa
+        set @${_key}=@BillCode
+        `
       })
+
+      if (_actionType !== 'insertOrUpdate') {
+        _sql += _billcodesSql
+      }
     }
 
     let hasvoucher = false
@@ -910,12 +1205,17 @@
 
       hasvoucher = true
 
-      _sql += `exec s_BVoucher_Create
+      _sql += `
+        /* 鍒涘缓鍑瘉 */
+        exec s_BVoucher_Create
           @Bill ='${data[_voucher.linkField]}',
           @BVoucherType ='${_voucher.BVoucherType}',
           @VoucherTypeOne ='${_voucher.VoucherTypeOne}',
           @VoucherTypeTwo ='${_voucher.VoucherTypeTwo}',
           @Type =${_voucher.Type},
+          @UserID=@UserID@,
+          @Username=@Username,
+          @FullName=@FullName,
           @BVoucher =@BVoucher OUTPUT ,
           @FIBVoucherDate =@FIBVoucherDate OUTPUT ,
           @FiYear =@FiYear OUTPUT ,
@@ -926,38 +1226,20 @@
         `
     }
 
-    // 鐢ㄤ簬鍙栫敤鎴蜂俊鎭�
-    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 = []
 
       formdata.forEach(item => {
-        if (item.type === 'funcvar') {
-          keys.push(item.key.toLowerCase())
-          values.push('@' + item.key)
-        } else if (item.type === 'number') {
-          keys.push(item.key.toLowerCase())
-          values.push(item.value)
-        } else {
-          keys.push(item.key.toLowerCase())
-          values.push('\'' + item.value + '\'')
-        }
+        keys.push(item.key.toLowerCase())
+        values.push('@' + item.key)
       })
 
-      if (!keys.includes(primaryKey)) {
-        keys.push(primaryKey)
+      if (!keys.includes(primaryKey.toLowerCase())) {
+        keys.push(primaryKey.toLowerCase())
         values.push('\'' + primaryId + '\'')
       }
       if (!keys.includes('createuserid')) {
@@ -973,28 +1255,30 @@
         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 = []
 
       formdata.forEach(item => {
         _arr.push(item.key.toLowerCase())
-
-        if (item.type === 'funcvar') {
-          _form.push(item.key + '=@' + item.key)
-        } else if (item.type === 'number') {
-          _form.push(item.key + '=' + item.value)
-        } else {
-          _form.push(item.key + '=\'' + item.value + '\'')
-        }
+        _form.push(item.key + '=@' + item.key)
       })
 
       if (!_arr.includes('modifydate')) {
@@ -1014,11 +1298,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 (_prevCustomScript) {
+      _sql += _prevCustomScript
+    }
+
+    // 娣诲姞銆佷慨鏀广�侀�昏緫鍒犻櫎銆佺墿鐞嗗垹闄�
+    if (_actionType === 'insert') {
+      _sql += `
+        /* 榛樿sql */
+        ${_insertsql}`
+    } else if (_actionType === 'update') {
+      _sql += `
+        /* 榛樿sql */
+        ${_updatesql}`
     } else if (_actionType === 'LogicDelete') { // 閫昏緫鍒犻櫎
-      _sql += `update ${btn.sql} set deleted=1,modifydate=getdate(),modifyuserid=@userid@ where ${primaryKey}=@${primaryKeyName};`
+      _sql += `
+        /* 榛樿sql */
+        update ${btn.sql} set deleted=1,modifydate=getdate(),modifyuserid=@userid@ where ${primaryKey}=@${primaryKeyName};`
     
     } else if (_actionType === 'delete') {      // 鐗╃悊鍒犻櫎
       let _msg = ''
@@ -1031,22 +1331,34 @@
           }
         })
       }
-      _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 += `
+        /* 榛樿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 += `
+        /* 榛樿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 => {
-        _scripts += `
-        ${item.sql}`
-      })
-      _sql += `${_scripts}`
+    if (_backCustomScript) {
+      _sql += _backCustomScript
     }
 
     _sql += `
-      aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
+        aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
+
+    _sql = _sql.replace(/\n\s{8}/ig, '\n')
     console.log(_sql)
     return _sql
   }
@@ -1251,6 +1563,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) {
@@ -1367,6 +1683,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 = []
 
@@ -1386,7 +1746,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}
 

--
Gitblit v1.8.0