session.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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) Info(db *sqlw.DB, currency_id int) {
  22. // Update prices
  23. // Update total
  24. }
  25. func (this *session) Plus(db *sqlw.DB, product_id int) {
  26. if p, ok := this.Products[product_id]; ok == true {
  27. p.Quantity++
  28. p.Sum = p.Price * float64(p.Quantity)
  29. this.updateTotals()
  30. return
  31. }
  32. row := &utils.MySql_shop_product{}
  33. if err := db.QueryRow(`
  34. SELECT
  35. shop_products.id,
  36. shop_products.name,
  37. shop_products.price
  38. FROM
  39. shop_products
  40. WHERE
  41. shop_products.active = 1 AND
  42. shop_products.id = ?
  43. LIMIT 1;`,
  44. product_id,
  45. ).Scan(
  46. &row.A_id,
  47. &row.A_name,
  48. &row.A_price,
  49. ); err == nil {
  50. // Load product image here
  51. this.Products[product_id] = &product{
  52. Id: row.A_id,
  53. Name: html.EscapeString(row.A_name),
  54. Image: "",
  55. Price: row.A_price,
  56. Quantity: 1,
  57. Sum: row.A_price,
  58. }
  59. this.updateTotals()
  60. }
  61. }
  62. func (this *session) Minus(db *sqlw.DB, product_id int) {
  63. if p, ok := this.Products[product_id]; ok == true {
  64. if p.Quantity > 1 {
  65. p.Quantity--
  66. p.Sum = p.Price * float64(p.Quantity)
  67. } else {
  68. delete(this.Products, product_id)
  69. }
  70. this.updateTotals()
  71. }
  72. }
  73. func (this *session) Remove(db *sqlw.DB, product_id int) {
  74. if _, ok := this.Products[product_id]; ok == true {
  75. delete(this.Products, product_id)
  76. this.updateTotals()
  77. }
  78. }
  79. func (this *session) updateTotals() {
  80. this.TotalSum = 0
  81. this.TotalCount = 0
  82. for _, product := range this.Products {
  83. this.TotalSum += product.Price * float64(product.Quantity)
  84. this.TotalCount += product.Quantity
  85. }
  86. }