daShangDao_psiServer/service/cancel_logistics.go

79 lines
2.0 KiB
Go

package service
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"psi/database"
"psi/models"
"time"
"github.com/pkg/errors"
)
type CancelLogisticsService struct{}
// CancelLogisticsResponse 取消物流接口返回
// 响应格式
type CancelLogisticsResponse struct {
Msg string `json:"msg"`
Code string `json:"code"`
}
// CancelLogistics 取消物流单号
func (s *CancelLogisticsService) CancelLogistics(userID int64, logisticsNo string) (*CancelLogisticsResponse, error) {
// 1. 调用外部接口取消物流单号
//定义字节流变量
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
if err := w.WriteField("mailNo", logisticsNo); err != nil {
return nil, errors.Wrap(err, "构造请求参数失败")
}
w.Close()
resp, err := http.Post("http://119.45.237.193:8073/api/print/cancelBmOrderApi", w.FormDataContentType(), &buf)
if err != nil {
return nil, errors.Wrap(err, "调用取消物流接口失败")
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "读取响应失败")
}
var cancelResp CancelLogisticsResponse
if err := json.Unmarshal(body, &cancelResp); err != nil {
return nil, errors.Wrap(err, "解析响应失败")
}
// 2. code 不是 200 直接返回
if cancelResp.Code != "200" {
return &cancelResp, nil
}
// 3. code == 200: 连接租户库,清空对应物流信息
tenantDB, err := database.GetTenantDB(userID)
if err != nil {
return nil, errors.Wrap(err, "获取租户数据库连接失败")
}
now := time.Now().Unix()
result := tenantDB.Model(&models.SalesOrderItem{}).
Where("logistics_no = ? AND is_del = ?", logisticsNo, 0).
Updates(map[string]interface{}{
"logistics_company": "",
"logistics_no": "",
"updated_at": now,
})
if result.Error != nil {
return nil, errors.Wrap(result.Error, "清空物流信息失败")
}
_ = result.RowsAffected // 不影响返回,仅用于调试
return &cancelResp, nil
}