12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package services
- import (
- "goiot-cronapi/models"
- "github.com/jinzhu/gorm"
- )
- func GetConsumeDatas(db *gorm.DB, count, pageSize int) []models.ConsumeData {
- var consumeList []models.ConsumeData
- sql := `SELECT m.id, m.name, m.box_id, m.utilization_rate, m.consumption_cycle, m.ascription, m.reset_runtime, p.project_name, p.user_id
- FROM btk_consumables_management m
- LEFT JOIN btk_project p
- ON p.project_auto_id = m.project_auto_id
- WHERE LENGTH(m.box_id) > 0 AND m.utilization_rate > 0 AND m.consumption_cycle > 0 AND m.is_delete = 0
- ORDER BY m.id DESC`
- db.Raw(sql).Limit(pageSize).Offset(count * pageSize).Find(&consumeList)
- for i, data := range consumeList {
- data.Ratio = 100 / float64(data.Cycle)
- consumeList[i] = data
- }
- return consumeList
- }
- func UpdateConsumeRate(db *gorm.DB, datas []models.ConsumeData, m map[string]int64) error {
- var (
- err error
- sql string
- )
- tx := db.Begin()
- for _, data := range datas {
- if data.Cycle <= 0 {
- continue
- }
- if data.Ascription == "盒子" {
- // 如果是盒子, 计算损耗率
- runtime := float64(m[data.BoxId])
- cycle := float64(data.Cycle * 24 * 60)
- if data.ResetRuntime > runtime {
- data.ResetRuntime = runtime
- }
- data.Rate = (cycle - (runtime - data.ResetRuntime)) / cycle * 100
- if data.Rate < 0 {
- data.Rate = 0
- }
- sql = "UPDATE btk_consumables_management SET utilization_rate = ? WHERE id = ?"
- err = tx.Exec(sql, data.Rate, data.ID).Error
- } else {
- // 如果是项目, 按照自然日每天扣减损耗率
- if data.Rate >= data.Ratio {
- sql = "UPDATE btk_consumables_management SET utilization_rate = utilization_rate - ? WHERE id = ?"
- err = tx.Exec(sql, data.Ratio, data.ID).Error
- } else {
- sql = "UPDATE btk_consumables_management SET utilization_rate = 0 WHERE id = ?"
- err = tx.Exec(sql, data.ID).Error
- }
- }
- if err != nil {
- tx.Rollback()
- break
- }
- }
- if err == nil {
- tx.Commit()
- }
- return err
- }
|