package model import ( "SciencesServer/app/common/model" "SciencesServer/serve/orm" "fmt" "time" ) type SysTenant struct { *model.SysTenant } type ( // SysTenantBasic 租户基本信息 SysTenantBasic struct { } // SysTenantInfo 租户信息 SysTenantInfo struct { *model.SysTenant DeviceCount int `json:"device_count"` CustomerDeviceCount int `json:"customer_device_count"` } // SysTenantSubsetInfo 租户子集信息 SysTenantSubsetInfo struct { ID uint64 `json:"id"` ParentID uint64 `json:"parent_id"` Name string `json:"name"` DeviceCount int `json:"device_count"` } // SysTenantDeviceCount 设备数量 SysTenantDeviceCount struct { TenantID uint64 `json:"tenant_id"` Count int `json:"count"` CustomerCount int `json:"customer_count"` } ) // IsInvalid 判断是否有效 func (m *SysTenant) IsInvalid() bool { return m.Status == model.SysTenantStatusForDisable || m.Status == model.SysTenantStatusForExpired || m.Deadline.Before(time.Now()) } // Tenants 租户信息 func (m *SysTenant) Tenants(page, pageSize int, count *int64, where ...*model.ModelWhere) ([]*SysTenantInfo, error) { db := orm.GetDB().Table(m.TableName()).Where("is_deleted = ?", model.DeleteStatusForNot) if len(where) > 0 { for _, wo := range where { db = db.Where(wo.Condition, wo.Value) } } out := make([]*SysTenantInfo, 0) if err := db.Count(count).Error; err != nil { return nil, err } if err := db.Order("id " + model.OrderModeToDesc).Offset((page - 1) * pageSize).Limit(pageSize).Scan(&out).Error; err != nil { return nil, err } return out, nil } // TenantSubset 租户子集信息 func (m *SysTenant) TenantSubset(tenantID uint64) ([]*SysTenantSubsetInfo, error) { sql := fmt.Sprintf(`SELECT t3.id, t3.parent_id, t3.name, d.count AS device_count FROM (SELECT t1.id, t1.parent_id, t1.name, IF(FIND_IN_SET( parent_id, @pids ) > 0, @pids := concat( @pids, ',', id ), 0 ) AS is_child FROM (SELECT id, parent_id, name FROM %s WHERE is_deleted = 0 ORDER BY id DESC) AS t1, (SELECT @pids := %d) AS t2) AS t3 LEFT JOIN (SELECT tenant_id, COUNT(id) AS count FROM %s WHERE is_deleted = 0 GROUP BY tenant_id) AS d ON t3.id = d.tenant_id WHERE is_child != 0`, m.TableName(), tenantID, "数据表") out := make([]*SysTenantSubsetInfo, 0) if err := orm.GetDB().Raw(sql).Scan(&out).Error; err != nil { return nil, err } return out, nil } func NewSysTenant() *SysTenant { return &SysTenant{SysTenant: model.NewSysTenant()} }