sign_up.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package upcrm
  2. import (
  3. "time"
  4. "go-common/app/admin/main/up/util/now"
  5. "go-common/app/job/main/up/model/signmodel"
  6. "go-common/app/job/main/up/model/upcrmmodel"
  7. "go-common/library/log"
  8. xtime "go-common/library/time"
  9. "github.com/jinzhu/gorm"
  10. )
  11. const (
  12. //PayStateUnpay not pay
  13. PayStateUnpay = 0
  14. //PayStatePayed payed
  15. PayStatePayed = 1
  16. )
  17. // var days
  18. var (
  19. Day = time.Hour * 24
  20. Day3 = Day * 3
  21. Week = Day * 7
  22. Week3 = Week * 3
  23. )
  24. // GetTaskDuration this will return task duration, [startDate, endDate)
  25. func GetTaskDuration(date time.Time, taskType int8) (startDate, endDate time.Time) {
  26. var ndate = now.New(date)
  27. now.WeekStartDay = time.Monday
  28. switch taskType {
  29. case signmodel.TaskTypeDay:
  30. var begin = ndate.BeginningOfDay()
  31. return begin, begin.AddDate(0, 0, 1)
  32. case signmodel.TaskTypeWeek:
  33. var begin = ndate.BeginningOfWeek()
  34. return begin, begin.AddDate(0, 0, 7)
  35. case signmodel.TaskTypeMonth:
  36. var begin = ndate.BeginningOfMonth()
  37. return begin, begin.AddDate(0, 1, 0)
  38. case signmodel.TaskTypeQuarter:
  39. var begin = ndate.BeginningOfQuarter()
  40. return begin, begin.AddDate(0, 3, 0)
  41. }
  42. return
  43. }
  44. // GetTaskExpireLimit this will return generate date range that needs to send email
  45. func GetTaskExpireLimit(today time.Time, taskType int8) (minDate, maxDate time.Time) {
  46. // 0<=(endDate-today)<= limit
  47. // 0<=(generateDate + duration - today) <= limit
  48. // today-duration <= generateDate <= today - duration + limit
  49. // duration = endDate - startDate
  50. switch taskType {
  51. case signmodel.TaskTypeDay:
  52. var tmp = today.AddDate(0, 0, -1)
  53. return tmp, tmp.Add(Day)
  54. case signmodel.TaskTypeWeek:
  55. var tmp = today.AddDate(0, 0, -7)
  56. return tmp, tmp.Add(Day3)
  57. case signmodel.TaskTypeMonth:
  58. var tmp = today.AddDate(0, -1, 0)
  59. return tmp, tmp.Add(Week)
  60. case signmodel.TaskTypeQuarter:
  61. var tmp = today.AddDate(0, -3, 0)
  62. return tmp, tmp.Add(Week3)
  63. }
  64. return
  65. }
  66. //InsertSignUp insert sign up
  67. // up : sign up
  68. func (d *Dao) InsertSignUp(up *signmodel.SignUp) (affectedRow int64, err error) {
  69. var db = d.crmdb.Save(up)
  70. err = db.Error
  71. affectedRow = db.RowsAffected
  72. return
  73. }
  74. //InsertPayInfo inert pay
  75. func (d *Dao) InsertPayInfo(info *signmodel.SignPay) (affectedRow int64, err error) {
  76. var db = d.crmdb.Save(info)
  77. err = db.Error
  78. affectedRow = db.RowsAffected
  79. return
  80. }
  81. //InsertTaskInfo insert task
  82. func (d *Dao) InsertTaskInfo(info *signmodel.SignTask) (affectedRow int64, err error) {
  83. var db = d.crmdb.Save(info)
  84. err = db.Error
  85. affectedRow = db.RowsAffected
  86. return
  87. }
  88. //InsertContractInfo insert contract
  89. func (d *Dao) InsertContractInfo(info interface{}) (affectedRow int64, err error) {
  90. var db = d.crmdb.Save(info)
  91. err = db.Error
  92. affectedRow = db.RowsAffected
  93. return
  94. }
  95. //GetSignUpByID signid 可以是nil,如果是nil,则会取所有的信息
  96. // query, args, 额外的查询条件
  97. func (d *Dao) GetSignUpByID(signID []uint32, order string, offset int, limit int, query interface{}, args ...interface{}) (result []signmodel.SignUp, err error) {
  98. var db = d.crmdb.Table("sign_up")
  99. if signID != nil {
  100. db = db.Where("id in (?)", signID)
  101. }
  102. if query != nil {
  103. db = db.Where(query, args)
  104. }
  105. if order != "" {
  106. db = db.Order(order)
  107. }
  108. err = db.
  109. Offset(offset).
  110. Limit(limit).
  111. Find(&result).Error
  112. if err == gorm.ErrRecordNotFound {
  113. err = nil
  114. }
  115. return
  116. }
  117. //GetSignUpCount get sign up's count
  118. func (d *Dao) GetSignUpCount(query string, args ...interface{}) (count int) {
  119. d.crmdb.Table(signmodel.TableNameSignUp).Where(query, args).Count(&count)
  120. return
  121. }
  122. //GetTask get task by sign id and state
  123. func (d *Dao) GetTask(signID []uint32, state ...int) (result []signmodel.SignTask, err error) {
  124. err = d.crmdb.Table(signmodel.TableNameSignTask).Where("sign_id in (?) and state = ?", signID, state).Find(&result).Error
  125. if err == gorm.ErrRecordNotFound {
  126. err = nil
  127. }
  128. return
  129. }
  130. //GetPay get get sign id
  131. func (d *Dao) GetPay(signID []uint32) (result []signmodel.SignPay, err error) {
  132. err = d.crmdb.Table(signmodel.TableNameSignPay).Where("sign_id in (?)", signID).Find(&result).Error
  133. if err == gorm.ErrRecordNotFound {
  134. err = nil
  135. }
  136. return
  137. }
  138. //GetContract get get sign id
  139. func (d *Dao) GetContract(signID []uint32) (result []signmodel.SignContract, err error) {
  140. err = d.crmdb.Table(signmodel.TableNameSignContract).Where("sign_id in (?)", signID).Find(&result).Error
  141. if err == gorm.ErrRecordNotFound {
  142. err = nil
  143. }
  144. return
  145. }
  146. //PayComplete finish pay by pay id
  147. func (d *Dao) PayComplete(ids []uint32) (affectedRow int64, err error) {
  148. var db = d.crmdb.Table(signmodel.TableNameSignPay).Where("id in (?)", ids).Updates(map[string]interface{}{"state": PayStatePayed})
  149. err = db.Error
  150. if err == nil {
  151. affectedRow = db.RowsAffected
  152. }
  153. return
  154. }
  155. //SignWithName sign with name, used to send mail
  156. type SignWithName struct {
  157. signmodel.SignUp
  158. Name string
  159. }
  160. //GetEndDate used for template
  161. func (s *SignWithName) GetEndDate() string {
  162. return s.EndDate.Time().Format(upcrmmodel.TimeFmtDate)
  163. }
  164. //GetDueSignUp check due
  165. // expireAfterDays : how many days to expire
  166. func (d *Dao) GetDueSignUp(now time.Time, expireAfterDays int) (result []*SignWithName, err error) {
  167. var dueDate = now.AddDate(0, 0, expireAfterDays)
  168. var db = d.crmdb.Table(signmodel.TableNameSignUp).Select("id, mid, end_date, admin_id, admin_name")
  169. // email_state = 0 是未发过邮件的意思
  170. db = db.Where("end_date <= ? and end_date >= ? and email_state = 0", dueDate.Format(upcrmmodel.TimeFmtDate), now.Format(upcrmmodel.TimeFmtDate))
  171. err = db.Find(&result).Error
  172. return
  173. }
  174. //PayWithAdmin pay with name, used to send mail
  175. type PayWithAdmin struct {
  176. signmodel.SignPay
  177. Name string
  178. AdminID int
  179. AdminName string
  180. }
  181. //GetEndDate used for template
  182. func (s *PayWithAdmin) GetEndDate() string {
  183. return s.DueDate.Time().Format(upcrmmodel.TimeFmtDate)
  184. }
  185. //GetPayValue for template
  186. func (s *PayWithAdmin) GetPayValue() float64 {
  187. return float64(s.PayValue) / 1000.0
  188. }
  189. //GetDuePay check due
  190. func (d *Dao) GetDuePay(now time.Time, expireAfterDays int) (result []*PayWithAdmin, err error) {
  191. var dueDate = now.AddDate(0, 0, expireAfterDays)
  192. err = d.crmdb.Raw("select p.id, "+
  193. "p.sign_id, "+
  194. "p.mid, "+
  195. "p.due_date, "+
  196. "p.pay_value,"+
  197. "s.admin_id, "+
  198. "s.admin_name"+
  199. " from sign_pay as p left join sign_up as s on p.sign_id = s.id "+
  200. " where p.due_date <= ? and p.email_state = 0 and p.state = 0", dueDate.Format(upcrmmodel.TimeFmtDate)).
  201. Scan(&result).Error
  202. return
  203. }
  204. //TaskWithAdmin task with admin
  205. type TaskWithAdmin struct {
  206. signmodel.SignTaskHistory
  207. Name string
  208. AdminID int
  209. AdminName string
  210. }
  211. //EndDate used for template
  212. func (s *TaskWithAdmin) EndDate() xtime.Time {
  213. var _, end = GetTaskDuration(s.GenerateDate.Time(), s.TaskType)
  214. return xtime.Time(end.Unix())
  215. }
  216. //TypeDesc descrption
  217. func (s *TaskWithAdmin) TypeDesc() string {
  218. return signmodel.TaskTypeStr(int(s.TaskType))
  219. }
  220. var (
  221. //NeedCheckTaskType task type
  222. NeedCheckTaskType = []int8{
  223. signmodel.TaskTypeWeek,
  224. signmodel.TaskTypeMonth,
  225. signmodel.TaskTypeQuarter,
  226. }
  227. )
  228. //GetDueTask get due tasks
  229. func (d *Dao) GetDueTask(now time.Time) (result []*TaskWithAdmin, err error) {
  230. // 到期的任务,
  231. // 从sign_task_history表中查询任务
  232. for _, t := range NeedCheckTaskType {
  233. var min, max = GetTaskExpireLimit(now, t)
  234. // 从sign_task_history中查询min<=generate_date <=max and task_type = t and state != 2
  235. var tasks []*TaskWithAdmin
  236. err = d.crmdb.Raw(`
  237. select t.*, u.admin_id, u.admin_name
  238. from sign_task_history as t
  239. left join sign_up as u
  240. on t.sign_id=u.id
  241. where t.generate_date=? and t.task_type=? and t.state!=2`, // t.generate_date=? 现在只在时间刚好达到时发送邮件,这样可以只发送一次,但是有可能会漏掉那些早已经过期的。
  242. max.Format(upcrmmodel.TimeFmtDate), t).
  243. Find(&tasks).Error
  244. if err != nil {
  245. log.Error("fail to get from db, task type=%d, min=%s, max=%s", t, min, max)
  246. return
  247. }
  248. log.Info("get from db, task type=%d, min=%s, max=%s, len=%d", t, min, max, len(tasks))
  249. result = append(result, tasks...)
  250. }
  251. return
  252. }
  253. //UpdateEmailState update email send state
  254. // state : @
  255. func (d *Dao) UpdateEmailState(table string, ids []uint32, state int8) (affectedRow int64, err error) {
  256. if len(ids) == 0 {
  257. log.Warn("no ids to update email state, state=%d", state)
  258. return
  259. }
  260. var db = d.crmdb.Table(table).Where("id in (?)", ids).Update("email_state", state)
  261. err = db.Error
  262. if err == nil {
  263. affectedRow = db.RowsAffected
  264. } else {
  265. log.Error("update email state fail, err=%+v", err)
  266. }
  267. return
  268. }
  269. //CheckUpHasValidContract check if has valid contract
  270. func (d *Dao) CheckUpHasValidContract(mid int64, date time.Time) (exist bool, err error) {
  271. var ids []struct {
  272. ID int
  273. }
  274. err = d.crmdb.Table(signmodel.TableNameSignUp).Select("id").Where("mid=? and end_date>=?", mid, date.Format(upcrmmodel.TimeFmtDate)).Limit(1).Find(&ids).Error
  275. if err != nil && err != gorm.ErrRecordNotFound {
  276. log.Error("check exist from db fail, err=%+v", err)
  277. return
  278. }
  279. exist = len(ids) > 0
  280. return
  281. }