[FRAMEWORK] Xây dựng page Account Phần 6 (ok)

Activity Event, Business Event, Add Business Event

Activity Even

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\ajax\business.php

<?php
add_action('wp_ajax_account_activity_load_list_deal', 'account_activity_load_list_deal');
function account_activity_load_list_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  $model = $bj_controller->Model("business");
  $list_deal = $model->activity_load_deal_id(5);
  if(!empty($list_deal)){
    $deal_model = $bj_controller->Model("deal");
    foreach ($list_deal as  $value) {
      $deal_detail = $deal_model->get_deal_detail($value["deal_id"]);
      echo '<div class="col-6">';
        get_template_part("framework/views/deal/item","",$deal_detail);
      echo '</div>';
    }
  }else{
    echo '<p class="p-3">'.__("No data","umm").'</p>';
  }
  wp_die();
}
add_action('wp_ajax_account_activity_get_tab_number', 'account_activity_get_tab_number');
function account_activity_get_tab_number() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  if(!isset($_POST["type"]) or !in_array($_POST["type"],["activity","business"])) die("error");
  global $bj_controller, $wpdb;
  $return = array(
    "deal" => 0,
    "event" => 0,
    ,"market" => 0,
    "business" => 0
  );
  if($_POST["type"] == "activity"){
    $list_deal = $bj_controller->Model("business")->activity_load_deal_id(10000);
    if(!empty($list_deal)) $return["deal"] = count($list_deal);
    $list_event = $bj_controller->Model("event")->get_list_event_saved($current_user_id);
    if(!empty($list_event)) $return["event"] = count($list_event);
  }else{
    $list_business_arr = $bj_controller->Model("business")->get_list_business_by_user_id($current_user_id);
    if(!empty($list_business_arr)) {
      $arr = [];
      foreach ($list_business_arr as $value) {
        $arr[] = $value["id"];
      }
      $table = $wpdb->prefix."bj_business_deal";
      $business_id_arr = implode("','",$arr);
      $list_deal = $wpdb->get_results ( " SELECT * FROM  {$table} WHERE business_id IN ('{$business_id_arr}') ORDER BY id DESC" ,ARRAY_A);
      if(!empty($list_deal)) $return["deal"] = count($list_deal);
    };
  }
  die(json_encode($return));
}
add_action('wp_ajax_account_business_load_list_deal', 'account_business_load_list_deal');
function account_business_load_list_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  global $wpdb;
  $list_business_arr = $bj_controller->Model("business")->get_list_business_by_user_id($current_user_id);
  if(!empty($list_business_arr)) {
    $arr = [];
    foreach ($list_business_arr as $value) {
      $arr[] = $value["id"];
    }
    $table = $wpdb->prefix."bj_business_deal";
    $business_id_arr = implode("','",$arr);
    $list_deal = $wpdb->get_results ( " SELECT * FROM  {$table} WHERE business_id IN ('{$business_id_arr}') ORDER BY id DESC" ,ARRAY_A);
    if(!empty($list_deal)){
      $deal_model = $bj_controller->Model("deal");
      foreach ($list_deal as  $value) {
        $deal_detail = $deal_model->get_deal_detail($value["id"]);
        $deal_detail["account"] = true;
        echo '<div class="col-6">';
        $bj_controller->View("item", $deal_detail, "deal"); 
        echo '</div>';
      }
    }else{
      echo '<p class="p-3">'.__("No data","umm").'</p>';
    }
  };
  wp_die();
}
add_action('wp_ajax_add_deal', 'add_deal');
function add_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'], BJ_NONCE_KEY.'adddeal'.$current_user_id ) ) {
    wp_die("error1"); 
  } 
  if(!empty($_POST['title']) && strlen($_POST["title"]) < 250 ){
    $title = strip_tags($_POST["title"]);}else{
    wp_die("error2");
  }
  if(!empty($_POST['description'])){
    $description = strip_tags($_POST["description"]);
  }else{
    wp_die("error3");
  }
  if(!empty($_POST['date_from'])){
    $date_from = strip_tags($_POST["date_from"]);
  }else{
    wp_die("error4");
  }
  if(!empty($_POST['date_to'])){
    $date_to = strip_tags($_POST["date_to"]);
  }else{
    wp_die("error5");
  }
  if(!empty($_POST['quantity']) && is_numeric($_POST["quantity"]) && $_POST['quantity'] < 9999999){
    $quantity = $_POST["quantity"];
  }else{
    wp_die("error6");
  }
  global $bj_controller;
  $model = $bj_controller -> Model("directory");
  if(!empty($_POST['business_id']) && is_numeric($_POST["business_id"]) && !empty($model->get_business_detail($_POST["business_id"]))){
    $business_id = $_POST["business_id"];
  }else{
      wp_die("error7");
  }
  $file_arr = $list_image_uploaded = [];
  if(!empty($_FILES["upload_files"])){    
    foreach ($_FILES["upload_files"]["name"] as $key => $value) {
      $file_arr[] = array(
        "name" => $_FILES["upload_files"]["name"][$key],
        "type" => $_FILES["upload_files"]["type"][$key],
        "tmp_name" => $_FILES["upload_files"]["tmp_name"][$key],
        "error" => $_FILES["upload_files"]["error"][$key],
        "size" => $_FILES["upload_files"]["size"][$key]
      );
    }
  }
  if(!empty($img_exclude)){
      foreach ($img_exclude as $key) {
        unset($file_arr[$key]);
      }
    }
    $district = "";
    $business_detai = $bj_controller->Model("business")->get_business_detail($business_id);
    if(!empty($business_detai)) $district = $business_detai["district"];
    $data_add = array(
    "business_id" => $business_id,
    "title" => $title,
    "description" => $description,
    "date_from" => $date_from,
    "date_to" => $date_to,
    "quantity" => $quantity,
    "district" => $district,
  );
  $data_format = array("%d","%s","%s","%s","%s","%d","%s");
  if(!empty($file_arr)){
    foreach ($file_arr as $file) {
      $upload_result = market_upload_image($file);
      if($upload_result["status"] == "success"){
        $list_image_uploaded[] = $upload_result["content"];
      }
    }
  }
  if(!empty($list_image_uploaded)){
    $data_add["images"] = json_encode($list_image_uploaded);
    $data_format[] = "%s";
  }
  $model = $bj_controller->Model("deal");
  $deal_id = $model->add_deal($data_add,$data_format);  
  echo $deal_id > 0 ? "success" : "error";
  wp_die();
}
add_action('wp_ajax_account_activity_load_list_event', 'account_activity_load_list_event');
function account_activity_load_list_event() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  $model = $bj_controller->Model("event");
  echo '<div class="col-12 col-activity-event">';
  foreach (["going","maybe"] as $type) {
    $list_event = $model->get_list_event_saved($current_user_id,$type);
    echo '<div class="row '.$type.'">';
    echo '<div class="col-12 col-title"><h5>'.$type.'</h5></div>';
    if(!empty($list_event)){
      foreach ($list_event as  $data) {
        $data["type"] = $type;
        echo '<div class="col-6">';
          $bj_controller->View("item", $data, "event"); 
        echo '</div>';
      }
    }else{
      echo '<p class="col-6">'.__("No data","umm").'</p>';
    }
    echo '</div>';
  }
  echo '</div>';
  wp_die();
}

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\js\account-business.js

