functions.go 17 KB

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