functions.go 17 KB

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