jQuery(document).ready(function($) {
  function account_activity_business_load(type) {
    $(".status").removeClass("d-none");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_load_list_' + type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        $(".tab-" + type + " .account-list-item").append(output);
        $(".status").addClass("d-none");
      }
    });
  }
  function account_get_tab_number(type = "activity") {
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_get_tab_number',
        type: type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        if (output != "error") {
          const obj = JSON.parse(output, function(key, value) {
            $(".account-load-btn[data-id='" + key + "'] span").text(value);
          });
        }
      }
    });
  }
  // ==
  account_activity_business_load("deal");
  account_get_tab_number();
  // ==
  $('body').on('click', '#change-acc', function(e) {
    const $this = $(this);
    const btnScan = $('#scan-voucher');
    const type = $this.attr('data-type');
    const userId = $this.attr('data-id');
    const tab_active = $(".tab-active").data("tab-id");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'change_business_activity',
        token: $('#nonce_token').val(),
        type: type,
        id: userId,
      },
      beforeSend: function() {
        $(".account-list-item:not('.news') .col-6").not(".col-addnew").remove();
        $this.find('svg').addClass('spin');
      },
      success: function(response) {
        $(".menu-tab-account .li").not(".active").find("a").addClass("load");
        $this.find('svg').removeClass('spin');
        btnScan.toggle();
        if (type == 'activity') {
          // xử lý data business
          account_get_tab_number("business");
          $this.attr('data-type', 'business').find('span').text(app.business);
          $(".account-list-item .col-addnew").removeClass("d-none");
          if (tab_active != "news") {
            account_activity_business_load(tab_active);
          }
          $(".menu-tab-account ul li:last-child,.tab-news").addClass("d-none");
          $(".col-activity-event").remove();
          return;
        }
        $this.attr('data-type', 'activity').find('span').text(app.activity);
        $(".account-list-item .col-addnew").addClass("d-none");
        account_get_tab_number();
        if (tab_active != "news") {
          account_activity_business_load(tab_active);
        }
        $(".menu-tab-account ul li:last-child,.tab-news").removeClass("d-none");
      },
      error: function() {
        $this.find('svg').removeClass('spin');
        alert('Error');
      }
    })
    return false;
  });
  // ==
  var exclude_img = [];
  var input_btn = 0;
  var xp = -1;
  $(document).on("click", ".add-image-btn", function(e) {
    let select = $(this).closest("form");
    input_btn++;
    select.find(".list-input-file").append("<input type='file' name='upload_files[]' id='filenumber" + input_btn + "' class='img_file upload_files' accept='.gif,.jpg,.jpeg,.png,' multiple/>");
    $("#filenumber" + input_btn).click();
  });
  $(document).on("change", ".upload_files", function(e) {
    let select = $(this).closest("form")
    files = e.target.files;
    filesLength = files.length;
    for (var i = 0; i < filesLength; i++) {
      var f = files[i];
      var res_ext = files[i].name.split(".");
      var img_or_video = res_ext[res_ext.length - 1];
      var fileReader = new FileReader();
      fileReader.name = f.name;
      fileReader.onload = function(e) {
        xp++;
        var file = e.target;
        select.find(".images-box").append("<div class='box preview-image'><div class='images-preview' style='background-image: url(" + e.target.result + ")'><button type='button' data-id='" + xp + "' class='remove-img btn-close' title='Remove'></button></div></div>");
      };
      fileReader.readAsDataURL(f);
    }
  });
  $(document).on("click", ".images-box .remove-img", function() {
    $(this).closest(".box").remove();
    exclude_img.push($(this).attr("data-id"));
  });
  // ==
  var is_busy = false;
  var add_deal_form = "#add-deal-form ";
  $(add_deal_form).submit(function() {
    if (is_busy == true) return;
    is_busy = true;
    var formData = new FormData(document.getElementById("add-deal-form"));
    formData.append('action', 'add_deal');
    formData.append('exclude_img', exclude_img);
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      contentType: false,
      processData: false,
      data: formData,
      success: function(output) {
        is_busy = false;
        if (output == "success") {
          $("#alert-success").modal("show");
          $("#add_deal_form").remove();
        }
      }
    });
    return false;
  });
  $(document).on("click", ".deal.add-favorite", function() {
    if (is_busy == true) return;
    is_busy = true;
    let select = $(this);
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'deal_favorite_process',
        id: $(this).attr("data-id"),
        token: $(this).attr("data-token"),
      },
      success: function(output) {
        $(".status").addClass("d-none");
        is_busy = false;
        if (output == "success") {
          select.toggleClass("added");
        }
      }
    })
  });
  $(".account-load-btn").click(function(){
    if($(this).hasClass("load")){
      let data_type = $(this).data("id");
      let account_type = $("#change-acc").attr("data-type");
      account_activity_business_load(data_type);
      $(this).removeClass("load");
    }
  })
});

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\framework.php

