functions.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * @description: 常用函数
  3. * @Author: CP
  4. * @Date: 2020-08-21 11:12:56
  5. * @FilePath: \construction_management\comm\functions.go
  6. */
  7. package comm
  8. import (
  9. "bytes"
  10. "crypto/aes"
  11. "crypto/cipher"
  12. "encoding/base64"
  13. "errors"
  14. "math"
  15. "math/rand"
  16. "time"
  17. "unicode"
  18. "crypto/md5"
  19. "encoding/binary"
  20. "fmt"
  21. "strconv"
  22. "strings"
  23. "go.mod/conf"
  24. "go.mod/models"
  25. "go.mod/web/viewmodels"
  26. )
  27. // 账号-构造视图层models
  28. func MakeProjectAccountVM(modelsAccount *models.CmProjectAccount) viewmodels.ProjectAccount {
  29. viewAccountData := viewmodels.ProjectAccount{}
  30. aesId, _ := AesEncrypt(strconv.Itoa(modelsAccount.Id), conf.SignSecret)
  31. aesProjectId, _ := AesEncrypt(strconv.Itoa(modelsAccount.ProjectId), conf.SignSecret)
  32. viewAccountData.Id = aesId
  33. viewAccountData.ProjectId = aesProjectId
  34. viewAccountData.Account = modelsAccount.Account
  35. viewAccountData.Name = modelsAccount.Name
  36. viewAccountData.Company = modelsAccount.Company
  37. viewAccountData.Role = modelsAccount.Role
  38. viewAccountData.Mobile = modelsAccount.Mobile
  39. viewAccountData.Telephone = modelsAccount.Telephone
  40. viewAccountData.IsAdmin = modelsAccount.IsAdmin
  41. viewAccountData.AccountGroup = modelsAccount.AccountGroup
  42. viewAccountData.Enable = modelsAccount.Enable
  43. viewAccountData.Position = modelsAccount.Position
  44. // viewAccountData.ContractPermission = modelsAccount.ContractPermission
  45. // viewAccountData.QualityPermission = modelsAccount.QualityPermission
  46. // viewAccountData.SafePermission = modelsAccount.SafePermission
  47. return viewAccountData
  48. }
  49. // 创建合同目录树
  50. func MakeFolderContract(Data []*viewmodels.FolderContract, node *viewmodels.FolderContract) { //参数为父节点,添加父节点的子节点指针切片
  51. childs, _ := HaveChildContract(Data, node) //判断节点是否有子节点并返回
  52. if childs != nil {
  53. // 子节点总数
  54. Total := len(childs)
  55. node.ChildsTotal = Total
  56. // 标记最后一个元素
  57. end := Total - 1
  58. childs[end].IsEnd = true
  59. // 往父节点添加子节点
  60. node.Children = append(node.Children, childs[0:]...) //添加子节点
  61. // 1.标段汇总
  62. // 1-1.合同相关汇总-收入金额
  63. totalIncome := 0.00
  64. // 1-2.合同总数
  65. totalContractNumber := 0
  66. // 1-3.汇款进度
  67. totalReturn := 0.00
  68. // 1-4支出金额
  69. totalPay := 0.00
  70. totalPaid := 0.00
  71. // 1-5 安全巡检
  72. safeTotal := 0
  73. safeTotalRectification := 0
  74. safeTotalRectificationIn := 0
  75. // 1-6 质量巡检
  76. qualityTotal := 0
  77. qualityTotalRectification := 0
  78. qualityTotalRectificationIn := 0
  79. for _, v := range childs { //查询子节点的子节点,并添加到子节点
  80. _, has := HaveChildContract(Data, v)
  81. if has {
  82. // 递归添加节点
  83. MakeFolderContract(Data, v)
  84. }
  85. // 目录下是否包含标段
  86. if v.Isfolder == 0 {
  87. node.IsBid = true
  88. } else {
  89. node.HasFolder = true
  90. }
  91. // 2.标段汇总
  92. // 2-1收入金额 合计
  93. price, _ := strconv.ParseFloat(v.ContractsIncome, 64)
  94. totalIncome = totalIncome + price
  95. // 2-2合同总数 合计
  96. totalContractNumber = totalContractNumber + v.Contracts
  97. // 2-3 汇款进度
  98. price, _ = strconv.ParseFloat(v.ContractsReturned, 64)
  99. totalReturn = totalReturn + price
  100. //
  101. price, _ = strconv.ParseFloat(v.ContractsPay, 64)
  102. totalPay = totalPay + price
  103. price, _ = strconv.ParseFloat(v.ContractsPaid, 64)
  104. totalPaid = totalPaid + price
  105. // 安全巡检
  106. safeTotal = safeTotal + v.SafeTotal
  107. safeTotalRectification = safeTotalRectification + v.SafeRectification
  108. safeTotalRectificationIn = safeTotalRectificationIn + v.SafeRectificationIn
  109. // 1-6 质量巡检
  110. qualityTotal = safeTotal + v.QualityTotal
  111. qualityTotalRectification = safeTotalRectification + v.QualityRectification
  112. qualityTotalRectificationIn = safeTotalRectificationIn + v.QualityRectificationIn
  113. }
  114. node.ContractsIncome = fmt.Sprintf("%.2f", totalIncome)
  115. node.Contracts = totalContractNumber
  116. // 汇款进度
  117. quotient := totalReturn / totalIncome
  118. if math.IsNaN(quotient) {
  119. quotient = 0
  120. }
  121. node.ContractsIncomeProgress = fmt.Sprintf("%.0f", (quotient)*100) + "%"
  122. // 支出相关
  123. node.ContractsPay = fmt.Sprintf("%.2f", totalPay)
  124. quotient = totalPaid / totalPay
  125. if math.IsNaN(quotient) {
  126. quotient = 0
  127. }
  128. node.ContractsPayProgress = fmt.Sprintf("%.0f", (quotient)*100) + "%"
  129. // 安全巡检
  130. node.SafeTotal = safeTotal
  131. node.SafeRectification = safeTotalRectification
  132. node.SafeRectificationIn = safeTotalRectificationIn
  133. // 质量巡检
  134. node.QualityTotal = qualityTotal
  135. node.QualityRectification = qualityTotalRectification
  136. node.QualityRectificationIn = qualityTotalRectificationIn
  137. }
  138. }
  139. // 是否有子树
  140. func HaveChildContract(Data []*viewmodels.FolderContract, node *viewmodels.FolderContract) (child []*viewmodels.FolderContract, yes bool) {
  141. for _, v := range Data {
  142. if v.ParentId == node.Id {
  143. child = append(child, v)
  144. }
  145. }
  146. if child != nil {
  147. yes = true
  148. }
  149. return
  150. }
  151. // 创建合同项目节树
  152. func MakeSectionContract(Data []*viewmodels.TreeSectionContract, node *viewmodels.TreeSectionContract) { //参数为父节点,添加父节点的子节点指针切片
  153. childs, _ := haveChildSectionContract(Data, node) //判断节点是否有子节点并返回
  154. if childs != nil {
  155. // 往父节点添加子节点
  156. // 孩子们从小到大排序
  157. if len(childs) != 0 {
  158. sectionSelectionSort(childs)
  159. childs[0].ElderBrother = false
  160. childs[len(childs)-1].IsEnd = true
  161. }
  162. node.Children = append(node.Children, childs[0:]...) //添加子节点
  163. for _, v := range childs { //查询子节点的子节点,并添加到子节点
  164. _, has := haveChildSectionContract(Data, v)
  165. if has {
  166. // 递归添加节点
  167. MakeSectionContract(Data, v)
  168. }
  169. }
  170. }
  171. }
  172. // 合同项目节孩子排序
  173. func sectionSelectionSort(child []*viewmodels.TreeSectionContract) {
  174. for i := 0; i < len(child); i++ {
  175. minIndex := i
  176. // 查找最小值
  177. for j := i; j < len(child); j++ {
  178. if child[j].Serial < child[minIndex].Serial {
  179. minIndex = j
  180. }
  181. }
  182. swapContract(child, i, minIndex)
  183. }
  184. }
  185. func swapContract(child []*viewmodels.TreeSectionContract, i int, minIndex int) {
  186. t := child[i]
  187. child[i] = child[minIndex]
  188. child[minIndex] = t
  189. }
  190. // 是否有子树
  191. func haveChildSectionContract(Data []*viewmodels.TreeSectionContract, node *viewmodels.TreeSectionContract) (child []*viewmodels.TreeSectionContract, yes bool) {
  192. for _, v := range Data {
  193. if v.ParentId == node.Id {
  194. child = append(child, v)
  195. }
  196. }
  197. if child != nil {
  198. yes = true
  199. }
  200. return
  201. }
  202. // 当前时间的时间戳
  203. func NowUnix() int {
  204. return int(time.Now().In(conf.SysTimeLocation).Unix())
  205. }
  206. // 将unix时间戳格式化为yyyymmdd H:i:s格式字符串
  207. func FormatFromUnixTime(t int64) string {
  208. if t > 0 {
  209. return time.Unix(t, 0).Format(conf.SysTimeform)
  210. } else {
  211. return time.Now().Format(conf.SysTimeform)
  212. }
  213. }
  214. // 将unix时间戳格式化为yyyymmdd格式字符串
  215. func FormatFromUnixTimeShort(t int64) string {
  216. if t > 0 {
  217. return time.Unix(t, 0).Format(conf.SysTimeformShort)
  218. } else {
  219. return time.Now().Format(conf.SysTimeformShort)
  220. }
  221. }
  222. // 将字符串转成时间
  223. func ParseTime(str string) (time.Time, error) {
  224. return time.ParseInLocation(conf.SysTimeform, str, conf.SysTimeLocation)
  225. }
  226. // 得到一个随机数
  227. func Random(max int) int {
  228. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  229. if max < 1 {
  230. return r.Int()
  231. } else {
  232. return r.Intn(max)
  233. }
  234. }
  235. // 加密密码
  236. func CreatePasswordSign(password string, account string) string {
  237. str := string(conf.SignSecret) + password + account
  238. str1 := fmt.Sprintf("%x", md5.Sum([]byte(str)))
  239. sign := fmt.Sprintf("%x", md5.Sum([]byte(str1)))
  240. return sign
  241. }
  242. // 对字符串进行签名
  243. func CreateSign(str string) string {
  244. str = string(conf.SignSecret) + str
  245. str1 := fmt.Sprintf("%x", md5.Sum([]byte(str)))
  246. sign := fmt.Sprintf("%x", md5.Sum([]byte(str1)))
  247. return sign
  248. }
  249. // 对一个字符串进行加密
  250. func Encrypt(key, text []byte) (string, error) {
  251. block, err := aes.NewCipher(key)
  252. if err != nil {
  253. return "", err
  254. }
  255. b := base64.StdEncoding.EncodeToString(text)
  256. ciphertext := make([]byte, aes.BlockSize+len(b))
  257. iv := ciphertext[:aes.BlockSize]
  258. //if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  259. // return nil, err
  260. //}
  261. cfb := cipher.NewCFBEncrypter(block, iv)
  262. cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
  263. return base64.RawURLEncoding.EncodeToString(ciphertext), nil
  264. }
  265. // 对一个字符串进行解密
  266. func Decrypt(key, text []byte) ([]byte, error) {
  267. block, err := aes.NewCipher(key)
  268. if err != nil {
  269. return nil, err
  270. }
  271. if len(text) < aes.BlockSize {
  272. return nil, errors.New("ciphertext too short")
  273. }
  274. iv := text[:aes.BlockSize]
  275. text = text[aes.BlockSize:]
  276. cfb := cipher.NewCFBDecrypter(block, iv)
  277. cfb.XORKeyStream(text, text)
  278. data, err := base64.StdEncoding.DecodeString(string(text))
  279. if err != nil {
  280. return nil, err
  281. }
  282. return data, nil
  283. }
  284. // 加密
  285. func AesEncrypt(orig string, key string) (string, error) {
  286. // 转成字节数组
  287. origData := []byte(orig)
  288. k := []byte(key)
  289. // 分组秘钥
  290. block, err := aes.NewCipher(k)
  291. if err != nil {
  292. return "", err
  293. }
  294. // 获取秘钥块的长度
  295. blockSize := block.BlockSize()
  296. // 补全码
  297. origData = PKCS7Padding(origData, blockSize)
  298. // 加密模式
  299. blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
  300. // 创建数组
  301. cryted := make([]byte, len(origData))
  302. // 加密
  303. blockMode.CryptBlocks(cryted, origData)
  304. //使用RawURLEncoding 不要使用StdEncoding
  305. //不要使用StdEncoding 放在url参数中回导致错误
  306. return base64.RawURLEncoding.EncodeToString(cryted), nil
  307. }
  308. // 解密
  309. func AesDecrypt(cryted string, key string) (string, error) {
  310. //使用RawURLEncoding 不要使用StdEncoding
  311. //不要使用StdEncoding 放在url参数中回导致错误
  312. crytedByte, err := base64.RawURLEncoding.DecodeString(cryted)
  313. if err != nil {
  314. return "", err
  315. }
  316. k := []byte(key)
  317. // 分组秘钥
  318. block, err := aes.NewCipher(k)
  319. if err != nil {
  320. return "", err
  321. }
  322. // 获取秘钥块的长度
  323. blockSize := block.BlockSize()
  324. // 加密模式
  325. blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
  326. // 创建数组
  327. orig := make([]byte, len(crytedByte))
  328. // 解密--传入不正确的字符时会报错-TODO 需捕获
  329. blockMode.CryptBlocks(orig, crytedByte)
  330. // 去补全码
  331. orig = PKCS7UnPadding(orig)
  332. return string(orig), nil
  333. }
  334. //补码
  335. func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
  336. padding := blocksize - len(ciphertext)%blocksize
  337. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  338. return append(ciphertext, padtext...)
  339. }
  340. //去码
  341. func PKCS7UnPadding(origData []byte) []byte {
  342. length := len(origData)
  343. unpadding := int(origData[length-1])
  344. return origData[:(length - unpadding)]
  345. }
  346. // addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。
  347. // 预定义字符是:
  348. // 单引号(')
  349. // 双引号(")
  350. // 反斜杠(\)
  351. func Addslashes(str string) string {
  352. tmpRune := []rune{}
  353. strRune := []rune(str)
  354. for _, ch := range strRune {
  355. switch ch {
  356. case []rune{'\\'}[0], []rune{'"'}[0], []rune{'\''}[0]:
  357. tmpRune = append(tmpRune, []rune{'\\'}[0])
  358. tmpRune = append(tmpRune, ch)
  359. default:
  360. tmpRune = append(tmpRune, ch)
  361. }
  362. }
  363. return string(tmpRune)
  364. }
  365. // stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。
  366. func Stripslashes(str string) string {
  367. dstRune := []rune{}
  368. strRune := []rune(str)
  369. strLenth := len(strRune)
  370. for i := 0; i < strLenth; i++ {
  371. if strRune[i] == []rune{'\\'}[0] {
  372. i++
  373. }
  374. dstRune = append(dstRune, strRune[i])
  375. }
  376. return string(dstRune)
  377. }
  378. // 将字符串的IP转化为数字
  379. func Ip4toInt(ip string) int64 {
  380. bits := strings.Split(ip, ".")
  381. if len(bits) == 4 {
  382. b0, _ := strconv.Atoi(bits[0])
  383. b1, _ := strconv.Atoi(bits[1])
  384. b2, _ := strconv.Atoi(bits[2])
  385. b3, _ := strconv.Atoi(bits[3])
  386. var sum int64
  387. sum += int64(b0) << 24
  388. sum += int64(b1) << 16
  389. sum += int64(b2) << 8
  390. sum += int64(b3)
  391. return sum
  392. } else {
  393. return 0
  394. }
  395. }
  396. // 得到当前时间到下一天零点的延时
  397. func NextDayDuration() time.Duration {
  398. year, month, day := time.Now().Add(time.Hour * 24).Date()
  399. next := time.Date(year, month, day, 0, 0, 0, 0, conf.SysTimeLocation)
  400. return next.Sub(time.Now())
  401. }
  402. // 从接口类型安全获取到int64
  403. func GetInt64(i interface{}, d int64) int64 {
  404. if i == nil {
  405. return d
  406. }
  407. switch i.(type) {
  408. case string:
  409. num, err := strconv.Atoi(i.(string))
  410. if err != nil {
  411. return d
  412. } else {
  413. return int64(num)
  414. }
  415. case []byte:
  416. bits := i.([]byte)
  417. if len(bits) == 8 {
  418. return int64(binary.LittleEndian.Uint64(bits))
  419. } else if len(bits) <= 4 {
  420. num, err := strconv.Atoi(string(bits))
  421. if err != nil {
  422. return d
  423. } else {
  424. return int64(num)
  425. }
  426. }
  427. case uint:
  428. return int64(i.(uint))
  429. case uint8:
  430. return int64(i.(uint8))
  431. case uint16:
  432. return int64(i.(uint16))
  433. case uint32:
  434. return int64(i.(uint32))
  435. case uint64:
  436. return int64(i.(uint64))
  437. case int:
  438. return int64(i.(int))
  439. case int8:
  440. return int64(i.(int8))
  441. case int16:
  442. return int64(i.(int16))
  443. case int32:
  444. return int64(i.(int32))
  445. case int64:
  446. return i.(int64)
  447. case float32:
  448. return int64(i.(float32))
  449. case float64:
  450. return int64(i.(float64))
  451. }
  452. return d
  453. }
  454. // 从接口类型安全获取到字符串类型
  455. func GetString(str interface{}, d string) string {
  456. if str == nil {
  457. return d
  458. }
  459. switch str.(type) {
  460. case string:
  461. return str.(string)
  462. case []byte:
  463. return string(str.([]byte))
  464. }
  465. return fmt.Sprintf("%s", str)
  466. }
  467. // 从map中得到指定的key
  468. func GetInt64FromMap(dm map[string]interface{}, key string, dft int64) int64 {
  469. data, ok := dm[key]
  470. if !ok {
  471. return dft
  472. }
  473. return GetInt64(data, dft)
  474. }
  475. // 从map中得到指定的key
  476. func GetInt64FromStringMap(dm map[string]string, key string, dft int64) int64 {
  477. data, ok := dm[key]
  478. if !ok {
  479. return dft
  480. }
  481. return GetInt64(data, dft)
  482. }
  483. // 从map中得到指定的key
  484. func GetStringFromMap(dm map[string]interface{}, key string, dft string) string {
  485. data, ok := dm[key]
  486. if !ok {
  487. return dft
  488. }
  489. return GetString(data, dft)
  490. }
  491. // 从map中得到指定的key
  492. func GetStringFromStringMap(dm map[string]string, key string, dft string) string {
  493. data, ok := dm[key]
  494. if !ok {
  495. return dft
  496. }
  497. return data
  498. }
  499. // 首字母大写
  500. func Ucfirst(str string) string {
  501. for i, v := range str {
  502. return string(unicode.ToUpper(v)) + str[i+1:]
  503. }
  504. return ""
  505. }