functions.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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("%G", 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. node.ContractsPay = fmt.Sprintf("%G", totalPay)
  125. quotient = totalPaid / totalPay
  126. if math.IsNaN(quotient) {
  127. quotient = 0
  128. }
  129. node.ContractsPayProgress = fmt.Sprintf("%.0f", (quotient)*100) + "%"
  130. // 安全巡检
  131. node.SafeTotal = safeTotal
  132. node.SafeRectification = safeTotalRectification
  133. node.SafeRectificationIn = safeTotalRectificationIn
  134. // 质量巡检
  135. node.QualityTotal = qualityTotal
  136. node.QualityRectification = qualityTotalRectification
  137. node.QualityRectificationIn = qualityTotalRectificationIn
  138. }
  139. }
  140. // 是否有子树
  141. func HaveChildContract(Data []*viewmodels.FolderContract, node *viewmodels.FolderContract) (child []*viewmodels.FolderContract, yes bool) {
  142. for _, v := range Data {
  143. if v.ParentId == node.Id {
  144. child = append(child, v)
  145. }
  146. }
  147. if child != nil {
  148. yes = true
  149. }
  150. return
  151. }
  152. // 创建合同项目节树
  153. func MakeSectionContract(Data []*viewmodels.TreeSectionContract, node *viewmodels.TreeSectionContract) { //参数为父节点,添加父节点的子节点指针切片
  154. childs, _ := haveChildSectionContract(Data, node) //判断节点是否有子节点并返回
  155. if childs != nil {
  156. // 往父节点添加子节点
  157. // 孩子们从小到大排序
  158. if len(childs) != 0 {
  159. sectionSelectionSort(childs)
  160. childs[0].ElderBrother = false
  161. childs[len(childs)-1].IsEnd = true
  162. }
  163. // 项目节父项使用
  164. // 1.合同总金额 回款总金额 已支付总金额
  165. contractPriceTotal := 0.00
  166. returnPriceTotal := 0.00
  167. paidPriceTotal := 0.00
  168. node.Children = append(node.Children, childs[0:]...) //添加子节点
  169. for _, v := range childs { //查询子节点的子节点,并添加到子节点
  170. _, has := haveChildSectionContract(Data, v)
  171. if has {
  172. // 递归添加节点
  173. MakeSectionContract(Data, v)
  174. }
  175. // 2.计算父项中金额
  176. contractPrice, _ := strconv.ParseFloat(v.ContractPrice, 64)
  177. contractPriceTotal += contractPrice
  178. returnPrice, _ := strconv.ParseFloat(v.ContractReturned, 64)
  179. returnPriceTotal += returnPrice
  180. paidPrice, _ := strconv.ParseFloat(v.ContractsPaid, 64)
  181. paidPriceTotal += paidPrice
  182. }
  183. // 3.赋值到父项中
  184. node.ContractPrice = fmt.Sprintf("%.2f", contractPriceTotal)
  185. node.ContractReturned = fmt.Sprintf("%.2f", returnPriceTotal)
  186. node.ContractsPaid = fmt.Sprintf("%.2f", paidPriceTotal)
  187. }
  188. }
  189. // 合同项目节孩子排序
  190. func sectionSelectionSort(child []*viewmodels.TreeSectionContract) {
  191. for i := 0; i < len(child); i++ {
  192. minIndex := i
  193. // 查找最小值
  194. for j := i; j < len(child); j++ {
  195. if child[j].Serial < child[minIndex].Serial {
  196. minIndex = j
  197. }
  198. }
  199. swapContract(child, i, minIndex)
  200. }
  201. }
  202. func swapContract(child []*viewmodels.TreeSectionContract, i int, minIndex int) {
  203. t := child[i]
  204. child[i] = child[minIndex]
  205. child[minIndex] = t
  206. }
  207. // 是否有子树
  208. func haveChildSectionContract(Data []*viewmodels.TreeSectionContract, node *viewmodels.TreeSectionContract) (child []*viewmodels.TreeSectionContract, yes bool) {
  209. for _, v := range Data {
  210. if v.ParentId == node.Id {
  211. child = append(child, v)
  212. }
  213. }
  214. if child != nil {
  215. yes = true
  216. }
  217. return
  218. }
  219. // 当前时间的时间戳
  220. func NowUnix() int {
  221. return int(time.Now().In(conf.SysTimeLocation).Unix())
  222. }
  223. // 将unix时间戳格式化为yyyymmdd H:i:s格式字符串
  224. func FormatFromUnixTime(t int64) string {
  225. if t > 0 {
  226. return time.Unix(t, 0).Format(conf.SysTimeform)
  227. } else {
  228. return time.Now().Format(conf.SysTimeform)
  229. }
  230. }
  231. // 将unix时间戳格式化为yyyymmdd格式字符串
  232. func FormatFromUnixTimeShort(t int64) string {
  233. if t > 0 {
  234. return time.Unix(t, 0).Format(conf.SysTimeformShort)
  235. } else {
  236. return time.Now().Format(conf.SysTimeformShort)
  237. }
  238. }
  239. // 将字符串转成时间
  240. func ParseTime(str string) (time.Time, error) {
  241. return time.ParseInLocation(conf.SysTimeform, str, conf.SysTimeLocation)
  242. }
  243. // 得到一个随机数
  244. func Random(max int) int {
  245. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  246. if max < 1 {
  247. return r.Int()
  248. } else {
  249. return r.Intn(max)
  250. }
  251. }
  252. // 加密密码
  253. func CreatePasswordSign(password string, account string) string {
  254. str := string(conf.SignSecret) + password + account
  255. str1 := fmt.Sprintf("%x", md5.Sum([]byte(str)))
  256. sign := fmt.Sprintf("%x", md5.Sum([]byte(str1)))
  257. return sign
  258. }
  259. // 对字符串进行签名
  260. func CreateSign(str string) string {
  261. str = string(conf.SignSecret) + str
  262. str1 := fmt.Sprintf("%x", md5.Sum([]byte(str)))
  263. sign := fmt.Sprintf("%x", md5.Sum([]byte(str1)))
  264. return sign
  265. }
  266. // 对一个字符串进行加密
  267. func Encrypt(key, text []byte) (string, error) {
  268. block, err := aes.NewCipher(key)
  269. if err != nil {
  270. return "", err
  271. }
  272. b := base64.StdEncoding.EncodeToString(text)
  273. ciphertext := make([]byte, aes.BlockSize+len(b))
  274. iv := ciphertext[:aes.BlockSize]
  275. //if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  276. // return nil, err
  277. //}
  278. cfb := cipher.NewCFBEncrypter(block, iv)
  279. cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
  280. return base64.RawURLEncoding.EncodeToString(ciphertext), nil
  281. }
  282. // 对一个字符串进行解密
  283. func Decrypt(key, text []byte) ([]byte, error) {
  284. block, err := aes.NewCipher(key)
  285. if err != nil {
  286. return nil, err
  287. }
  288. if len(text) < aes.BlockSize {
  289. return nil, errors.New("ciphertext too short")
  290. }
  291. iv := text[:aes.BlockSize]
  292. text = text[aes.BlockSize:]
  293. cfb := cipher.NewCFBDecrypter(block, iv)
  294. cfb.XORKeyStream(text, text)
  295. data, err := base64.StdEncoding.DecodeString(string(text))
  296. if err != nil {
  297. return nil, err
  298. }
  299. return data, nil
  300. }
  301. // 加密
  302. func AesEncrypt(orig string, key string) (string, error) {
  303. // 转成字节数组
  304. origData := []byte(orig)
  305. k := []byte(key)
  306. // 分组秘钥
  307. block, err := aes.NewCipher(k)
  308. if err != nil {
  309. return "", err
  310. }
  311. // 获取秘钥块的长度
  312. blockSize := block.BlockSize()
  313. // 补全码
  314. origData = PKCS7Padding(origData, blockSize)
  315. // 加密模式
  316. blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
  317. // 创建数组
  318. cryted := make([]byte, len(origData))
  319. // 加密
  320. blockMode.CryptBlocks(cryted, origData)
  321. //使用RawURLEncoding 不要使用StdEncoding
  322. //不要使用StdEncoding 放在url参数中回导致错误
  323. return base64.RawURLEncoding.EncodeToString(cryted), nil
  324. }
  325. // 解密
  326. func AesDecrypt(cryted string, key string) (string, error) {
  327. //使用RawURLEncoding 不要使用StdEncoding
  328. //不要使用StdEncoding 放在url参数中回导致错误
  329. crytedByte, err := base64.RawURLEncoding.DecodeString(cryted)
  330. if err != nil {
  331. return "", err
  332. }
  333. k := []byte(key)
  334. // 分组秘钥
  335. block, err := aes.NewCipher(k)
  336. if err != nil {
  337. return "", err
  338. }
  339. // 获取秘钥块的长度
  340. blockSize := block.BlockSize()
  341. // 加密模式
  342. blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
  343. // 创建数组
  344. orig := make([]byte, len(crytedByte))
  345. // 解密--传入不正确的字符时会报错-TODO 需捕获
  346. blockMode.CryptBlocks(orig, crytedByte)
  347. // 去补全码
  348. orig = PKCS7UnPadding(orig)
  349. return string(orig), nil
  350. }
  351. //补码
  352. func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
  353. padding := blocksize - len(ciphertext)%blocksize
  354. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  355. return append(ciphertext, padtext...)
  356. }
  357. //去码
  358. func PKCS7UnPadding(origData []byte) []byte {
  359. length := len(origData)
  360. unpadding := int(origData[length-1])
  361. return origData[:(length - unpadding)]
  362. }
  363. // addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。
  364. // 预定义字符是:
  365. // 单引号(')
  366. // 双引号(")
  367. // 反斜杠(\)
  368. func Addslashes(str string) string {
  369. tmpRune := []rune{}
  370. strRune := []rune(str)
  371. for _, ch := range strRune {
  372. switch ch {
  373. case []rune{'\\'}[0], []rune{'"'}[0], []rune{'\''}[0]:
  374. tmpRune = append(tmpRune, []rune{'\\'}[0])
  375. tmpRune = append(tmpRune, ch)
  376. default:
  377. tmpRune = append(tmpRune, ch)
  378. }
  379. }
  380. return string(tmpRune)
  381. }
  382. // stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。
  383. func Stripslashes(str string) string {
  384. dstRune := []rune{}
  385. strRune := []rune(str)
  386. strLenth := len(strRune)
  387. for i := 0; i < strLenth; i++ {
  388. if strRune[i] == []rune{'\\'}[0] {
  389. i++
  390. }
  391. dstRune = append(dstRune, strRune[i])
  392. }
  393. return string(dstRune)
  394. }
  395. // 将字符串的IP转化为数字
  396. func Ip4toInt(ip string) int64 {
  397. bits := strings.Split(ip, ".")
  398. if len(bits) == 4 {
  399. b0, _ := strconv.Atoi(bits[0])
  400. b1, _ := strconv.Atoi(bits[1])
  401. b2, _ := strconv.Atoi(bits[2])
  402. b3, _ := strconv.Atoi(bits[3])
  403. var sum int64
  404. sum += int64(b0) << 24
  405. sum += int64(b1) << 16
  406. sum += int64(b2) << 8
  407. sum += int64(b3)
  408. return sum
  409. } else {
  410. return 0
  411. }
  412. }
  413. // 得到当前时间到下一天零点的延时
  414. func NextDayDuration() time.Duration {
  415. year, month, day := time.Now().Add(time.Hour * 24).Date()
  416. next := time.Date(year, month, day, 0, 0, 0, 0, conf.SysTimeLocation)
  417. return next.Sub(time.Now())
  418. }
  419. // 从接口类型安全获取到int64
  420. func GetInt64(i interface{}, d int64) int64 {
  421. if i == nil {
  422. return d
  423. }
  424. switch i.(type) {
  425. case string:
  426. num, err := strconv.Atoi(i.(string))
  427. if err != nil {
  428. return d
  429. } else {
  430. return int64(num)
  431. }
  432. case []byte:
  433. bits := i.([]byte)
  434. if len(bits) == 8 {
  435. return int64(binary.LittleEndian.Uint64(bits))
  436. } else if len(bits) <= 4 {
  437. num, err := strconv.Atoi(string(bits))
  438. if err != nil {
  439. return d
  440. } else {
  441. return int64(num)
  442. }
  443. }
  444. case uint:
  445. return int64(i.(uint))
  446. case uint8:
  447. return int64(i.(uint8))
  448. case uint16:
  449. return int64(i.(uint16))
  450. case uint32:
  451. return int64(i.(uint32))
  452. case uint64:
  453. return int64(i.(uint64))
  454. case int:
  455. return int64(i.(int))
  456. case int8:
  457. return int64(i.(int8))
  458. case int16:
  459. return int64(i.(int16))
  460. case int32:
  461. return int64(i.(int32))
  462. case int64:
  463. return i.(int64)
  464. case float32:
  465. return int64(i.(float32))
  466. case float64:
  467. return int64(i.(float64))
  468. }
  469. return d
  470. }
  471. // 从接口类型安全获取到字符串类型
  472. func GetString(str interface{}, d string) string {
  473. if str == nil {
  474. return d
  475. }
  476. switch str.(type) {
  477. case string:
  478. return str.(string)
  479. case []byte:
  480. return string(str.([]byte))
  481. }
  482. return fmt.Sprintf("%s", str)
  483. }
  484. // 从map中得到指定的key
  485. func GetInt64FromMap(dm map[string]interface{}, key string, dft int64) int64 {
  486. data, ok := dm[key]
  487. if !ok {
  488. return dft
  489. }
  490. return GetInt64(data, dft)
  491. }
  492. // 从map中得到指定的key
  493. func GetInt64FromStringMap(dm map[string]string, key string, dft int64) int64 {
  494. data, ok := dm[key]
  495. if !ok {
  496. return dft
  497. }
  498. return GetInt64(data, dft)
  499. }
  500. // 从map中得到指定的key
  501. func GetStringFromMap(dm map[string]interface{}, key string, dft string) string {
  502. data, ok := dm[key]
  503. if !ok {
  504. return dft
  505. }
  506. return GetString(data, dft)
  507. }
  508. // 从map中得到指定的key
  509. func GetStringFromStringMap(dm map[string]string, key string, dft string) string {
  510. data, ok := dm[key]
  511. if !ok {
  512. return dft
  513. }
  514. return data
  515. }
  516. // 首字母大写
  517. func Ucfirst(str string) string {
  518. for i, v := range str {
  519. return string(unicode.ToUpper(v)) + str[i+1:]
  520. }
  521. return ""
  522. }