<?php
class Pv_Controller {
  public function load() {
    global $bj_controller;
    return $bj_controller;
  }
}
class BJ_Controller {
  public function Controller($file_name = "") {
    $obj      = new stdClass();
    $file_url = "controllers/" . $file_name . ".php";
    require_once $file_url;
    $controller_name = "BJ_" . $file_name . "_Controller";
    $obj             = new $controller_name();
    return $obj;
  }
  public function Model($file_name = "") {
    $obj      = new stdClass();
    $file_url = "models/" . $file_name . ".php";
    require_once $file_url;
    $model_name = "BJ_" . $file_name . "_Model";
    $obj        = new $model_name();
    return $obj;
  }
  public function View($file_name = "", $data = array(), $path = "") {
    $file_name = $path . "/" . $file_name;
    get_template_part("framework/views/" . $file_name, "", $data);
  }
}
function render_district($district = "",$tinh_thanh = 79){  
  $json = file_get_contents(get_stylesheet_directory() ."/json/quan-huyen/".$tinh_thanh.".json");
  $arr = json_decode($json,true);
  return $district == "" ? $arr : $arr[$district]['name_with_type']; 
}

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\views\event\item.php

<?php  
global $bj_controller;
$model = $bj_controller->Model("event");
$thumb_url = THEME_URL."images/default.jpg";
if(!empty($args["images"])){
  $images_arr = json_decode($args["images"],true);
  if(!empty($images_arr)){
    $thumb_url = get_market_image_url($images_arr[0]);
  }
}
$token = wp_create_nonce(BJ_NONCE_KEY."event".$args["id"]);
$status = $model->get_event_user_status($args["id"],get_current_user_id());
$added_class = !empty($status) ? " added" : "";
$add = "";
if(isset($args["type"]) && $args["type"] == "going"){
  $svg = '<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg" style="width: 18px !important;">
      <circle cx="11" cy="11" r="11" fill="#686868"></circle>
      <path d="M17 7L8.53846 15L6 12.6024" stroke="#DADADA" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
      </svg>';
}else{
  $svg = '<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M11 1L14.09 7.26L21 8.27L16 13.14L17.18 20.02L11 16.77L4.82 20.02L6 13.14L1 8.27L7.91 7.26L11 1Z" fill="#686868" stroke="#686868" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>';
}
if(empty($args["account"])){
$add = '<button class="event add-favorite btn'.$added_class.'" data-id="'.$args["id"].'" data-token="'.$token.'" data-type="maybe" data-page="archive">'.$svg.'</button>';
  $link = get_site_url()."/events/?id=".$args["id"]."&token=".$token."&appt=N";
}else{
  $link = get_site_url()."/account/?action=view-event&event_id=".$args["id"]."&token=".$token."&appt=N";
}
?>
<div class="business-item box event">
  <a href="<?php echo $link ?>">
    <div class="thumb">
      <img src="<?php echo $thumb_url ?>" alt="">
      <div class="event-date">
        <?php  
          $timestamp = strtotime($args["date_"]);
        ?>
        <strong><?php echo date('d', $timestamp); ?></strong>
        <strong><?php echo date('M', $timestamp); ?></strong>
      </div>
    </div>
    <div class="info">
      <h5><?php echo $args["title"] ?></h5>
      <ul class="list-unstyled">
        <li>
          <div><img src="<?php echo THEME_URL."images/clock.svg"; ?>"></div>
          <span><?php echo substr($args["time_from"], 0, -3)." - ". substr($args["time_to"], 0, -3); ?></span>
        </li>
        <li>
          <div><img src="<?php echo THEME_URL."images/local.svg"; ?>"></div>
          <span><?php echo render_district($args["district"],$args["province"]); ?></span>
        </li>
        <li>
          <div><img src="<?php echo THEME_URL."images/user-group.svg"; ?>"></div>
          <span><?php echo  $args["going"].__(" Going","umm"); ?></span>
        </li>
      </ul>
    </div>
  </a>
  <?php echo $add; ?>
