functions.go 17 KB

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