module_shop_act_delete.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package modules
  2. import (
  3. "os"
  4. "golang-fave/engine/wrapper"
  5. "golang-fave/utils"
  6. )
  7. func (this *Modules) RegisterAction_ShopDelete() *Action {
  8. return this.newAction(AInfo{
  9. WantDB: true,
  10. Mount: "shop-delete",
  11. WantAdmin: true,
  12. }, func(wrap *wrapper.Wrapper) {
  13. pf_id := wrap.R.FormValue("id")
  14. if !utils.IsNumeric(pf_id) {
  15. wrap.MsgError(`Inner system error`)
  16. return
  17. }
  18. if err := wrap.DB.Transaction(func(tx *wrapper.Tx) error {
  19. // Block rows
  20. if _, err := tx.Exec("SELECT id FROM shop_products WHERE id = ? FOR UPDATE;", pf_id); err != nil {
  21. return err
  22. }
  23. if _, err := tx.Exec("SELECT product_id FROM shop_cat_product_rel WHERE product_id = ? FOR UPDATE;", pf_id); err != nil {
  24. return err
  25. }
  26. if _, err := tx.Exec("SELECT product_id FROM shop_filter_product_values WHERE product_id = ? FOR UPDATE;", pf_id); err != nil {
  27. return err
  28. }
  29. if _, err := tx.Exec("SELECT product_id FROM shop_product_images WHERE product_id = ? FOR UPDATE;", pf_id); err != nil {
  30. return err
  31. }
  32. // Delete product attached images
  33. rows, err := wrap.DB.Query(
  34. `SELECT
  35. product_id,
  36. filename
  37. FROM
  38. shop_product_images
  39. WHERE
  40. product_id = ?
  41. ;`,
  42. pf_id,
  43. )
  44. if err == nil {
  45. defer rows.Close()
  46. values := make([]string, 2)
  47. scan := make([]interface{}, len(values))
  48. for i := range values {
  49. scan[i] = &values[i]
  50. }
  51. for rows.Next() {
  52. err = rows.Scan(scan...)
  53. if err == nil {
  54. target_file_full := wrap.DHtdocs + string(os.PathSeparator) + "products" + string(os.PathSeparator) + "images" + string(os.PathSeparator) + string(values[0]) + string(os.PathSeparator) + string(values[1])
  55. os.Remove(target_file_full)
  56. }
  57. }
  58. }
  59. if _, err := tx.Exec("DELETE FROM shop_product_images WHERE product_id = ?;", pf_id); err != nil {
  60. return err
  61. }
  62. // Delete target product with category connection data
  63. if _, err := tx.Exec("DELETE FROM shop_filter_product_values WHERE product_id = ?;", pf_id); err != nil {
  64. return err
  65. }
  66. if _, err := tx.Exec("DELETE FROM shop_cat_product_rel WHERE product_id = ?;", pf_id); err != nil {
  67. return err
  68. }
  69. if _, err := tx.Exec("DELETE FROM shop_products WHERE id = ?;", pf_id); err != nil {
  70. return err
  71. }
  72. return nil
  73. }); err != nil {
  74. wrap.MsgError(err.Error())
  75. return
  76. }
  77. // Reload current page
  78. wrap.Write(`window.location.reload(false);`)
  79. })
  80. }