functions.go 16 KB

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