From 27f12ae6cbc056470fa8291322a75676f806b54c Mon Sep 17 00:00:00 2001
From: king <18310653075@163.com>
Date: 星期五, 14 二月 2020 14:26:13 +0800
Subject: [PATCH] 2020-02-14

---
 src/utils/utils.js |  229 +++++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 212 insertions(+), 17 deletions(-)

diff --git a/src/utils/utils.js b/src/utils/utils.js
index 6b0a8e6..3bf9737 100644
--- a/src/utils/utils.js
+++ b/src/utils/utils.js
@@ -441,6 +441,131 @@
   }
 
   /**
+   * @description 鑾峰彇excel瀵煎叆鍙傛暟
+   * @return {String} btn   鎸夐挳
+   * @return {String} data  excel鏁版嵁
+   */
+  static getExcelInSql (item, data, dict) {
+    let btn = item.verify
+    let keys = ['delete', 'drop', 'insert', 'truncate', 'update']
+
+    let errors = []
+    let _topline = btn.range || 0
+    let _Ltext = data.map((item, lindex) => {
+      let vals = btn.columns.map((col, cindex) => {
+        let val = item[col.Column] !== undefined ? item[col.Column] : ''
+        let _position = (_topline + lindex + 1) + dict['main.excel.line'] + ' ' + (cindex + 1) + dict['main.excel.column']  + ' '
+
+        if (/^Nvarchar/ig.test(col.type)) {
+          if (typeof(val) === 'number') {
+            val = val.toString()
+          }
+
+          val = val.replace(/(^\s*$)|\t*|\v*/ig, '')
+
+          let limitlen = col.type.match(/\d+/)[0]
+
+          if (!val && col.required === 'true') { // 蹇呭~鏍¢獙
+            let _error =  _position + dict['main.excel.content.emptyerror']
+            errors.push(_error)
+          } else if (val.length > limitlen) {    // 闀垮害鏍¢獙
+            let _error =  _position + dict['main.excel.content.maxlimit']
+            errors.push(_error)
+          } else {                               // 鍏抽敭瀛楁牎楠�
+            keys.forEach(key => {
+              let _patten = new RegExp('(^' + key + '\\s+)|(\\s+' + key + '\\s+)', 'ig')
+              if (_patten.test(val)) {
+                let _error = _position + dict['main.excel.includekey'] + key
+                errors.push(_error)
+              }
+            })
+          }
+        } else if (/^int/ig.test(col.type)) {
+          if (typeof(val) !== 'number' || parseInt(val) < parseFloat(val)) { // 妫�楠屾槸鍚︿负鏁存暟
+            let _error = _position + dict['main.excel.content.interror']
+            errors.push(_error)
+          } else if ((col.min || col.min === 0) && val < col.min) {          // 鏈�灏忓�兼楠�
+            let _error = _position + dict['main.excel.content.limitmin']
+            errors.push(_error)
+          } else if ((col.max || col.max === 0) && val > col.max) {          // 鏈�澶у�兼楠�
+            let _error = _position + dict['main.excel.content.limitmax']
+            errors.push(_error)
+          }
+        } else if (/^Decimal/ig.test(col.type)) {
+          let _val = val + ''
+          _val = _val.split('.')
+          let limitlen = col.type.match(/\d+/ig)[1]
+
+          if (typeof(val) !== 'number') {                           // 妫�楠屾槸鍚︿负娴偣鏁�
+            let _error = _position + dict['main.excel.content.floaterror']
+            errors.push(_error)
+          } else if (_val[0].length > 18) {                         // 妫�楠屾暣鏁颁綅
+            let _error = _position + dict['main.excel.content.floatIntover']
+            errors.push(_error)
+          } else if (_val[1] && _val[1].length > limitlen) {        // 鏈�灏忓�兼楠�
+            let _error = _position + dict['main.excel.content.floatPointover']
+            errors.push(_error)
+          } else if ((col.min || col.min === 0) && val < col.min) { // 鏈�灏忓�兼楠�
+            let _error = _position + dict['main.excel.content.limitmin']
+            errors.push(_error)
+          } else if ((col.max || col.max === 0) && val > col.max) { // 鏈�澶у�兼楠�
+            let _error = _position + dict['main.excel.content.limitmax']
+            errors.push(_error)
+          }
+        }
+        
+        return `'${val}' as ${col.Column}`
+      })
+
+      if (!item.innerFunc) {
+        vals.push(`@upid+'${this.getuuid()}' as jskey`)
+      }
+
+      return `Select ${vals.join(',')}`
+    })
+
+    _Ltext = _Ltext.join(' Union all ')
+
+    let _sql = ''
+
+    if (!item.innerFunc) {
+      let declarefields = []
+      let fields = []
+      let timestamp = new Date().getTime()
+
+      btn.columns.forEach(col => {
+        declarefields.push(`${col.Column} ${col.type}`)
+        fields.push(col.Column)
+      })
+
+      fields = fields.join(',')
+
+      _sql = `declare @${btn.sheet} table (${declarefields.join(',')},jskey nvarchar(50) )
+      Declare @UserName nvarchar(50),@FullName nvarchar(50) ,@upid nvarchar(50)
+      select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID@
+      
+      set @upid='${timestamp}'
+     
+      Insert into  @${btn.sheet} (${fields},jskey)
+      ${_Ltext}
+
+      Insert into ${btn.sheet} (${fields},createuserid,createuser,createstaff,bid,upid) 
+      Select ${fields},@userid@,@username,@fullname,@BID@,@upid From @${btn.sheet}
+
+      Delete @${btn.sheet}`
+
+    } else {
+      _sql = _Ltext
+    }
+
+    console.log(_sql)
+    return {
+      sql: _sql,
+      errors: errors.join('; ')
+    }
+  }
+
+  /**
    * @description 浣跨敤绯荤粺鍑芥暟鏃讹紙sPC_TableData_InUpDe 锛夛紝鐢熸垚sql璇彞
    * @return {String} type   鎵ц绫诲瀷
    * @return {String} table  琛ㄥ悕
@@ -452,7 +577,8 @@
     let _formFieldValue = {}
     // 闇�瑕佸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', 'id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey']
+    let _vars = ['tbid', 'errorcode', 'retmsg', 'billcode', 'bvoucher', 'fibvoucherdate', 'fiyear', 'username', 'fullname']
 
     // 涓婚敭瀛楁
     let primaryKey = setting.primaryKey || 'id'
@@ -462,7 +588,8 @@
       `
 
     // let _initvars = ['ID', 'BID', 'LoginUID', 'SessionUid', 'UserID', 'Appkey'] // 宸茶祴鍊煎瓧娈甸泦
-    let _initvars = ['id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey'] // 宸茶祴鍊煎瓧娈甸泦
+    // let _initvars = ['id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey'] // 宸茶祴鍊煎瓧娈甸泦
+    let _initvars = [] // 宸茶祴鍊煎瓧娈甸泦
     let _initfields = []
     let _declarefields = []
 
@@ -474,7 +601,12 @@
 
         if (!_initvars.includes(_key)) {
           _initvars.push(_key)
-          _initfields.push(`@${_key}='${form.value}'`)
+
+          if (form.type === 'number' && typeof(form.value) === 'number') {
+            _initfields.push(`@${_key}=${form.value}`)
+          } else {
+            _initfields.push(`@${_key}='${form.value}'`)
+          }
         }
         
         if (!_vars.includes(_key)) {
@@ -505,7 +637,12 @@
             _initvars.push(_key)
 
             let _val = data.hasOwnProperty(col.field) ? data[col.field] : ''
-            _initfields.push(`@${_key}='${_val}'`)
+
+            if (col.type === 'number' && typeof(_val) === 'number') {
+              _initfields.push(`@${_key}=${_val}`)
+            } else {
+              _initfields.push(`@${_key}='${_val}'`)
+            }
           }
           
           if (!_vars.includes(_key)) {
@@ -514,7 +651,7 @@
             let _type = `nvarchar(${col.fieldlength || 50})`
 
             if (col.type === 'number') {
-              let _length = (col.decimal || col.decimal === 0) ? col.decimal : 18
+              let _length = col.decimal ? col.decimal : 0
               _type = `decimal(18,${_length})`
             } else if (col.type === 'picture' || col.type === 'textarea') {
               _type = `nvarchar(${col.fieldlength || 512})`
@@ -540,10 +677,10 @@
         `
     }
 
-    // 娣诲姞鏃朵富閿负绌�
-    if (btn.sqlType === 'insert') {
-      primaryId = ''
-    }
+    // 娣诲姞鏃朵富閿负绌� 鏀逛负鍓嶅彴鐢熸垚
+    // if (btn.sqlType === 'insert') {
+    //   primaryId = ''
+    // }
 
     // 鍘婚櫎绂佺敤鐨勯獙璇�
     if (verify.contrasts) {
@@ -605,13 +742,26 @@
 
     // 鍞竴鎬ч獙璇侊紝蹇呴』瀛樺湪琛ㄥ崟锛堣〃鍗曞瓨鍦ㄦ椂锛屼富閿潎涓哄崟鍊硷級,蹇呴』濉啓鏁版嵁婧�
     if (formdata && verify.uniques && verify.uniques.length > 0) {
+      let hasBid = false // 妫�楠岃〃鍗曞強鍒楀瓧娈典腑鏄惁鏈塨id
+      let _keys_ = Object.keys(_formFieldValue).map(key => key.toLowerCase())
+      if (_keys_.includes('bid')) {
+        hasBid = true
+      }
+
       verify.uniques.forEach(item => {
         let _fieldValue = []                     // 琛ㄥ崟閿�煎field=value
         let _value = []                          // 琛ㄥ崟鍊硷紝鐢ㄤ簬閿欒鎻愮ず
         let _labels = item.fieldlabel.split(',') // 琛ㄥ崟鎻愮ず鏂囧瓧
 
         item.field.split(',').forEach((_field, index) => {
-          _fieldValue.push(`${_field}='${_formFieldValue[_field]}'`)
+          let _fval = `'${_formFieldValue[_field]}'`
+          // if (['id', 'bid', 'loginuid', 'sessionuid', 'userid', 'appkey'].includes(_field.toLowerCase())) {
+          //   _fval = '@' + _field + '@'
+          // }
+          if (_field.toLowerCase() === 'bid' && !hasBid) { // 琛ㄥ崟涓病鏈塨id鍒欎娇鐢ㄧ郴缁焍id鍙橀噺
+            _fval = '@BID@'
+          }
+          _fieldValue.push(`${_field}=${_fval}`)
           _value.push(`${_labels[index] || ''}锛�${_formFieldValue[_field] || ''}`)
         })
 
@@ -686,13 +836,13 @@
       })
     }
 
-    let _updateconfig = ''
+    let hasvoucher = false
 
     // 鍑瘉-鏄剧ず鍒椾腑閫夊彇,蹇呴』閫夎
     if (verify.voucher && verify.voucher.enabled && data) {
       let _voucher = verify.voucher
 
-      _updateconfig = ',BVoucher=@BVoucher,FIBVoucherDate=@FIBVoucherDate,FiYear=@FiYear'
+      hasvoucher = true
 
       _sql += `exec s_BVoucher_Create
           @Bill ='${data[_voucher.linkField]}',
@@ -720,26 +870,52 @@
     if (btn.OpenType === 'pop' && btn.sqlType === 'insert' && verify.default !== 'false') {
       let keys = []
       let values = []
+
       formdata.forEach(item => {
         if (item.type === 'funcvar') {
-          keys.push(item.key)
+          keys.push(item.key.toLowerCase())
           values.push('@' + item.key)
         } else if (item.type === 'number') {
-          keys.push(item.key)
+          keys.push(item.key.toLowerCase())
           values.push(item.value)
         } else {
-          keys.push(item.key)
+          keys.push(item.key.toLowerCase())
           values.push('\'' + item.value + '\'')
         }
       })
 
+      if (!keys.includes(primaryKey)) {
+        keys.push(primaryKey)
+        values.push('\'' + primaryId + '\'')
+      }
+      if (!keys.includes('createuserid')) {
+        keys.push('createuserid')
+        values.push('@userid@')
+      }
+      if (!keys.includes('createuser')) {
+        keys.push('createuser')
+        values.push('@username')
+      }
+      if (!keys.includes('createstaff')) {
+        keys.push('createstaff')
+        values.push('@fullname')
+      }
+      if (!keys.includes('bid')) {
+        keys.push('bid')
+        values.push('@BID@')
+      }
+
       keys = keys.join(',')
       values = values.join(',')
       _sql += _user
-      _sql += `insert into ${btn.sql} (${keys},createuserid,CreateUser,CreateStaff,BID) select ${values},@userid@,@username,@fullname,@BID@;`
+      _sql += `insert into ${btn.sql} (${keys}) select ${values};`
     } else if (btn.OpenType === 'pop' && btn.sqlType === 'update' && verify.default !== 'false') {
       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') {
@@ -748,8 +924,27 @@
           _form.push(item.key + '=\'' + item.value + '\'')
         }
       })
+
+      if (!_arr.includes('modifydate')) {
+        _form.push('modifydate=getdate()')
+      }
+      if (!_arr.includes('modifyuserid')) {
+        _form.push('modifyuserid=@userid@')
+      }
+      if (hasvoucher) {
+        if (!_arr.includes('bvoucher')) {
+          _form.push('BVoucher=@BVoucher')
+        }
+        if (!_arr.includes('fibvoucherdate')) {
+          _form.push('FIBVoucherDate=@FIBVoucherDate')
+        }
+        if (!_arr.includes('fiyear')) {
+          _form.push('FiYear=@FiYear')
+        }
+      }
+
       _form = _form.join(',')
-      _sql += `update ${btn.sql} set ${_form},modifydate=getdate(),modifyuserid=@userid@${_updateconfig} where ${primaryKey}=@${primaryKeyName};`
+      _sql += `update ${btn.sql} set ${_form} where ${primaryKey}=@${primaryKeyName};`
     } else if ((btn.OpenType === 'prompt' || btn.OpenType === 'exec') && btn.sqlType === 'LogicDelete' && verify.default !== 'false') { // 閫昏緫鍒犻櫎
       _sql += `update ${btn.sql} set deleted=1,modifydate=getdate(),modifyuserid=@userid@ where ${primaryKey}=@${primaryKeyName};`
     } else if ((btn.OpenType === 'prompt' || btn.OpenType === 'exec') && btn.sqlType === 'delete' && verify.default !== 'false') {      // 鐗╃悊鍒犻櫎

--
Gitblit v1.8.0