merchant_product.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package merchant
  2. import (
  3. "errors"
  4. stringUtils "eta/eta_mini_ht_api/common/utils/string"
  5. "eta/eta_mini_ht_api/models"
  6. "fmt"
  7. "sort"
  8. "strings"
  9. "sync/atomic"
  10. "time"
  11. )
  12. type SaleStatus string
  13. type MerchantProductType string
  14. const (
  15. detailColumns = "id,source_id,title,cover_src,cover_url,description,price,type,is_permanent,valid_days,sale_status,created_time,updated_time"
  16. detailColumnsWithRisk = "id,source_id,title,cover_src,cover_url,description,price,type,is_permanent,valid_days,sale_status,created_time,updated_time,permissions.risk_level as risk_level"
  17. sourceIdColumn = "id,source_id"
  18. )
  19. const (
  20. OnSale SaleStatus = "on_sale" //上架
  21. OffSale SaleStatus = "off_sale" //下架
  22. Package MerchantProductType = "package"
  23. Report MerchantProductType = "report"
  24. Video MerchantProductType = "video"
  25. Audio MerchantProductType = "audio"
  26. )
  27. // MerchantProduct 商户产品信息结构体
  28. type MerchantProduct struct {
  29. Id int `gorm:"column:id;primary_key;autoIncrement;comment:主键"`
  30. SourceId int `gorm:"column:source_id;type:int(11);comment:单品或者套餐对应的主键"`
  31. Title string `gorm:"column:title;type:varchar(255);comment:标题"`
  32. CoverSrc int `gorm:"column:cover_src;type:int(11);comment:封面图片资源库id"`
  33. CoverUrl string `gorm:"column:cover_url;type:varchar(255);comment:封面图片url"`
  34. Description string `gorm:"column:description;type:varchar(255);comment:描述"`
  35. Price string `gorm:"column:price;type:decimal(10,2);comment:价格"`
  36. RiskLevel string `gorm:"column:risk_level;type:varchar(100);comment:风险等级"`
  37. Type MerchantProductType `gorm:"column:type;type:enum('report','video','audio','package');not null;comment:类型"`
  38. IsPermanent bool `gorm:"column:is_permanent;type:int(1);not null;default:0;comment:是否永久"`
  39. ValidDays int `gorm:"column:valid_days;type:int(11);comment:有效期天数"`
  40. SaleStatus SaleStatus `gorm:"column:sale_status;type:enum('on_sale','off_sale');not null;default:'on_sale';comment:上架/下架状态"`
  41. Deleted bool `gorm:"column:deleted;type:tinyint(1);not null;default:0;comment:是否删除"`
  42. CreatedTime time.Time `gorm:"column:created_time;type:datetime;comment:创建时间"`
  43. UpdatedTime time.Time `gorm:"column:updated_time;type:datetime;comment:更新时间;default:CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
  44. }
  45. // TableName 指定表名
  46. func (MerchantProduct) TableName() string {
  47. return "merchant_products"
  48. }
  49. func GetMerchantProductById(id int) (product MerchantProduct, err error) {
  50. db := models.Main()
  51. err = db.Select(detailColumns).Where("id = ? ", id).First(&product).Error
  52. return
  53. }
  54. func GetMerchantProductBySourceId(sourceId int, productType ...MerchantProductType) (product MerchantProduct, err error) {
  55. db := models.Main()
  56. if len(productType) > 0 {
  57. if len(productType) == 1 {
  58. if productType[0] == Package {
  59. err = db.Select(detailColumnsWithRisk).InnerJoins("permissions on permissions.permission_id=source_id")
  60. } else {
  61. err = db.Select(detailColumns).Where("source_id =? and type = ? and deleted =?", sourceId, productType[0], 0).First(&product).Error
  62. }
  63. } else {
  64. err = db.Select(detailColumns).Where("source_id =? and type in (?) and deleted =?", sourceId, productType, 0).First(&product).Error
  65. }
  66. } else {
  67. err = db.Select(detailColumns).Where("source_id =? and deleted =?", sourceId, 0).First(&product).Error
  68. }
  69. return
  70. }
  71. func GetProductListBySourceIds(ids []int, detail bool, productType ...MerchantProductType) (productList []MerchantProduct, err error) {
  72. db := models.Main()
  73. var columns string
  74. if productType == nil {
  75. err = errors.New("productType参数不能为空")
  76. return
  77. }
  78. if detail {
  79. columns = detailColumns
  80. } else {
  81. columns = sourceIdColumn
  82. }
  83. if len(productType) > 0 {
  84. if len(productType) == 1 {
  85. err = db.Select(columns).Where("source_id in ? and type = ? and deleted =? order by created_time desc", ids, productType[0], false).Find(&productList).Error
  86. } else {
  87. err = db.Select(columns).Where("source_id in ? and type in (?) and deleted =? by created_time desc", ids, productType, false).Find(&productList).Error
  88. }
  89. } else {
  90. err = db.Select(columns).Where("source_id in ? and deleted =? by created_time desc", ids, productType, false).Find(&productList).Error
  91. }
  92. return
  93. }
  94. func GetTotalPageCountByProductType(productType MerchantProductType) (total int64, latestId int64) {
  95. db := models.Main()
  96. _ = db.Model(&MerchantProduct{}).Select("count(*)").Where("type=? and deleted =?", productType, false).Scan(&total).Error
  97. _ = db.Model(&MerchantProduct{}).Select("max(id)").Where("type=? and deleted =?", productType, false).Scan(&latestId).Error
  98. return
  99. }
  100. func GetProductPageByProductType(productIds []int, id int64, offset int, limit int) (list []MerchantProduct, err error) {
  101. db := models.Main()
  102. err = db.Select(detailColumns).Where("id <= ? and deleted =? and id in ? order by created_time desc limit ?,? ", id, false, productIds, offset, limit).Find(&list).Error
  103. return
  104. }
  105. func GetProductListByProductType(productType MerchantProductType, detail bool) (list []MerchantProduct, err error) {
  106. db := models.Main()
  107. var columns string
  108. if detail {
  109. columns = detailColumns
  110. } else {
  111. columns = sourceIdColumn
  112. }
  113. if productType == "" {
  114. err = errors.New("productType参数不能为空")
  115. return
  116. }
  117. err = db.Select(columns).Where(" type = ? and deleted =? order by created_time desc", productType, false).Find(&list).Error
  118. return
  119. }
  120. type MerchantProductIdMap struct {
  121. Type string
  122. SourceId string
  123. }
  124. func GetProductByProductType() (productIds map[string]string, err error) {
  125. db := models.Main()
  126. var productIdMap []MerchantProductIdMap
  127. sql := `SELECT type,GROUP_CONCAT(source_id ORDER BY source_id SEPARATOR ',') as source_id FROM merchant_products GROUP BY type`
  128. err = db.Raw(sql).Find(&productIdMap).Error
  129. productIds = make(map[string]string, len(productIdMap))
  130. for _, v := range productIdMap {
  131. productIds[v.Type] = v.SourceId
  132. }
  133. return
  134. }
  135. func generateSignalPdSql(idMap map[string][]int) (condition string) {
  136. for k, v := range idMap {
  137. if condition == "" {
  138. condition = "(" + fmt.Sprintf("(type ='%s' and source_id in (%s))", k, strings.Join(stringUtils.IntToStringSlice(v), ","))
  139. } else {
  140. condition = condition + fmt.Sprintf(" or (type ='%s' and source_id in (%s))", k, strings.Join(stringUtils.IntToStringSlice(v), ","))
  141. }
  142. }
  143. condition = condition + ")"
  144. if len(idMap) == 1 {
  145. condition = condition[1 : len(condition)-1]
  146. }
  147. return
  148. }
  149. func LatestId() (latestId int64) {
  150. db := models.Main()
  151. _ = db.Model(&MerchantProduct{}).Select("max(id)").Where("deleted=?", false).Scan(&latestId).Error
  152. return
  153. }
  154. type ProductDTO struct {
  155. SourceId int
  156. SourceType string
  157. Score float64
  158. }
  159. func ProductListBySort(list []ProductDTO, id int64, offset int, size int) (productList []MerchantProduct, err error) {
  160. var productMap = make(map[string][]int, len(list))
  161. sort.Slice(list, func(i, j int) bool {
  162. return list[i].Score > list[j].Score
  163. })
  164. var idSort []int
  165. for _, v := range list {
  166. idSort = append(idSort, v.SourceId)
  167. }
  168. for _, v := range list {
  169. ids := productMap[v.SourceType]
  170. ids = append(ids, v.SourceId)
  171. productMap[v.SourceType] = ids
  172. }
  173. sql := generateSignalPdSql(productMap)
  174. db := models.Main()
  175. query := fmt.Sprintf("id <= ? and deleted =? and %s order by Field(id,?) desc limit ?,?", sql)
  176. err = db.Select(detailColumns).Where(query, id, false, strings.Join(stringUtils.IntToStringSlice(idSort), ","), offset, size).Find(&productList).Error
  177. return
  178. }
  179. type packageStruct struct {
  180. SourceId int
  181. Weight int32
  182. }
  183. func PackageListBySort(weightMap map[int]*atomic.Int32, id int64, offset int, size int) (productList []MerchantProduct, err error) {
  184. var packageList []packageStruct
  185. for k, v := range weightMap {
  186. packageList = append(packageList, packageStruct{
  187. SourceId: k,
  188. Weight: v.Load(),
  189. })
  190. }
  191. sort.Slice(packageList, func(i, j int) bool {
  192. return packageList[i].Weight > packageList[j].Weight
  193. })
  194. var idSort []int
  195. for _, v := range packageList {
  196. idSort = append(idSort, v.SourceId)
  197. }
  198. db := models.Main()
  199. err = db.Select(detailColumns).Where("id <= ? and type =? and deleted =? and source_id in ? order by Field(id,?) desc limit ?,? ", id, Package, false, idSort, strings.Join(stringUtils.IntToStringSlice(idSort), ","), offset, size).Find(&productList).Error
  200. return
  201. }
  202. func GetOffSaleProducts(query []MerchantProductType) (list []MerchantProduct, err error) {
  203. db := models.Main()
  204. err = db.Select(detailColumns).Where(" deleted =? and type in ? and sale_status = ? ", false, query, OffSale).Find(&list).Error
  205. return
  206. }
  207. func GetReportOnSalePackageIds(ids []int) (sourceIds []int, err error) {
  208. sql := `
  209. SELECT
  210. r.id
  211. FROM
  212. reports r
  213. LEFT JOIN permission_classify_mapping pcm ON r.classify_id = pcm.classify_id
  214. LEFT JOIN merchant_products mp ON mp.source_id = pcm.permission_id
  215. AND mp.type = 'package'
  216. AND mp.sale_status = 'on_sale'
  217. AND mp.deleted = 0
  218. WHERE
  219. mp.id IS NOT NULL and r.id in ?
  220. UNION ALL
  221. SELECT
  222. r.id
  223. FROM
  224. reports r
  225. LEFT JOIN permissions p ON r.plate_name = p.NAME
  226. LEFT JOIN merchant_products mp ON mp.source_id = p.permission_id
  227. AND mp.type = 'package'
  228. AND mp.sale_status = 'on_sale'
  229. AND mp.deleted = 0
  230. WHERE
  231. mp.id IS NOT NULL and r.id in ?`
  232. db := models.Main()
  233. err = db.Raw(sql, ids, ids).Scan(&sourceIds).Error
  234. return
  235. }
  236. func GetMediaOnSalePackageIds(ids []int) (sourceIds []int, err error) {
  237. sql := ` SELECT
  238. distinct mpm.media_id
  239. FROM
  240. media_permission_mappings mpm
  241. LEFT JOIN merchant_products mp ON mp.source_id = mpm.permission_id
  242. AND mp.type = 'package'
  243. AND mp.sale_status = 'on_sale'
  244. and mp.deleted=0
  245. WHERE
  246. mpm.deleted=0 and mp.id is not null and mpm.media_id in ?`
  247. db := models.Main()
  248. err = db.Raw(sql, ids).Scan(&sourceIds).Error
  249. return
  250. }
  251. func GetOnSaleReportIds(ids []int) (sourceIds []int, err error) {
  252. sql := `SELECT
  253. r.id
  254. FROM
  255. reports r
  256. LEFT JOIN merchant_products mp ON mp.source_id = r.id
  257. AND mp.type = 'report'
  258. AND mp.sale_status = 'on_sale'
  259. AND mp.deleted = 0
  260. WHERE
  261. mp.id IS NOT NULL and r.id in ?`
  262. db := models.Main()
  263. err = db.Raw(sql, ids).Scan(&sourceIds).Error
  264. return
  265. }
  266. func GetOnSaleMediaIds(ids []int, productType MerchantProductType) (sourceIds []int, err error) {
  267. sql := `SELECT
  268. distinct mpm.media_id
  269. FROM
  270. media_permission_mappings mpm
  271. LEFT JOIN merchant_products mp ON mp.source_id = mpm.media_id
  272. AND mp.type = ?
  273. AND mp.sale_status = 'on_sale'
  274. AND mp.deleted = 0
  275. WHERE
  276. mpm.deleted=0 and mp.id is not null and mpm.media_id in ?`
  277. db := models.Main()
  278. err = db.Raw(sql, productType, ids).Scan(&sourceIds).Error
  279. return
  280. }