feat(expiry): 完成 #25 用户设置接口实现
This commit is contained in:
@@ -19,6 +19,7 @@ var (
|
||||
ErrExpiryFilterCategoryInvalid = errors.New("category 参数无效")
|
||||
ErrExpiryFilterSortInvalid = errors.New("sort 参数无效")
|
||||
ErrExpiryStatusInvalid = errors.New("状态无效,仅支持 used/discarded")
|
||||
ErrExpiryRemindDaysInvalid = errors.New("remind_days 必须是 1-30 的整数,数量 1-5 个")
|
||||
)
|
||||
|
||||
// Service 封装保质期模块业务逻辑。
|
||||
@@ -86,6 +87,11 @@ type SummaryResponse struct {
|
||||
Discarded int `json:"discarded"`
|
||||
}
|
||||
|
||||
// SettingsResponse 用户提醒设置返回结构。
|
||||
type SettingsResponse struct {
|
||||
RemindDays []int `json:"remind_days"`
|
||||
}
|
||||
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
@@ -255,6 +261,41 @@ func (s *Service) UpdateItemStatus(id, userID uint, status string) error {
|
||||
return s.repo.UpdateStatus(id, userID, status)
|
||||
}
|
||||
|
||||
// GetSettings 获取用户提醒设置;若未配置则返回默认值。
|
||||
func (s *Service) GetSettings(userID uint) (*SettingsResponse, error) {
|
||||
settings, err := s.repo.GetSettings(userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if settings == nil || len(settings.RemindDays) == 0 {
|
||||
return &SettingsResponse{
|
||||
RemindDays: copyIntSlice(defaultRemindDays),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &SettingsResponse{
|
||||
RemindDays: copyIntSlice(settings.RemindDays),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateSettings 更新用户提醒设置。
|
||||
func (s *Service) UpdateSettings(userID uint, remindDays []int) (*SettingsResponse, error) {
|
||||
validated, err := validateRemindDays(remindDays)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
settings, err := s.repo.UpdateSettings(userID, validated)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &SettingsResponse{
|
||||
RemindDays: copyIntSlice(settings.RemindDays),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func validateBaseFields(name, category string, quantity int, location, remark string) error {
|
||||
name = strings.TrimSpace(name)
|
||||
category = strings.TrimSpace(category)
|
||||
@@ -367,3 +408,28 @@ func toItemView(item ExpiryItem) ItemView {
|
||||
UpdatedAt: item.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func validateRemindDays(days []int) ([]int, error) {
|
||||
if len(days) == 0 || len(days) > 5 {
|
||||
return nil, ErrExpiryRemindDaysInvalid
|
||||
}
|
||||
|
||||
seen := make(map[int]struct{}, len(days))
|
||||
result := make([]int, 0, len(days))
|
||||
for _, day := range days {
|
||||
if day < 1 || day > 30 {
|
||||
return nil, ErrExpiryRemindDaysInvalid
|
||||
}
|
||||
if _, ok := seen[day]; ok {
|
||||
continue
|
||||
}
|
||||
seen[day] = struct{}{}
|
||||
result = append(result, day)
|
||||
}
|
||||
|
||||
if len(result) == 0 || len(result) > 5 {
|
||||
return nil, ErrExpiryRemindDaysInvalid
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user