You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.8 KiB
76 lines
1.8 KiB
package logic
|
|
|
|
import (
|
|
"context"
|
|
|
|
"healthapi/internal/model"
|
|
"healthapi/internal/svc"
|
|
"healthapi/internal/types"
|
|
"healthapi/pkg/errorx"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type CreateAddressLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewCreateAddressLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAddressLogic {
|
|
return &CreateAddressLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *CreateAddressLogic) CreateAddress(req *types.SaveAddressReq) (resp *types.Address, err error) {
|
|
userID, err := GetUserIDFromCtx(l.ctx)
|
|
if err != nil {
|
|
return nil, errorx.ErrUnauthorized
|
|
}
|
|
|
|
// 如果设为默认,先取消其他默认地址
|
|
if req.IsDefault {
|
|
l.svcCtx.DB.Model(&model.Address{}).Where("user_id = ?", userID).Update("is_default", false)
|
|
}
|
|
|
|
// 检查是否是第一个地址,如果是则自动设为默认
|
|
var count int64
|
|
l.svcCtx.DB.Model(&model.Address{}).Where("user_id = ?", userID).Count(&count)
|
|
if count == 0 {
|
|
req.IsDefault = true
|
|
}
|
|
|
|
addr := model.Address{
|
|
UserID: userID,
|
|
ReceiverName: req.ReceiverName,
|
|
Phone: req.Phone,
|
|
Province: req.Province,
|
|
City: req.City,
|
|
District: req.District,
|
|
DetailAddr: req.DetailAddr,
|
|
PostalCode: req.PostalCode,
|
|
IsDefault: req.IsDefault,
|
|
Tag: req.Tag,
|
|
}
|
|
|
|
if err := l.svcCtx.DB.Create(&addr).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
resp = &types.Address{
|
|
ID: uint(addr.ID),
|
|
ReceiverName: addr.ReceiverName,
|
|
Phone: addr.Phone,
|
|
Province: addr.Province,
|
|
City: addr.City,
|
|
District: addr.District,
|
|
DetailAddr: addr.DetailAddr,
|
|
PostalCode: addr.PostalCode,
|
|
IsDefault: addr.IsDefault,
|
|
Tag: addr.Tag,
|
|
}
|
|
return resp, nil
|
|
}
|
|
|