123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546 |
- package service
- import (
- "app.yhyue.com/moapp/jyResourcesCenter/entity"
- "app.yhyue.com/moapp/jyResourcesCenter/rpc/resourcesCenter"
- "bytes"
- "encoding/json"
- "fmt"
- "github.com/gogf/gf/v2/util/gconv"
- "io/ioutil"
- "log"
- "net/http"
- "strconv"
- "time"
- )
- type BalanceService struct{}
- const (
- ConsumeRecord = "consume_record" //流水表
- AccountResources = "account_resources" //结存表
- )
- // 根据账户标识新增资源
- func (service *BalanceService) PurchaseUserBalance(balanceData *resourcesCenter.Balance, detailedData *resourcesCenter.Detailed, producMap map[string]interface{}) (int64, string) {
- orm := entity.Engine.NewSession()
- err := orm.Begin()
- balance := entity.Balance{}
- userType := int64(1)
- remarks := detailedData.Remarks
- if detailedData.ResourceType == "附件下载包" {
- remarksMap := map[string]interface{}{}
- switch balanceData.Model {
- case 0:
- remarksMap["describe"] = fmt.Sprintf("购买附件下载包,获得%v(读取购买数量)个附件下载权益。\n附件下载权益当月有效。\n", balanceData.Number)
- case 2:
- userType = 2
- remarksMap["describe"] = "剑鱼币兑换成功\n兑换剑鱼币30天内有效。\n"
- case 3:
- userType = 3
- remarksMap["describe"] = fmt.Sprintf("超级订阅用户每月享有下载%v个附件的权限,每月1号上余额清零重新计算。", balanceData.Number)
- }
- jsonData, err := json.Marshal(remarksMap)
- if err != nil {
- fmt.Println(err)
- }
- remarks = string(jsonData)
- }
- if producMap[balanceData.ResourceType] != nil {
- fool, err := orm.Table(AccountResources).
- Select("*").
- Where("accountId=? and companyId=? and departmentId=? and ResourceType=? and endTime=? and vipTime=? and sourceType=?",
- balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, balanceData.EndTime, balanceData.VipTime, userType).
- Get(&balance)
- if err != nil && !fool {
- fmt.Println("结存查询失败:", err)
- return entity.ErrorCode, "企业下的组织查询失败"
- }
- } else {
- fool, err := orm.Table(AccountResources).
- Select("*").
- Where("accountId=? and companyId=? and departmentId=? and ResourceType=? and endTime=? and sourceType=?", balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, balanceData.EndTime, userType).
- Get(&balance)
- if err != nil && !fool {
- fmt.Println("结存查询失败:", err)
- return entity.ErrorCode, "企业下的组织查询失败"
- }
- }
- //新增流水记录
- detailed := entity.Detailed{
- AccountId: detailedData.AccountId,
- CompanyId: detailedData.CompanyId,
- DepartmentId: detailedData.DepartmentId,
- ResourceType: detailedData.ResourceType,
- Number: detailedData.Number,
- RuleId: detailedData.RuleId,
- Name: detailedData.Name,
- CreateTime: time.Now().Local(),
- Remarks: remarks,
- UserType: userType,
- }
- insertNumb, err := orm.Table(ConsumeRecord).Insert(&detailed)
- if err != nil {
- fmt.Println("新增流水失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "新增流水失败"
- }
- if insertNumb <= 0 {
- orm.Rollback()
- return entity.ErrorCode, "新增流水失败"
- }
- //资源流水新增
- //orm.Table(AccountResources).Insert(&balance)
- if balance.Id == 0 {
- //新增结存记录
- balance = entity.Balance{
- AccountId: balanceData.AccountId,
- CompanyId: balanceData.CompanyId,
- DepartmentId: balanceData.DepartmentId,
- Name: balanceData.Name,
- ResourceType: balanceData.ResourceType,
- Number: balanceData.Number,
- Spec: balanceData.Spec,
- AppId: balanceData.AppId,
- EndTime: balanceData.EndTime,
- VipTime: balanceData.VipTime,
- SourceType: userType,
- }
- insertNumb, err = orm.Table(AccountResources).Insert(&balance)
- if err != nil || insertNumb <= 0 {
- fmt.Println("结存查询失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "结存新增失败"
- }
- orm.Commit()
- return entity.SuccessCode, "结存新增成功"
- }
- balance.Number = balance.Number + balanceData.Number
- updateNumb, err := orm.Table(AccountResources).Cols("number").
- Where(" id=?", balance.Id).
- Update(&balance)
- if err != nil || updateNumb <= 0 {
- orm.Rollback()
- fmt.Println("结存修改失败:", err)
- return entity.ErrorCode, "结存修改失败"
- }
- orm.Commit()
- return entity.SuccessCode, "结存修改成功"
- }
- // 根据账户标识使用资源
- func (service *BalanceService) UseUserDetailed(duplicateRemoval int64, balanceData *resourcesCenter.Balance, detailedData *resourcesCenter.Detailed, infoId, url string, producMap map[string]interface{}) (int64, string, int64) {
- orm := entity.Engine.NewSession()
- err := orm.Begin()
- //去重
- deductionNumb := detailedData.Number
- deductionNumbs := detailedData.Number
- if duplicateRemoval == 1 {
- dataDesc := 0
- if detailedData.ResourceType == "标准字段包" {
- dataDesc = 2
- } else if detailedData.ResourceType == "高级字段包" {
- dataDesc = 1
- }
- var appheader = "application/x-www-form-urlencoded"
- param := "dataDesc=" + fmt.Sprint(dataDesc) + "&personId=" + detailedData.UserId + "&infoId=" + infoId + "&accountId=" + detailedData.AccountId
- resp, status, _ := HttpPost_M(url+"/data/dedupAndSave/"+fmt.Sprint(time.Now().Unix()), appheader, param, 20)
- log.Println(resp, status)
- if status != 200 && (resp == nil || len(resp) <= 0) {
- return entity.ErrorCode, "请求去重接口出错", 0
- }
- data := resp["data"].(map[string]interface{})
- if fmt.Sprint(resp["code"]) == "0" {
- deductionNumb, _ = strconv.ParseInt(fmt.Sprint(data["newCount"]), 10, 64)
- deductionNumbs, _ = strconv.ParseInt(fmt.Sprint(data["newCount"]), 10, 64)
- if fmt.Sprint(data["totalCount"]) == "0" {
- return entity.ErrorCode, "去重失败", 0
- }
- } else {
- return entity.ErrorCode, "去重失败", 0
- }
- }
- //查询结存是否够用
- type SumStruct struct {
- Age int `xorm:"age"`
- }
- sumStruct := "0"
- now1 := time.Now()
- currentYear, currentMonth, _ := now1.Date()
- currentLocation := now1.Location()
- firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, currentLocation)
- lastOfMonth := firstOfMonth.AddDate(0, 1, -1)
- endTime := lastOfMonth.Format("2006-01-02")
- starteTime := lastOfMonth.Format("2006-01-02")
- nowTime := now1.Format("2006-01-02")
- if producMap[balanceData.ResourceType] != nil {
- if balanceData.ResourceType == "附件下载包" {
- _, err = orm.Table(AccountResources).
- Select("sum(number) as number").
- Where("accountId=? and companyId=? and departmentId=? and ResourceType=? "+
- "and (( endTime>= ? and endTime<=? and vipTime>? )or (endTime>= ? and endTime<=? and (vipTime = '' or vipTime is NULL ) )) ",
- balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, starteTime, endTime, nowTime, starteTime, endTime).
- Get(&sumStruct)
- } else {
- _, err = orm.Table(AccountResources).
- Select("sum(number) as number").
- Where("accountId=? and companyId=? and departmentId=? and ResourceType=? and endTime=? and vipTime>?", balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, endTime, nowTime).
- Get(&sumStruct)
- }
- } else {
- _, err = orm.Table(AccountResources).
- Select("sum(number) as number").
- Where("accountId=? and companyId=? and departmentId=? and ResourceType=? and endTime>=?", balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, time.Now().Format("2006-01-02")).
- Get(&sumStruct)
- }
- if err != nil {
- fmt.Println("结存查询失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "结存查询失败", 0
- }
- surplusNumb, err := strconv.ParseInt(sumStruct, 10, 64)
- if surplusNumb < deductionNumb {
- return entity.ErrorCode, "结存不足,请立即充值", 0
- }
- //新增流水记录
- detailed := entity.Detailed{
- AccountId: detailedData.AccountId,
- CompanyId: detailedData.CompanyId,
- DepartmentId: detailedData.DepartmentId,
- ResourceType: detailedData.ResourceType,
- Number: detailedData.Number,
- RuleId: detailedData.RuleId,
- CreateTime: time.Now().Local(),
- UserType: 0,
- UserId: detailedData.UserId,
- Remarks: detailedData.Remarks,
- DeductionNumb: deductionNumb,
- Name: detailedData.Name,
- }
- insertNumb, err := orm.Table(ConsumeRecord).Insert(&detailed)
- if err != nil || insertNumb <= 0 {
- fmt.Println("新增流水失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "新增流水失败", 0
- }
- if deductionNumb == 0 {
- orm.Commit()
- return entity.SuccessCode, "修改结存成功", deductionNumb
- }
- //修改结存
- balanceList := []entity.Balance{}
- if producMap[balanceData.ResourceType] != nil {
- if balanceData.ResourceType == "附件下载包" {
- err = orm.Table(AccountResources).
- Select("*").
- Where("accountId=? and companyId=? and departmentId=? and number>0 and ResourceType=?"+
- " and (( endTime>= ? and endTime<=? and vipTime>=? )or (endTime>= ? and (vipTime='' or vipTime is NULL ) )) ",
- balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, starteTime, endTime, nowTime, nowTime).
- OrderBy("endTime").
- Find(&balanceList)
- } else {
- err = orm.Table(AccountResources).
- Select("*").
- Where("accountId=? and companyId=? and departmentId=? and number>0 and ResourceType=? and endTime=? and vipTime>? ", balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, endTime, nowTime).
- OrderBy("endTime").
- Find(&balanceList)
- }
- } else {
- err = orm.Table(AccountResources).
- Select("*").
- Where("accountId=? and companyId=? and departmentId=? and number>0 and ResourceType=? and endTime>=? ", balanceData.AccountId, balanceData.CompanyId, balanceData.DepartmentId, balanceData.ResourceType, time.Now().Format("2006-01-02")).
- OrderBy("endTime").
- Find(&balanceList)
- }
- if err != nil {
- fmt.Println("结存查询失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "企业下的组织查询失败", 0
- }
- for _, value := range balanceList {
- if value.Number > deductionNumb {
- value.Number = value.Number - deductionNumb
- deductionNumb = 0
- } else {
- deductionNumb = deductionNumb - value.Number
- value.Number = 0
- }
- updateNumb, err := orm.Table(AccountResources).
- Cols("number").ID(value.Id).
- Update(&value)
- if err != nil || updateNumb <= 0 {
- fmt.Println("结存修改失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "结存修改失败", 0
- }
- if deductionNumb == 0 {
- break
- }
- }
- orm.Commit()
- return entity.SuccessCode, "使用结存成功", deductionNumbs
- }
- // 去重查询
- func (service *BalanceService) FindPreview(in *resourcesCenter.PreviewReq, url string) (int64, string, int64, int64) {
- orm := entity.Engine
- balance := []entity.AccountBalance{}
- //先查询余额
- dataDesc := 0
- if in.ResourceType == "标准字段包" {
- dataDesc = 2
- } else if in.ResourceType == "高级字段包" {
- dataDesc = 1
- }
- err := orm.Table("account_resources").Select("number").
- Where("accountId = ? and resourceType = ?", in.AccountId, in.ResourceType).Find(&balance)
- if err != nil {
- return entity.ErrorCode, "查询余额失败", 0, 0
- }
- var appheader = "application/x-www-form-urlencoded"
- param := "dataDesc=" + fmt.Sprint(dataDesc) + "&personId=" + in.AccountId + "&infoId=" + in.InfoId + "&accountId=" + in.AccountId
- resp, status, _ := HttpPost_M(url+"/data/dedupByAcount/"+fmt.Sprint(time.Now().Unix()), appheader, param, 20)
- log.Println(resp, status)
- if status != 200 && (resp == nil || len(resp) <= 0) {
- return entity.ErrorCode, "请求去重接口出错", 0, 0
- }
- data := resp["data"].(map[string]interface{})
- repeatNumb := data["existCount"].(float64)
- deductionNumb := data["newCount"].(float64)
- log.Println(repeatNumb, deductionNumb)
- return entity.SuccessCode, "去重", int64(repeatNumb), int64(deductionNumb)
- }
- func HttpPost_M(href, contentType, param string, timeout int) (map[string]interface{}, int, int64) {
- t1 := time.Now().UnixNano()
- client := &http.Client{}
- client.Timeout = time.Duration(timeout) * time.Second
- req, _ := http.NewRequest("POST", href, bytes.NewReader([]byte(param)))
- req.Header.Set("Content-Type", contentType)
- resp, err := client.Do(req)
- if err != nil {
- log.Println("post_M err1:", err)
- return nil, -1, 0
- }
- defer resp.Body.Close()
- bs, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- log.Println("post_M err2:", err)
- return nil, -2, 0
- }
- var resData = map[string]interface{}{}
- json.Unmarshal(bs, &resData)
- t2 := time.Now().UnixNano()
- return resData, resp.StatusCode, t2 - t1
- }
- // 账号合并
- func (service *BalanceService) UserMerge(mergeUser, mergedUser, appId string, producMap map[string]interface{}) (int64, string) {
- orm := entity.Engine.NewSession()
- err := orm.Begin()
- if err != nil {
- return entity.ErrorCode, "账号合并失败"
- }
- //查询有效的资源量
- balanceList := []entity.Balance{}
- err = orm.Table(AccountResources).
- Select("*").
- Where("accountId=? and number >0 and endTime>=? ", mergedUser, time.Now().Format("2006-01-02")).
- OrderBy("endTime").
- Find(&balanceList)
- //计算总量
- for _, value := range balanceList {
- //流水操作
- //被合并用户流水
- mergedDetailed := entity.Detailed{
- AccountId: mergedUser,
- CompanyId: int64(0),
- DepartmentId: int64(0),
- ResourceType: value.ResourceType + "(合并)",
- Number: value.Number,
- RuleId: "",
- CreateTime: time.Now().Local(),
- UserType: 0,
- UserId: mergeUser,
- Remarks: "",
- DeductionNumb: int64(0),
- Name: value.Name + "(合并)",
- }
- insertNumb, err := orm.Table(ConsumeRecord).Insert(&mergedDetailed)
- if err != nil || insertNumb <= 0 {
- fmt.Println("新增流水失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "新增流水失败"
- }
- //合并用户流水
- pType := 0
- if value.ResourceType == "标准字段包" {
- pType = 1
- } else if value.ResourceType == "高级字段包" {
- pType = 2
- }
- times, _ := time.Parse("2006-01-02 15:04:05", value.EndTime+" 23:59:59")
- timeUnix := times.Unix()
- filter_map := map[string]interface{}{
- "pType": pType,
- "pNum": value.Number,
- "validYear": -1,
- "price": -1,
- "endTime": timeUnix,
- }
- filter, _ := json.Marshal(filter_map)
- mergeDetailed := entity.Detailed{
- AccountId: mergeUser,
- CompanyId: int64(0),
- DepartmentId: int64(0),
- ResourceType: value.ResourceType + "(合并)",
- Number: value.Number,
- RuleId: "",
- CreateTime: time.Now().Local(),
- UserType: 1,
- UserId: mergeUser,
- Remarks: string(filter),
- DeductionNumb: int64(0),
- Name: value.Name + "(合并)",
- }
- insertNumb, err = orm.Table(ConsumeRecord).Insert(&mergeDetailed)
- if err != nil || insertNumb <= 0 {
- fmt.Println("新增流水失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "新增流水失败"
- }
- //结存操作
- balance := entity.Balance{}
- _, err = orm.Table(AccountResources).
- Select("*").
- Where("accountId=? and resourceType=? endTime=? and vipTime=?", mergeUser, value.ResourceType, value.EndTime, value.VipTime).
- OrderBy("endTime").
- Get(&balance)
- if balance.Id != 0 {
- //增加结存数量
- balance.Number += value.Number
- updateNumb, err := orm.Table(AccountResources).
- Cols("number").ID(balance.Id).
- Update(&balance)
- if err != nil || updateNumb <= 0 {
- fmt.Println("结存修改失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "结存修改失败"
- }
- //增加用户资源量
- //查看是否有结止时间为endTime的数据
- } else {
- //新增结存信息
- mergeBalance := entity.Balance{
- AccountId: mergeUser,
- CompanyId: 0,
- DepartmentId: 0,
- Name: value.Name,
- ResourceType: value.ResourceType,
- Number: value.Number,
- Spec: value.Spec,
- AppId: value.AppId,
- EndTime: value.EndTime,
- VipTime: value.VipTime,
- }
- insertNumb, err := orm.Table(AccountResources).Insert(&mergeBalance)
- if err != nil || insertNumb <= 0 {
- fmt.Println("结存新增失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "结存新增失败"
- }
- }
- value.Number = 0
- updateNumb, err := orm.Table(AccountResources).
- Cols("number").ID(value.Id).
- Update(&value)
- if err != nil || updateNumb <= 0 {
- fmt.Println("结存修改失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "结存修改失败"
- }
- }
- orm.Commit()
- return entity.SuccessCode, "合并成功"
- }
- // 超级订阅时间修改
- func (service *BalanceService) UpdateVipTime(data *resourcesCenter.VipReq, productValue string) (int64, string) {
- orm := entity.Engine.NewSession()
- err := orm.Begin()
- defer orm.Close()
- updateNumb := int64(0)
- now1 := time.Now()
- currentYear, currentMonth, _ := now1.Date()
- currentLocation := now1.Location()
- firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, currentLocation)
- lastOfMonth := firstOfMonth.AddDate(0, 1, -1)
- endTime := lastOfMonth.Format("2006-01-02")
- dataMap := map[string]interface{}{
- "vipTime": data.VipTime,
- }
- resourceTypeStr := `FIND_IN_SET(resourceType,%s)`
- resourceTypeStr = fmt.Sprintf(` FIND_IN_SET(resourceType,"%s")`, productValue)
- updateNumb, err = orm.Table(AccountResources).
- Cols("vipTime").Where("endTime = ? and accountId=? and sourceType in(1,3) and "+resourceTypeStr, endTime, data.AccountId).
- Update(&dataMap)
- if err != nil || updateNumb < 0 {
- fmt.Println("结存修改失败:", err)
- orm.Rollback()
- return entity.ErrorCode, "超级订阅时间修改失败"
- }
- orm.Commit()
- return entity.SuccessCode, "超级订阅时间修改成功"
- }
- func (service *BalanceService) ExpireHandle() {
- orm := entity.Engine.NewSession()
- endTime := time.Now().Format("2006-01-02")
- expireList := []map[string]interface{}{}
- endTime = "2023-10-21"
- orm.Table(AccountResources).Where("resourceType=? and (endTime=? or vipTime=?) and number >0 ", "附件下载包", endTime, endTime).Find(&expireList)
- for _, m := range expireList {
- //流水生成
- sourceType := gconv.Int64(m["sourceType"])
- accountId := gconv.String(m["accountId"])
- number := gconv.Int64(m["number"])
- resourcesId := gconv.Int64(m["id"])
- userType := int64(1)
- remarks := ""
- remarksMap := map[string]interface{}{}
- switch sourceType {
- case 1:
- remarksMap["describe"] = "购买附件下载包权益未使用失效。"
- case 2:
- userType = 2
- remarksMap["describe"] = "剑鱼币兑换权益未使用失效。"
- case 3:
- userType = 3
- remarksMap["describe"] = fmt.Sprintf("超级订阅%s附件下载权益未使用失效。", time.Now().Format("2006年01"))
- }
- jsonData, err := json.Marshal(remarksMap)
- if err != nil {
- fmt.Println(err)
- }
- remarks = string(jsonData)
- detailed := entity.Detailed{
- AccountId: accountId,
- ResourceType: "附件下载包",
- Number: number,
- Name: "附件下载包",
- CreateTime: time.Now().Local(),
- Remarks: remarks,
- UserType: userType,
- }
- orm.Table(ConsumeRecord).Insert(&detailed)
- //jie结存清空
- updataMap := map[string]interface{}{
- "number": 0,
- }
- orm.Table(AccountResources).
- Cols("number").Where("id =? ", resourcesId).
- Update(&updataMap)
- }
- }
|