session.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package basket
  2. import (
  3. "encoding/json"
  4. "html"
  5. "golang-fave/engine/sqlw"
  6. "golang-fave/utils"
  7. )
  8. type session struct {
  9. Products map[int]*product `json:"products"`
  10. Currency *currency `json:"currency"`
  11. TotalSum float64 `json:"total_sum"`
  12. TotalCount int `json:"total_count"`
  13. }
  14. func (this *session) String() string {
  15. json, err := json.Marshal(this)
  16. if err != nil {
  17. return `{"msg":"basket_engine_error","message":"` + err.Error() + `"}`
  18. }
  19. return string(json)
  20. }
  21. func (this *session) Plus(db *sqlw.DB, product_id int) {
  22. if p, ok := this.Products[product_id]; ok == true {
  23. p.Quantity++
  24. p.Sum = p.Price * float64(p.Quantity)
  25. this.updateTotals()
  26. return
  27. }
  28. row := &utils.MySql_shop_product{}
  29. if err := db.QueryRow(`
  30. SELECT
  31. shop_products.id,
  32. shop_products.name,
  33. shop_products.price
  34. FROM
  35. shop_products
  36. WHERE
  37. shop_products.active = 1 AND
  38. shop_products.id = ?
  39. LIMIT 1;`,
  40. product_id,
  41. ).Scan(
  42. &row.A_id,
  43. &row.A_name,
  44. &row.A_price,
  45. ); err == nil {
  46. // Load product image here
  47. this.Products[product_id] = &product{
  48. Id: row.A_id,
  49. Name: html.EscapeString(row.A_name),
  50. Image: "",
  51. Price: row.A_price,
  52. Quantity: 1,
  53. Sum: row.A_price,
  54. }
  55. this.updateTotals()
  56. }
  57. }
  58. func (this *session) Minus(db *sqlw.DB, product_id int) {
  59. if p, ok := this.Products[product_id]; ok == true {
  60. if p.Quantity > 1 {
  61. p.Quantity--
  62. p.Sum = p.Price * float64(p.Quantity)
  63. } else {
  64. delete(this.Products, product_id)
  65. }
  66. this.updateTotals()
  67. }
  68. }
  69. func (this *session) Remove(db *sqlw.DB, product_id int) {
  70. if _, ok := this.Products[product_id]; ok == true {
  71. delete(this.Products, product_id)
  72. this.updateTotals()
  73. }
  74. }
  75. func (this *session) updateTotals() {
  76. this.TotalSum = 0
  77. this.TotalCount = 0
  78. for _, product := range this.Products {
  79. this.TotalSum += product.Price * float64(product.Quantity)
  80. this.TotalCount += product.Quantity
  81. }
  82. }