All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m50s
91 lines
2.5 KiB
Go
91 lines
2.5 KiB
Go
package exporter
|
|
|
|
import (
|
|
"context"
|
|
"strconv"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/break/junhong_cmp_fiber/internal/model"
|
|
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
|
)
|
|
|
|
// DeviceDataSource 设备导出数据源。
|
|
type DeviceDataSource struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewDeviceDataSource 创建设备导出数据源。
|
|
func NewDeviceDataSource(db *gorm.DB) *DeviceDataSource {
|
|
return &DeviceDataSource{db: db}
|
|
}
|
|
|
|
// Scene 返回导出场景编码。
|
|
func (s *DeviceDataSource) Scene() string {
|
|
return constants.ExportTaskSceneDevice
|
|
}
|
|
|
|
// Count 统计设备导出行数。
|
|
func (s *DeviceDataSource) Count(ctx context.Context, params ExportParams) (int, error) {
|
|
var total int64
|
|
query := s.applyFilters(s.db.WithContext(ctx).Model(&model.Device{}), params)
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return 0, err
|
|
}
|
|
return int(total), nil
|
|
}
|
|
|
|
// Headers 返回设备导出表头。
|
|
func (s *DeviceDataSource) Headers(ctx context.Context, params ExportParams) ([]string, error) {
|
|
return []string{"ID", "设备虚拟号", "设备名称", "设备型号", "设备类型", "状态", "店铺ID", "创建时间"}, nil
|
|
}
|
|
|
|
// Fetch 按 offset/limit 查询设备导出数据。
|
|
func (s *DeviceDataSource) Fetch(ctx context.Context, params ExportParams, offset, limit int) ([][]string, error) {
|
|
if limit <= 0 {
|
|
return [][]string{}, nil
|
|
}
|
|
|
|
var devices []model.Device
|
|
query := s.applyFilters(s.db.WithContext(ctx).Model(&model.Device{}), params).
|
|
Order("id ASC").
|
|
Limit(limit).
|
|
Offset(offset)
|
|
if err := query.Find(&devices).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
rows := make([][]string, 0, len(devices))
|
|
for _, item := range devices {
|
|
rows = append(rows, []string{
|
|
strconv.FormatUint(uint64(item.ID), 10),
|
|
item.VirtualNo,
|
|
item.DeviceName,
|
|
item.DeviceModel,
|
|
item.DeviceType,
|
|
strconv.Itoa(item.Status),
|
|
formatOptionalUint(item.ShopID),
|
|
item.CreatedAt.Format(exportTimeLayout),
|
|
})
|
|
}
|
|
return rows, nil
|
|
}
|
|
|
|
func (s *DeviceDataSource) applyFilters(query *gorm.DB, params ExportParams) *gorm.DB {
|
|
query = applyExportShopScope(query, params, "shop_id")
|
|
|
|
if status, ok := filterInt(params.Filters, "status"); ok {
|
|
query = query.Where("status = ?", status)
|
|
}
|
|
if shopID, ok := filterUint(params.Filters, "shop_id"); ok {
|
|
query = query.Where("shop_id = ?", shopID)
|
|
}
|
|
if start, ok := filterTime(params.Filters, "created_at_start"); ok {
|
|
query = query.Where("created_at >= ?", start)
|
|
}
|
|
if end, ok := filterTime(params.Filters, "created_at_end"); ok {
|
|
query = query.Where("created_at <= ?", end)
|
|
}
|
|
return query
|
|
}
|