functions.go 17 KB

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