init: initial commit
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
package plant
|
||||
|
||||
type ServiceGroup struct {
|
||||
MyPlantService
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package plant
|
||||
|
||||
import (
|
||||
"sundynix-go/global"
|
||||
common "sundynix-go/model/commom/request"
|
||||
"sundynix-go/model/plant"
|
||||
plantReq "sundynix-go/model/plant/request"
|
||||
plantRes "sundynix-go/model/plant/response"
|
||||
"sundynix-go/model/system"
|
||||
"sundynix-go/utils/timer"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MyPlantService struct{}
|
||||
|
||||
var MyPlantServiceApp = new(MyPlantService)
|
||||
|
||||
// AddPlant 添加植物
|
||||
func (s *MyPlantService) AddPlant(req plantReq.CreateMyPlant, id string) error {
|
||||
err := global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
//1. 验证oss是否存在
|
||||
var ossList []*system.Oss
|
||||
err := tx.Where("id in ?", req.OssIds).Find(&ossList).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bgTime := timer.GetZeroTime()
|
||||
//2. 处理养护计划
|
||||
var carePlans []*plant.CarePlan
|
||||
for _, v := range req.CarePlans {
|
||||
carePlans = append(carePlans, &plant.CarePlan{
|
||||
UserId: id,
|
||||
Name: v.Name,
|
||||
Icon: v.Icon,
|
||||
Period: v.Period,
|
||||
})
|
||||
}
|
||||
//3.保存数据
|
||||
myPlant := plant.MyPlant{
|
||||
UserId: id,
|
||||
Name: req.Name,
|
||||
PlantTime: bgTime,
|
||||
Status: 1,
|
||||
Placement: req.Placement,
|
||||
PotMaterial: req.PotMaterial,
|
||||
PotSize: req.PotSize,
|
||||
Sunlight: req.Sunlight,
|
||||
PlantingMaterial: req.PlantingMaterial,
|
||||
CarePlans: carePlans,
|
||||
}
|
||||
err = tx.Create(&myPlant).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
//4.处理图片关系
|
||||
if len(ossList) > 0 {
|
||||
var relations []map[string]interface{}
|
||||
for _, oss := range ossList {
|
||||
relations = append(relations, map[string]interface{}{
|
||||
"my_plant_id": myPlant.Id,
|
||||
"oss_id": oss.Id,
|
||||
})
|
||||
}
|
||||
err = tx.Table("sundynix_my_plant_oss").Create(relations).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
|
||||
}
|
||||
|
||||
// PlantPage 植物列表
|
||||
func (s *MyPlantService) PlantPage(req common.PageInfo, userId string) (list interface{}, total int64, err error) {
|
||||
limit := req.PageSize
|
||||
offset := req.PageSize * (req.Current - 1)
|
||||
db := global.DB.Model(&plant.MyPlant{}).Preload("ImgList", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("created_at desc")
|
||||
})
|
||||
var myPlants []*plant.MyPlant
|
||||
db = db.Where("user_id = ?", userId)
|
||||
err = db.Count(&total).Error
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = db.Limit(limit).Offset(offset).Order("created_at desc").Find(&myPlants).Error
|
||||
return myPlants, total, err
|
||||
}
|
||||
|
||||
// PlantDetail 植物详情
|
||||
func (s *MyPlantService) PlantDetail(id string) (p plant.MyPlant, err error) {
|
||||
var res plant.MyPlant
|
||||
err = global.DB.Where("id = ?", id).
|
||||
Preload("ImgList", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("created_at desc")
|
||||
}).
|
||||
Preload("CarePlans").
|
||||
Preload("CareRecords").
|
||||
First(&res).Error
|
||||
|
||||
//不存在的时候不要返回错误,而是返回nil
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (s *MyPlantService) UpdatePlant(req plantReq.UpdateMyPlant) error {
|
||||
// 以map形式更新 先构建map
|
||||
updateMap := map[string]interface{}{
|
||||
"name": req.Name,
|
||||
"placement": req.Placement,
|
||||
"planting_material": req.PlantingMaterial,
|
||||
"pot_material": req.PotMaterial,
|
||||
"pot_size": req.PotSize,
|
||||
"sunlight": req.Sunlight,
|
||||
}
|
||||
return global.DB.Model(&plant.MyPlant{}).Where("id = ?", req.Id).Updates(updateMap).Error
|
||||
}
|
||||
|
||||
// TodayTask 今日任务
|
||||
func (s *MyPlantService) TodayTask(userId string) ([]plantRes.PlantTaskVO, error) {
|
||||
today := timer.GetZeroTime()
|
||||
endOfToday := today.Add(24 * time.Hour)
|
||||
|
||||
var tasks []*plant.CareTask
|
||||
// 查询条件:1.未完成的任务(包含今天和以前逾期的) 2.今天已经完成的任务
|
||||
err := global.DB.Where("user_id = ? AND ("+
|
||||
"(status = 1 AND due_date < ?) OR "+
|
||||
"(status = 2 AND completed_at >= ? AND completed_at < ?)"+
|
||||
")", userId, endOfToday, today, endOfToday).
|
||||
Order("due_date ASC").
|
||||
Find(&tasks).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 2.内存处理:聚合数据
|
||||
plantTaskMap := make(map[string][]*plant.CareTask)
|
||||
expiredMap := make(map[string]bool)
|
||||
var plantIds []string
|
||||
for _, t := range tasks {
|
||||
plantIds = append(plantIds, t.PlantId)
|
||||
plantTaskMap[t.PlantId] = append(plantTaskMap[t.PlantId], t)
|
||||
// 判定右上角红标:状态为待办 且 应做时间早于今天
|
||||
if t.Status == 1 && t.DueDate.Before(today) {
|
||||
expiredMap[t.PlantId] = true
|
||||
}
|
||||
}
|
||||
//3.批量查询植物
|
||||
var myPlants []*plant.MyPlant
|
||||
err = global.DB.Where("id in ?", plantIds).Preload("ImgList", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("created_at desc")
|
||||
}).Find(&myPlants).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//4.组装结果
|
||||
var res []plantRes.PlantTaskVO
|
||||
for _, p := range myPlants {
|
||||
plantTaskVO := plantRes.PlantTaskVO{
|
||||
MyPlant: p,
|
||||
HasExpired: expiredMap[p.Id],
|
||||
Tasks: plantTaskMap[p.Id],
|
||||
}
|
||||
res = append(res, plantTaskVO)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// CompleteTask 完成任务
|
||||
func (s *MyPlantService) CompleteTask(req plantReq.CompleteTask) error {
|
||||
return global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
var task plant.CareTask
|
||||
if err := tx.Where("id = ?", req.TaskId).First(&task).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
//1.更新当前任务为完成
|
||||
updateData := map[string]interface{}{
|
||||
"status": 2,
|
||||
"completed_at": time.Now(),
|
||||
}
|
||||
if err := tx.Model(&task).Where("id = ?", req.TaskId).Updates(updateData).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
//2.获取计划模版
|
||||
var plan plant.CarePlan
|
||||
if err := tx.Where("id = ?", task.PlanId).First(&plan).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
//3.生成下个周期的任务
|
||||
today := timer.GetZeroTime()
|
||||
nextDueDate := today.AddDate(0, 0, plan.Period)
|
||||
newTask := plant.CareTask{
|
||||
UserId: plan.UserId,
|
||||
PlantId: plan.PlantId,
|
||||
PlanId: plan.Id,
|
||||
Name: plan.Name,
|
||||
Icon: plan.Icon,
|
||||
DueDate: nextDueDate,
|
||||
Status: 1,
|
||||
}
|
||||
if err := tx.Create(&newTask).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
//4.保存养护记录
|
||||
record := plant.CareRecord{
|
||||
UserId: plan.UserId,
|
||||
PlantId: plan.PlantId,
|
||||
PlanId: plan.Id,
|
||||
Name: plan.Name,
|
||||
Icon: plan.Icon,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
if err := tx.Create(&record).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package plant
|
||||
|
||||
//
|
||||
//import (
|
||||
// "context"
|
||||
// "errors"
|
||||
// "net/http"
|
||||
// "sundynix-go/global"
|
||||
// "sundynix-go/model/plant"
|
||||
// "sundynix-go/model/system"
|
||||
// "sundynix-go/utils/wechat"
|
||||
//
|
||||
// "github.com/gin-gonic/gin"
|
||||
// "github.com/wechatpay-apiv3/wechatpay-go/core"
|
||||
// "github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
|
||||
// "github.com/wechatpay-apiv3/wechatpay-go/core/notify"
|
||||
// "github.com/wechatpay-apiv3/wechatpay-go/services/payments"
|
||||
// "github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
|
||||
// "github.com/wechatpay-apiv3/wechatpay-go/utils"
|
||||
// "go.uber.org/zap"
|
||||
// "gorm.io/gorm"
|
||||
//)
|
||||
//
|
||||
//type PayService struct{}
|
||||
//
|
||||
//var PayServiceApp = new(PayService)
|
||||
//
|
||||
//// PrePay 预支付
|
||||
//func (s *PayService) PrePay(orderId, userId string) (resp *jsapi.PrepayWithRequestPaymentResponse, err error) {
|
||||
// //1.查询订单和 用户
|
||||
// var order plant.Order
|
||||
// err = global.DB.Where("id = ?", orderId).First(&order).Error
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// var user system.User
|
||||
// err = global.DB.Where("id = ?", userId).First(&user).Error
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// payClient, err := wechat.GetWxPayClient()
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
//
|
||||
// svc := jsapi.JsapiApiService{Client: payClient}
|
||||
// result, _, err := svc.PrepayWithRequestPayment(context.Background(),
|
||||
// jsapi.PrepayRequest{
|
||||
// Appid: core.String(global.Config.MiniProgram.AppId),
|
||||
// Mchid: core.String(global.Config.WechatPay.MchId),
|
||||
// Description: core.String(order.Name),
|
||||
// OutTradeNo: core.String(order.OutTradeNo),
|
||||
// //TimeExpire: core.Time(time.Now()), //选填
|
||||
// //Attach: core.String("自定义数据说明"), //选填
|
||||
// NotifyUrl: core.String(global.Config.WechatPay.NotifyUrl),
|
||||
// //GoodsTag: core.String("WXG"), //选填
|
||||
// //SupportFapiao: core.Bool(false), //选填
|
||||
// Amount: &jsapi.Amount{
|
||||
// Currency: core.String("CNY"),
|
||||
// Total: core.Int64(int64(order.Amount)),
|
||||
// },
|
||||
// Payer: &jsapi.Payer{
|
||||
// Openid: core.String(user.MiniOpenId),
|
||||
// },
|
||||
// //Detail: &jsapi.Detail{
|
||||
// // CostPrice: core.Int64(608800),
|
||||
// // GoodsDetail: []jsapi.GoodsDetail{jsapi.GoodsDetail{
|
||||
// // GoodsName: core.String("iPhoneX 256G"),
|
||||
// // MerchantGoodsId: core.String("ABC"),
|
||||
// // Quantity: core.Int64(1),
|
||||
// // UnitPrice: core.Int64(828800),
|
||||
// // WechatpayGoodsId: core.String("1001"),
|
||||
// // }},
|
||||
// // InvoiceId: core.String("wx123"),
|
||||
// //}, //选填
|
||||
// //SceneInfo: &jsapi.SceneInfo{
|
||||
// // DeviceId: core.String("013467007045764"),
|
||||
// // PayerClientIp: core.String("14.23.150.211"),
|
||||
// // StoreInfo: &jsapi.StoreInfo{
|
||||
// // Address: core.String("广东省深圳市南山区科技中一道10000号"),
|
||||
// // AreaCode: core.String("440305"),
|
||||
// // Id: core.String("0001"),
|
||||
// // Name: core.String("腾讯大厦分店"),
|
||||
// // },
|
||||
// //},
|
||||
// //SettleInfo: &jsapi.SettleInfo{
|
||||
// // ProfitSharing: core.Bool(false),
|
||||
// //}, //选填
|
||||
// })
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
//
|
||||
// return result, nil
|
||||
//
|
||||
//}
|
||||
//
|
||||
//// PayCallback 支付回调
|
||||
//func (s *PayService) PayCallback(c *gin.Context) error {
|
||||
// //1.加载共钥
|
||||
// mchPublicKeyPath := global.Config.WechatPay.PublicKeyPath
|
||||
// mchPublicKey, err := utils.LoadPublicKeyWithPath(mchPublicKeyPath)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// ctx := context.Background()
|
||||
// //2.创建客户端
|
||||
// handler, err := notify.NewRSANotifyHandler(global.Config.WechatPay.MchAPIv3Key,
|
||||
// verifiers.NewSHA256WithRSAPubkeyVerifier(global.Config.WechatPay.PublicKeyId, *mchPublicKey))
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// //3.验签 解密
|
||||
// //将支付回调通知中的内容,解析为 payments.Transaction。
|
||||
// transaction := new(payments.Transaction)
|
||||
// notifyReq, err := handler.ParseNotifyRequest(ctx, c.Request, transaction)
|
||||
// // 4.如果验签未通过,或者解密失败
|
||||
// if err != nil {
|
||||
// //应答微信
|
||||
// c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
|
||||
// "code": "FAIL",
|
||||
// "message": "失败",
|
||||
// })
|
||||
// global.Logger.Error("wxPay回调-验签或解密:", zap.Error(err))
|
||||
// return err
|
||||
// }
|
||||
// //5.应答微信
|
||||
// c.Status(http.StatusOK)
|
||||
// // 6.处理通知内容
|
||||
// global.Logger.Info("wxPay回调-成功:", zap.Any("notifyReq", notifyReq.Summary))
|
||||
// //7. 异步处理数据
|
||||
// go func() {
|
||||
// payNotify := plant.PayNotify{
|
||||
// Amount: *transaction.Amount.Total,
|
||||
// Currency: *transaction.Amount.Currency,
|
||||
// PayerCurrency: *transaction.Amount.PayerCurrency,
|
||||
// PayerTotal: *transaction.Amount.PayerTotal,
|
||||
// Appid: *transaction.Appid,
|
||||
// Mchid: *transaction.Mchid,
|
||||
// OutTradeNo: *transaction.OutTradeNo,
|
||||
// Attach: *transaction.Attach,
|
||||
// BankType: *transaction.BankType,
|
||||
// Payer: *transaction.Payer.Openid,
|
||||
// SuccessTime: *transaction.SuccessTime,
|
||||
// TradeState: *transaction.TradeState,
|
||||
// TradeStateDesc: *transaction.TradeStateDesc,
|
||||
// TradeType: *transaction.TradeType,
|
||||
// TransactionId: *transaction.TransactionId,
|
||||
// }
|
||||
// //7.1 回调记录
|
||||
// err = global.DB.Create(&payNotify).Error
|
||||
// if err != nil {
|
||||
// global.Logger.Error("wxPay回调-存储数据异常:", zap.Error(err))
|
||||
// }
|
||||
// if payNotify.TradeState == "SUCCESS" {
|
||||
// //7.2 扣商品库存
|
||||
// var order plant.Order
|
||||
// err = global.DB.Where("out_trade_no = ?", *transaction.OutTradeNo).First(&order).Error
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// global.Logger.Error("wxPay回调-订单不存在:", zap.Error(err))
|
||||
// }
|
||||
// }
|
||||
// //根据订单找到领取记录
|
||||
// var record plant.ClaimPlantRecord
|
||||
// err = global.DB.Where("order_id = ?", order.Id).First(&record).Error
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// global.Logger.Error("wxPay回调-领取记录不存在:", zap.Error(err))
|
||||
// }
|
||||
// }
|
||||
// //根据领取记录找到植物
|
||||
// var claimPlant plant.ClaimPlant
|
||||
// err = global.DB.Where("id = ?", record.ClaimPlantId).First(&claimPlant).Error
|
||||
// if err != nil {
|
||||
// if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// global.Logger.Error("wxPay回调-植物不存在:", zap.Error(err))
|
||||
// }
|
||||
// }
|
||||
// err = global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
// //扣库存
|
||||
// if err = tx.Model(&claimPlant).Update("stock", gorm.Expr("stock - ?", 1)).Error; err != nil {
|
||||
// return err
|
||||
// }
|
||||
// //订单状态
|
||||
// if err = tx.Model(&order).Update("pay_status", "SUCCESS").Error; err != nil {
|
||||
// return err
|
||||
// }
|
||||
// //修改领取记录为成功
|
||||
// if err = tx.Model(&record).Update("status", 1).Error; err != nil {
|
||||
// return err
|
||||
// }
|
||||
// //减用户积分
|
||||
// if err = tx.Model(&plant.Personal{}).Where("user_id = ?", order.UserId).Update("points_count", gorm.Expr("points_count - ?", claimPlant.Points)).Error; err != nil {
|
||||
// return err
|
||||
// }
|
||||
// return nil
|
||||
// })
|
||||
// }
|
||||
// if err != nil {
|
||||
// return
|
||||
// }
|
||||
// }()
|
||||
// return nil
|
||||
//
|
||||
//}
|
||||
Reference in New Issue
Block a user