functions.go 15 KB

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