Jelajahi Sumber

社区图谱

huangchundi 1 hari lalu
induk
melakukan
14cb05049e

+ 176 - 4
controllers/api/CommunityListController.go

@@ -1,9 +1,16 @@
 package api
 
 import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"net/url"
 	"strconv"
 	"think-go/controllers/services"
 	"think-go/utils"
+	"time"
 
 	beego "github.com/beego/beego/v2/server/web"
 )
@@ -15,6 +22,171 @@ type CommunityListController struct {
 var communityListService = &services.CommunityListService{}
 
 // GetCommunityList 获取社区列表信息
+
+type ExternalCommunityResponse struct {
+	Code int `json:"code"`
+	Data struct {
+		InviteAmount int `json:"invite_amount"`
+		List         []struct {
+			CTime          int64  `json:"c_time"`
+			UserID         string `json:"userid"`
+			Username       string `json:"username"`
+			PromoteName    string `json:"promote_name"`
+			Sales          string `json:"sales"`
+			TeamSales      string `json:"team_sales"`
+			TodayTeamSales string `json:"today_team_sales"`
+			UserBV         string `json:"user_bv"`
+			SubStatus      int    `json:"sub_status"`
+		} `json:"list"`
+		Count int `json:"count"`
+	} `json:"data"`
+}
+
+// 假设路由为 /invite/list [post]
+func (c *CommunityListController) GetExternalCommunityList() {
+	// 1. 获取当前请求中的参数(可以根据业务从 c 中获取,例如 c.GetInt 等)
+	limit, _ := c.GetInt("limit", 100) // 默认每页10条
+	page, _ := c.GetInt("page", 1)     // 默认第一页
+	userid := c.GetString("userid")    // 假设从当前请求传入
+
+	// 2. 准备外部接口的请求参数(x-www-form-urlencoded)
+	data := url.Values{}
+	data.Set("limit", strconv.Itoa(limit))
+	data.Set("page", strconv.Itoa(page))
+	data.Set("userid", userid)
+
+	// 3. 构造 HTTP 请求
+	externalURL := "https://app-api.aiceanglobal1.com/api/v1/reward/inviteList" // 替换为真实地址
+	req, err := http.NewRequest("POST", externalURL, bytes.NewBufferString(data.Encode()))
+	if err != nil {
+		c.Data["json"] = map[string]interface{}{"code": 500, "msg": "请求构造失败"}
+		c.ServeJSON()
+		return
+	}
+
+	// 4. 设置 Headers
+	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	// 假设 Authorization 是 Bearer token,从配置或环境变量获取
+	req.Header.Set("Authorization", "Bearer 9409e48b4f3cfabc4d44b88db19516ca")
+	// 外部接口需要的 userid header(可能和 body 中的 userid 不同,按需设置)
+	req.Header.Set("userid", "04a0d628189644a1b918f14cde664610")
+
+	// 5. 发送请求
+	client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+		c.Data["json"] = map[string]interface{}{"code": 500, "msg": "请求外部接口失败"}
+		c.ServeJSON()
+		fmt.Println("errrr:", err)
+		return
+	}
+	defer resp.Body.Close()
+
+	// 6. 读取响应体
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		c.Data["json"] = map[string]interface{}{"code": 500, "msg": "读取响应失败"}
+		c.ServeJSON()
+		return
+	}
+
+	// 7. 解析 JSON
+	var externalResp ExternalCommunityResponse
+	if err := json.Unmarshal(body, &externalResp); err != nil {
+		c.Data["json"] = map[string]interface{}{"code": 500, "msg": "解析响应失败"}
+		c.ServeJSON()
+		return
+	}
+
+	// 遍历列表
+	for _, item := range externalResp.Data.List {
+		fmt.Printf("用户: %s, 用户名: %s, 销售额: %s\n",
+			item.UserID, item.Username, item.Sales)
+
+		// 取 count
+		info := &services.CommunityInfo{
+			ParentId:       userid,
+			UserId:         item.UserID,
+			Username:       item.Username,
+			PromoteName:    item.PromoteName,
+			Sales:          item.Sales,
+			TeamSales:      item.TeamSales,
+			TodayTeamSales: item.TodayTeamSales,
+			UserBv:         item.UserBV,
+			SubStatus:      strconv.Itoa(item.SubStatus),
+			CTime:          item.CTime,
+			IsYes:          0,
+		}
+
+		err := communityListService.CreateCommunityList(info)
+		if err != nil {
+			utils.JSON(&c.Controller, 500, err.Error(), nil)
+			return
+		}
+	}
+
+	// 8. 根据业务需要处理外部接口返回的数据,例如转换格式、添加额外字段等
+	// 这里直接透传给客户端,也可以重新封装
+	c.Data["json"] = externalResp
+	c.ServeJSON()
+}
+
+func (c *CommunityListController) GetExternalCommunityList002() {
+	// 外部循环 50 次
+	for i := 0; i < 100; i++ {
+		// 1. 查询数据库中待处理的用户
+		records, err := communityListService.GetCommunityListByIsYes()
+		if err != nil {
+			utils.JSON(&c.Controller, 500, "查询失败: "+err.Error(), nil)
+			return
+		}
+
+		// 如果本次查询没有数据,说明处理完了,直接跳出大循环
+		if len(records) == 0 {
+			break
+		}
+
+		// 2. 遍历用户
+		for _, record := range records {
+			// 注意:因为报错提示 mismatched types,说明 record 是值类型而非指针
+			// 所以这里不需要 if record == nil 的判断,直接使用即可
+
+			info := &services.CommunityInfo{
+				CommunityId:    record.CommunityId,
+				ParentId:       record.ParentId,
+				UserId:         record.UserId,
+				Username:       record.Username,
+				PromoteName:    record.PromoteName,
+				Sales:          record.Sales,
+				TeamSales:      record.TeamSales,
+				TodayTeamSales: record.TodayTeamSales,
+				UserBv:         record.UserBv,
+				SubStatus:      record.SubStatus,
+				CTime:          record.CTime,
+				IsYes:          1, // 标记为已处理
+			}
+
+			// 按照业务需求延迟 5 秒
+			time.Sleep(5 * time.Second)
+			fmt.Println("正在处理用户ID:", info.UserId)
+
+			// 3. 请求外部接口并存入数据库
+			communityListService.GoRequestNetCommunityInfo(info.UserId)
+
+			// 4. 修改当前用户状态
+			err = communityListService.UpdateCommunityList(info)
+			if err != nil {
+				utils.JSON(&c.Controller, 500, "更新状态失败: "+err.Error(), nil)
+				return
+			}
+		}
+	}
+
+	// 5. 循环全部结束后,正常返回成功
+	// 此时 err 为空,所以不能调用 err.Error()
+	utils.JSON(&c.Controller, 200, "处理完成", nil)
+}
+
 // @router /api/community/list [get]
 func (c *CommunityListController) GetCommunityList() {
 	// 获取参数
@@ -109,9 +281,9 @@ func (c *CommunityListController) CreateCommunityList() {
 // UpdateCommunityList 更新社区列表记录
 // @router /api/community/update [post]
 func (c *CommunityListController) UpdateCommunityList() {
-	idStr, _ := utils.GetRequestString(&c.Controller, "id")
-	id, err := strconv.Atoi(idStr)
-	if err != nil || id <= 0 {
+	idStr, _ := utils.GetRequestString(&c.Controller, "community_id")
+	communityId, err := strconv.Atoi(idStr)
+	if err != nil || communityId <= 0 {
 		utils.JSON(&c.Controller, 400, "invalid or missing id parameter", nil)
 		return
 	}
@@ -143,7 +315,7 @@ func (c *CommunityListController) UpdateCommunityList() {
 	}
 
 	info := &services.CommunityInfo{
-		Id:             id,
+		CommunityId:    communityId,
 		ParentId:       parentId,
 		UserId:         userId,
 		Username:       username,

+ 146 - 5
controllers/services/CommunityListService.go

@@ -1,7 +1,14 @@
 package services
 
 import (
+	"bytes"
+	"encoding/json"
 	"errors"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"net/url"
+	"strconv"
 	"think-go/models"
 
 	"github.com/beego/beego/v2/client/orm"
@@ -11,7 +18,7 @@ type CommunityListService struct{}
 
 // CommunityInfo represents community list information
 type CommunityInfo struct {
-	Id             int    `json:"id"`
+	CommunityId    int    `json:"community_id"`
 	ParentId       string `json:"parent_id"`
 	UserId         string `json:"user_id"`
 	Username       string `json:"username"`
@@ -42,6 +49,25 @@ func (s *CommunityListService) GetCommunityList(id int) (*CommunityInfo, error)
 	return s.toCommunityInfo(record), nil
 }
 
+type ExternalCommunityResponse struct {
+	Code int `json:"code"`
+	Data struct {
+		InviteAmount int `json:"invite_amount"`
+		List         []struct {
+			CTime          int64  `json:"c_time"`
+			UserID         string `json:"userid"`
+			Username       string `json:"username"`
+			PromoteName    string `json:"promote_name"`
+			Sales          string `json:"sales"`
+			TeamSales      string `json:"team_sales"`
+			TodayTeamSales string `json:"today_team_sales"`
+			UserBV         string `json:"user_bv"`
+			SubStatus      int    `json:"sub_status"`
+		} `json:"list"`
+		Count int `json:"count"`
+	} `json:"data"`
+}
+
 // GetCommunityListByUserId retrieves community list by user_id
 func (s *CommunityListService) GetCommunityListByUserId(userId string) (*CommunityInfo, error) {
 	if userId == "" {
@@ -60,6 +86,121 @@ func (s *CommunityListService) GetCommunityListByUserId(userId string) (*Communi
 
 	return s.toCommunityInfo(record), nil
 }
+func (s *CommunityListService) GoRequestNetCommunityInfo(userId string) {
+	svc := &CommunityListService{}
+	// 2. 准备外部接口的请求参数(x-www-form-urlencoded)
+	data := url.Values{}
+	data.Set("limit", strconv.Itoa(1000))
+	data.Set("page", strconv.Itoa(1))
+	data.Set("userid", userId)
+
+	// 3. 构造 HTTP 请求
+	externalURL := "https://app-api.aiceanglobal1.com/api/v1/reward/inviteList" // 替换为真实地址
+	req, err := http.NewRequest("POST", externalURL, bytes.NewBufferString(data.Encode()))
+	if err != nil {
+
+		return
+	}
+
+	// 4. 设置 Headers
+	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	// 假设 Authorization 是 Bearer token,从配置或环境变量获取
+	req.Header.Set("Authorization", "Bearer 9409e48b4f3cfabc4d44b88db19516ca")
+	// 外部接口需要的 userid header(可能和 body 中的 userid 不同,按需设置)
+	req.Header.Set("userid", "04a0d628189644a1b918f14cde664610")
+
+	// 5. 发送请求
+	client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+
+		fmt.Println("errrr:", err)
+		return
+	}
+	defer resp.Body.Close()
+
+	// 6. 读取响应体
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+
+		return
+	}
+
+	// 7. 解析 JSON
+	var externalResp ExternalCommunityResponse
+	if err := json.Unmarshal(body, &externalResp); err != nil {
+
+		return
+	}
+
+	// 遍历列表
+	for _, item := range externalResp.Data.List {
+		// 取 count
+		info := &CommunityInfo{
+			ParentId:       userId,
+			UserId:         item.UserID,
+			Username:       item.Username,
+			PromoteName:    item.PromoteName,
+			Sales:          item.Sales,
+			TeamSales:      item.TeamSales,
+			TodayTeamSales: item.TodayTeamSales,
+			UserBv:         item.UserBV,
+			SubStatus:      strconv.Itoa(item.SubStatus),
+			CTime:          item.CTime,
+			IsYes:          0,
+		}
+
+		err := svc.CreateCommunityList(info)
+		if err != nil {
+			return
+		}
+	}
+
+}
+func (s *CommunityListService) GetCommunityListByIsYes() ([]CommunityInfo, error) {
+
+	query := make(map[string]string)
+	query["is_yes"] = strconv.Itoa(0)
+	fields := []string{"CommunityId", "ParentId", "UserId", "Username", "PromoteName", "Sales", "TeamSales", "TodayTeamSales", "UserBv", "SubStatus", "CTime", "IsYes"}
+	sortby := []string{"CommunityId"}
+	order := []string{"desc"}
+
+	ml, err := models.GetAllCommunityList(query, fields, sortby, order, 0, 100)
+	if err != nil {
+		return nil, err
+	}
+
+	//fmt.Printf("ml------:", ml)
+	result := make([]CommunityInfo, 0, len(ml))
+
+	for _, item := range ml {
+		// 断言 item 是 map[string]interface{}
+		m, ok := item.(map[string]interface{})
+		if !ok {
+			// 类型不匹配,跳过或记录错误
+			continue
+		}
+
+		// 从 map 中安全提取字段(注意字段名与 JSON 标签一致)
+		info := CommunityInfo{
+			CommunityId:    getInt(m, "CommunityId"), // 根据实际字段名调整
+			ParentId:       getString(m, "ParentId"),
+			UserId:         getString(m, "UserId"),
+			Username:       getString(m, "Username"),
+			PromoteName:    getString(m, "PromoteName"),
+			Sales:          getString(m, "Sales"),
+			TeamSales:      getString(m, "TeamSales"),
+			TodayTeamSales: getString(m, "TodayTeamSales"),
+			UserBv:         getString(m, "UserBv"),
+			SubStatus:      getString(m, "SubStatus"),
+			CTime:          getInt64(m, "CTime"),
+			IsYes:          getInt(m, "IsYes"),
+		}
+		result = append(result, info)
+	}
+
+	return result, err
+}
 
 // CreateCommunityList creates a new community list record
 func (s *CommunityListService) CreateCommunityList(info *CommunityInfo) error {
@@ -95,11 +236,11 @@ func (s *CommunityListService) CreateCommunityList(info *CommunityInfo) error {
 
 // UpdateCommunityList updates an existing community list record
 func (s *CommunityListService) UpdateCommunityList(info *CommunityInfo) error {
-	if info.Id <= 0 {
+	if info.CommunityId <= 0 {
 		return errors.New("invalid id")
 	}
 
-	record, err := models.GetCommunityListById(info.Id)
+	record, err := models.GetCommunityListById(info.CommunityId)
 	if err != nil {
 		if err == orm.ErrNoRows {
 			return errors.New("community list record not found")
@@ -139,7 +280,7 @@ func (s *CommunityListService) GetAllCommunityLists(offset, limit int64) ([]Comm
 	for _, item := range ml {
 		if record, ok := item.(models.CommunityList); ok {
 			result = append(result, CommunityInfo{
-				Id:             record.CommunityId,
+				CommunityId:    record.CommunityId,
 				ParentId:       record.ParentId,
 				UserId:         record.UserId,
 				Username:       record.Username,
@@ -185,7 +326,7 @@ func (s *CommunityListService) DeleteCommunityList(id int) error {
 // toCommunityInfo converts model to service info
 func (s *CommunityListService) toCommunityInfo(record *models.CommunityList) *CommunityInfo {
 	return &CommunityInfo{
-		Id:             record.CommunityId,
+		CommunityId:    record.CommunityId,
 		ParentId:       record.ParentId,
 		UserId:         record.UserId,
 		Username:       record.Username,

+ 2 - 0
routers/router.go

@@ -34,6 +34,8 @@ func init() {
 		beego.NSRouter("/community/update", &api.CommunityListController{}, "post:UpdateCommunityList"),
 		beego.NSRouter("/community/listAll", &api.CommunityListController{}, "get:GetAllCommunityLists"),
 		beego.NSRouter("/community/delete", &api.CommunityListController{}, "post:DeleteCommunityList"),
+		beego.NSRouter("/community/getExternalCommunityList", &api.CommunityListController{}, "post:GetExternalCommunityList"),
+		beego.NSRouter("/community/getExternalCommunityList002", &api.CommunityListController{}, "post:GetExternalCommunityList002"),
 	)
 	beego.AddNamespace(nsAdmin)
 	beego.AddNamespace(nsApi)