</div>

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\models\event.php

<?php
class BJ_event_Model {
  private $table_event = 'bj_event';
  public function get_list_event_id_saved($user_id) {
    global $wpdb;
    $arr    = [];
    $table  = $wpdb->prefix . "bj_event_user";
    $result = $wpdb->get_results($wpdb->prepare(" SELECT event_id FROM  {$table} WHERE user_id = %d ", $user_id), ARRAY_A);
    if (!empty($result)) {
      foreach ($result as $value) {
        $arr[] = $value["event_id"];
      }
    }
    return $arr;
  }
  public function get_list_event_saved($user_id) {
    global $wpdb;
    $table         = $wpdb->prefix . $this->table_event;
    $list_event_id = $this->get_list_event_id_saved($user_id);
    if (!empty($list_event_id)) {
      $array  = implode("','", $list_event_id);
      $result = $wpdb->get_results("SELECT * FROM  {$table} WHERE id IN ('{$array}')", ARRAY_A);
      if (!empty($result)) {
        return $result;
      }
    }
  }
  public function get_event_user_status($event_id, $user_id) {
    global $wpdb;
    $table  = $wpdb->prefix . "bj_event_user";
    $result = $wpdb->get_results($wpdb->prepare(" SELECT type FROM  {$table} WHERE event_id = %d AND user_id = %d", $event_id, $user_id), ARRAY_A);
    if (!empty($result)) {
      return $result[0]["type"];
    }
  }
} //end class

Last updated