get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'shop_order' AND post_status IN ('{$post_status}')"); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$stock_date."'"); $count = 0; //chech matched delivery date and sku# foreach ($result as $order_obj ){ $order = wc_get_order( $order_obj->ID ); $delivery_date = $order->get_meta('delivery_date', true); if($delivery_date == $stock_date){ foreach ( $order->get_items() as $item ) { $product = $item->get_product(); $stock_sku = get_master_sku($product->get_sku()); $unit_qty = 1; if(has_master_sku($product->get_sku())){ $unit_qty = get_master_sku_unit_qty($product->get_sku()); //get master sku unit qty }else{ //check variation for old product $variation_id = $item->get_variation_id(); if($variation_id!=0){ $unit_qty = get_variation_unit_qty($variation_id); //get variation unit qty }else{ $unit_qty = 1; } } if($stock_sku==$sku){ $count += $item->get_quantity()*$unit_qty; } } } } return $count; } function adjust_stock($order_id){ if ( ! $order_id ) return; global $wpdb; // Getting an instance of the order object $order = wc_get_order( $order_id ); $delivery_date = $order->get_meta('delivery_date', true); if(get_post_meta( $order_id, 'stock_out', true ) ) return; // Exit if already processed //if($order->has_status('processing') || $order->has_status('completed')){ if($order->has_status('pending') || $order->has_status('processing') || $order->has_status('completed')){ foreach ( $order->get_items() as $item_id => $item ) { $prod = $item->get_product(); $sku = $prod->get_sku(); $variation_id = $item->get_variation_id(); $product = wc_get_product(wc_get_product_id_by_sku($sku)); $stock_sku = get_master_sku($sku); $unit_qty = 1; if(has_master_sku($sku)){ $description = $product->get_name(); $unit_qty = get_master_sku_unit_qty($sku); }else{ if($variation_id!=0){ $description = get_name_from_variation_id($product->get_name(),$variation_id); $unit_qty = get_variation_unit_qty($variation_id); }else{ $description = $product->get_name(); // make a unique key $unit_qty = 1; } } $quantity = $item->get_quantity()*$unit_qty; if(isset($delivery_date)){ $qty_from = get_sku_stock_by_date($stock_sku, $delivery_date); $qty_to = $qty_from - $quantity; $sql_update = "UPDATE sku_stock SET `".$stock_sku."` = '".$qty_to."' WHERE stock_date = '".$delivery_date."' LIMIT 1"; if($wpdb->query($sql_update)){ write_log($delivery_date, "New Order", "Back End (Mobile)", $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update); } } } if(isset($delivery_date)){ //wc_create_order_note($order_id, "Delivery Date: ".sanitize_text_field($delivery_date), false, true); update_post_meta($order_id, 'stock_out','1'); } } } // wocommerce create order function 2021-06-07 by Samiel // function create_wc_order( $data ){ global $wpdb; $gateways = WC()->payment_gateways->get_available_payment_gateways(); $order = new WC_Order(); //create order object // Set Billing and Shipping adresses foreach( array('billing_', 'shipping_') as $type ) { foreach ( $data['address'] as $key => $value ) { if( $type === 'shipping_' && in_array( $key, array( 'email', 'phone' ) ) ) { $order->update_meta_data( '_shipping_'.$key, $value ); // add custom shipping field (email & phone) } else { $type_key = $type.$key; if ( is_callable( array( $order, "set_{$type_key}" ) ) ) { $order->{"set_{$type_key}"}( $value ); } } } } // Set other details $order->set_created_via( 'programatically' ); $order->set_customer_id( $data['user_id'] ); $order->set_currency( get_woocommerce_currency() ); $order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) ); $order->set_customer_note( isset( $data['order_comments'] ) ? $data['order_comments'] : '' ); //$order->set_payment_method( isset( $gateways[ $data['payment_method'] ] ) ? $gateways[ $data['payment_method'] ] : $data['payment_method'] ); if($data['user_id']!=0) { $customerInfo = new WC_Customer($data['user_id']); if($customerInfo->get_billing_first_name()!="" && $customerInfo->get_billing_address_1()!=""){ $order->set_billing_first_name($customerInfo->get_billing_first_name()); $order->set_billing_last_name($customerInfo->get_billing_last_name() ); $order->set_billing_company($customerInfo->get_billing_company() ); $order->set_billing_email($customerInfo->get_billing_email()); $order->set_billing_phone($customerInfo->get_billing_phone()); $order->set_billing_address_1($customerInfo->get_billing_address_1() ); $order->set_billing_address_2($customerInfo->get_billing_address_2() ); $order->set_billing_city($customerInfo->get_billing_city() ); $order->set_billing_state($customerInfo->get_billing_state() ); $order->set_billing_postcode($customerInfo->get_billing_postcode() ); $order->set_billing_country($customerInfo->get_billing_country() ); } } // Set custom details $order->update_meta_data('delivery_date', $data['delivery_date']); $order->update_meta_data('_stripe_intent_id', $data['payment_intent']); $order->update_meta_data('_customer_ip_address', $data['customer_ip']); $calculate_taxes_for = array( 'country' => $data['address']['country'], 'state' => $data['address']['state'], 'postcode' => $data['address']['postcode'], 'city' => $data['address']['city'] ); // Set Line items (product) foreach( $data['line_items'] as $line_item ) { $args = $line_item['args']; $product = wc_get_product( isset($args['variation_id']) && $args['variation_id'] > 0 ? $args['variation_id'] : $args['product_id'] ); $item_id = $order->add_product( $product, $line_item['quantity'], $line_item['args'] ); $item = $order->get_item( $item_id, false ); $item->calculate_taxes($calculate_taxes_for); $item->save(); if(isset($args['variation_id']) && $args['variation_id'] > 0){ $variation = wc_get_product($args['variation_id']); foreach($variation->get_variation_attributes() as $attribute_name => $attribute_value){ $wpdb->insert('wp_woocommerce_order_itemmeta', array( 'order_item_id' => $item_id, 'meta_key' => str_replace("attribute_","",$attribute_name), 'meta_value' => $attribute_value )); } } } // Set Line items (shipping) $shipping_lines = new WC_Order_Item_Shipping(); $shipping_lines->set_method_title($data['shipping_lines']['method_title']); $shipping_lines->set_method_id($data['shipping_lines']['method_id']); $shipping_lines->set_total($data['shipping_lines']['total']); $shipping_lines->calculate_taxes($calculate_tax_for); $order->add_item( $shipping_lines ); // Coupon items if( isset($data['coupon_items'])){ foreach( $data['coupon_items'] as $coupon_item ) { $order->apply_coupon(sanitize_title($coupon_item['code'])); } } // Set calculated totals $order->calculate_totals(); if( isset($data['order_status']) ) { // Update order status from pending to your defined status and save data $order->update_status($data['order_status']['status'], $data['order_status']['note']); $order->add_order_note("Delivery Date: ".$data['delivery_date']); $order_id = $order->get_id(); if($data['adjust_stock']=="Y"){ adjust_stock($order_id); // only run if order status = processing } update_post_meta($order_id, '_payment_method', 'other'); update_post_meta($order_id, '_payment_method_title', 'other'); update_post_meta($order_id, 'Payment', $data['payment_method']); update_post_meta($order_id, 'adjust_stock',$data['adjust_stock']); } else { // Save order to database (returns the order ID) $order_id = $order->save(); } // Returns the order ID return $order_id; } function get_sequence($stock_sku, $date){ global $wpdb; $result = $wpdb->get_results("SELECT * FROM `stock_init` WHERE sku = '".$stock_sku."' LIMIT 1"); if(count($result)>0){ if($date >= $result[0]->start_date && $date <= $result[0]->end_date) { return "1"; } elseif($date >= $result[0]->start_date && $result[0]->end_date == "0000-00-00") { return "2"; } elseif($date > $result[0]->end_date) { return "3"; } elseif($date < $result[0]->start_date) { return "0"; } }else{ return "0"; } } // check api key if($key!=API_KEY){ $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "invalid_key"; $array_result['message'] = "Unauthorized API Key"; $array_result['data'] = array( 'id' => null, 'email' => null, 'nicename' => null, 'firstName' => null, 'lastName' => null, 'displayName' => null, ); }elseif($secret!=API_SECRET){ // chcek api secret $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "invalid_secret"; $array_result['message'] = "Unauthorized API Secret"; $array_result['data'] = array( 'id' => null, 'email' => null, 'nicename' => null, 'firstName' => null, 'lastName' => null, 'displayName' => null, ); }else{ // check login if($section=="auth"){ $user = wp_authenticate( $param['username'], $param['password'] ); //$role = "TEST"; foreach($user->roles as $userRole){ //var_dump($userRole); $role = $userRole; } //print_r($user); if ( is_wp_error( $user ) ) { $error_code = $user->get_error_code(); $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = $error_code; $array_result['message'] = strip_tags( $user->get_error_message( $error_code ) ); $array_result['data'] = array( 'id' => null, 'email' => null, 'nicename' => null, 'firstName' => null, 'lastName' => null, 'displayName' => null, ); } elseif(!in_array($role, array("administrator","editor"))){ $error_code = $user->get_error_code(); $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "login_error"; $array_result['message'] = "This user is not allowed to use this app"; $array_result['data'] = array( 'id' => null, 'email' => null, 'nicename' => null, 'firstName' => null, 'lastName' => null, 'displayName' => null, ); }else { $stripe_customer_id = get_user_meta($user->ID, "wp__stripe_customer_id", true); //echo "stripe_id:".$stripe_customer_id; if($stripe_customer_id == ""){ $url = "https://www.breadsecret.com/StripeBackend/createCustomer.php"; $data = array( 'email' => $user->user_email, 'name' => $user->username, 'phone' => '' ); //print_r($data); $stripe_response = httpPost($url, $data); $stripe_data = json_decode($stripe_response, true); //print_r($stripe_data); update_user_meta($user->ID, "wp__stripe_customer_id", $stripe_data['id']); } $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "login_success"; $array_result['message'] = "Login Success!"; $array_result['data'] = array( 'id' => $user->ID, 'email' => $user->user_email, 'nicename' => $user->user_nicename, 'firstName' => $user->first_name, 'lastName' => $user->last_name, 'displayName' => $user->display_name, ); } } // check login if($section=="profile_data"){ $user = new WC_Customer( $_GET['user_id'] ); $array_result['id'] = intval($_GET['user_id']); $array_result['email'] = $user->get_email(); $array_result['first_name'] = $user->get_first_name(); $array_result['last_name'] = $user->get_last_name(); $array_result['username'] = $user->get_username(); $array_result['avatar_url'] = get_avatar_url($_GET['user_id']); $billing = array(); // Customer billing information details (from account) $billing['first_name'] = $user->get_billing_first_name(); $billing['last_name'] = $user->get_billing_last_name(); $billing['company'] = $user->get_billing_company(); $billing['address_1'] = $user->get_billing_address_1(); $billing['address_2'] = $user->get_billing_address_2(); $billing['city'] = $user->get_billing_city(); $billing['state'] = $user->get_billing_state(); $billing['postcode'] = $user->get_billing_postcode(); $billing['country'] = $user->get_billing_country(); $billing['phone'] = $user->get_billing_phone(); $billing['email'] = $user->get_billing_email(); $array_result['billing'] = $billing; // Customer shipping information details (from account) $shipping['first_name'] = $user->get_shipping_first_name(); $shipping['last_name'] = $user->get_shipping_last_name(); $shipping['company'] = $user->get_shipping_company(); $shipping['address_1'] = $user->get_shipping_address_1(); $shipping['address_2'] = $user->get_shipping_address_2(); $shipping['city'] = $user->get_shipping_city(); $shipping['state'] = $user->get_shipping_state(); $shipping['postcode'] = $user->get_shipping_postcode(); $shipping['country'] = $user->get_shipping_country(); $array_result['shipping'] = $shipping; $array_result['stripe_customer_id'] = get_user_meta($_GET['user_id'], 'wp__stripe_customer_id', true); } if($section=="order_list") { $array_result = array(); $delivery_date = isset($_GET['delivery_date']) && $_GET['delivery_date']!=""?$_GET['delivery_date']:date("Y-m-d"); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$delivery_date."' Order by order_master.ID DESC"); foreach ($result as $order_obj ){ $arr_order = array(); $order = wc_get_order( $order_obj->ID ); $arr_order['id'] = $order->get_id(); $arr_order['number'] = $order->get_order_number(); $arr_order['date_created'] = date("Y-m-d\TH:i:s", strtotime($order_obj->post_date)); //$arr_order['delivery_date'] = get_post_meta($order->get_id(), 'delivery_date', true); $arr_order['total'] = $order->get_total(); $arr_order['status'] = $order->get_status(); $arr_billing = array(); $arr_billing['first_name'] = $order->get_billing_first_name(); $arr_billing['last_name'] = $order->get_billing_last_name(); $arr_billing['company'] = $order->get_billing_company(); $arr_billing['address_1'] = $order->get_billing_address_1(); $arr_billing['city'] = $order->get_billing_city(); $arr_billing['state'] = $order->get_billing_state(); $arr_billing['country'] = $order->get_billing_country(); $arr_billing['email'] = $order->get_billing_email(); $arr_billing['phone'] = $order->get_billing_phone(); $arr_order['billing'] = $arr_billing; $arr_order['shipping_method'] = get_shipping_method_from_code($order->get_shipping_method()); $shipping_type = explode(" ",$order->get_shipping_method()); $arr_order['shipping_type'] = $shipping_type[0]; array_push($array_result, $arr_order); } } if($section=="order_detail"){ if(!empty($_GET['ord_id'])){ $order = new WC_Order($_GET['ord_id']); $array_result['id'] = intval($_GET['ord_id']); $array_result['number'] = $order->get_order_number(); $array_result['status'] = $order->get_status(); $array_result['currency'] = $order->get_currency(); //$array_result['date_created'] = $order->get_date_created()->format("m/d/Y"); $array_result['date_created'] = date("d/m/Y", strtotime($order->order_date)); $array_result['date_paid'] = is_null($order->get_date_paid())?"":$order->get_date_paid()->format("m/d/Y"); $array_result['subtotal'] = strval(number_format($order->get_subtotal(),2,".",",")); $array_result['discount_total'] = number_format($order->get_discount_total(),2,".",","); $array_result['shipping_total'] = number_format($order->get_shipping_total(),2,".",","); $array_result['total'] = number_format($order->get_total(),2,".",","); $array_result['customer_id'] = $order->get_customer_id(); $array_result['payment_method_title'] = $order->get_payment_method_title(); $array_result['transaction_id'] = $order->get_transaction_id(); $array_result['delivery_date'] = is_null(get_post_meta($_GET['ord_id'], 'delivery_date', true))?"":date("d/m/Y", strtotime(get_post_meta($_GET['ord_id'], 'delivery_date', true))); $array_result['payment'] = get_post_meta($_GET['ord_id'], 'Payment', true); $array_result['customer_note'] = $order->get_customer_note(); $array_result['shipping_method'] = get_shipping_method_from_code($order->get_shipping_method()); //billing info. $array_billing = array(); $array_billing['first_name'] = $order->get_billing_first_name(); $array_billing['last_name'] = $order->get_billing_last_name(); $array_billing['company'] = $order->get_billing_company(); $array_billing['address_1'] = $order->get_billing_address_1(); $array_billing['address_2'] = $order->get_billing_address_2(); $array_billing['city'] = $order->get_billing_city(); $array_billing['state'] = get_region_from_code($order->get_billing_state()); $array_billing['country'] = $order->get_billing_country(); $array_billing['email'] = $order->get_billing_email(); $array_billing['phone'] = $order->get_billing_phone(); $array_result['billing'] = $array_billing; //shipping info. $array_shipping = array(); $array_shipping['first_name'] = $order->get_shipping_first_name(); $array_shipping['last_name'] = $order->get_shipping_last_name(); $array_shipping['company'] = $order->get_shipping_company(); $array_shipping['address_1'] = $order->get_shipping_address_1(); $array_shipping['address_2'] = $order->get_shipping_address_2(); $array_shipping['city'] = $order->get_shipping_city(); $array_shipping['state'] = get_region_from_code($order->get_shipping_state()); $array_shipping['country'] = $order->get_shipping_country(); $array_shipping['email'] = get_post_meta($_GET['ord_id'], '_shipping_email', true); $array_shipping['phone'] = get_post_meta($_GET['ord_id'], '_shipping_phone', true); $array_result['shipping'] = $array_shipping; //item info. $array_line_items = array(); foreach ( $order->get_items() as $item_id => $item ) { $product = array(); $products = $item->get_product(); $product['id'] = $item->get_product_id(); $product['type'] = $products->get_type(); $category_name = array(); $category_id = wp_get_post_terms($product['id'], 'product_cat', array('fields' => 'ids')); foreach($category_id as $cat_id){ $category = get_term_by( 'id', $cat_id, 'product_cat', 'ARRAY_A' ); array_push($category_name, $category['name']); } $product['category'] = implode("/",$category_name); $product['variation_id'] = $item->get_variation_id(); $zh_post_id = 0; $trid = $sitepress->get_element_trid($product['id'], 'post_product'); $translations = $sitepress->get_element_translations($trid, 'product'); foreach( $translations as $lang=>$translation){ if($translation->language_code == "zh-hant") $zh_post_id = $translation->element_id; } if($product['variation_id']==0){ $product['variation_name'] = ""; } else { $arr_variation = explode(":",get_the_excerpt($product['variation_id'])); $product['variation_name'] = trim($arr_variation[1]); } $product['name'] = html_entity_decode(get_the_title($product['id'])); $product['name_zh'] = get_the_title($zh_post_id); $product['unit'] = get_post_meta($product['id'], '_woo_uom_input', true); $product['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true)==false?"":get_post_meta($zh_post_id, '_woo_uom_input', true); $product['sku'] = $products->get_sku(); $product['quantity'] = $item->get_quantity(); $product['price'] = $products->get_price()==0?strval($item->get_subtotal()/$item->get_quantity()):$products->get_price(); //$product['price'] = $item->get_subtotal(); $product['subtotal'] = $item->get_subtotal(); $product['image'] = wp_get_attachment_url($products->get_image_id())==false?"":wp_get_attachment_url($products->get_image_id()); array_push($array_line_items, $product); } $array_result['line_items'] = $array_line_items; } } if($section=="create_user"){ $check_user = username_exists($param['username']); if ( !$check_user ) { if( email_exists($param['email']) == false) { $user_id = wc_create_new_customer($param['email'], $param['username'], $param['password'] ); if($user_id){ update_user_meta( $user_id, "billing_first_name", $param['username'] ); update_user_meta( $user_id, "shipping_first_name", $param['username'] ); update_user_meta( $user_id, "billing_country", 'HK' ); update_user_meta( $user_id, "shipping_country", 'HK' ); update_user_meta( $user_id, "billing_email", $param['email'] ); $url = "https://www.breadsecret.com/StripeBackend/createCustomer.php"; $data = array( 'email' => $param['email'], 'name' => $param['username'], 'phone' => '' ); $stripe_response = httpPost($url, $data); $stripe_data = json_decode($stripe_response, true); //print_r($stripe_data); update_user_meta($user_id, "wp__stripe_customer_id", $stripe_data['id']); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "register_success"; $array_result['message'] = "Register Success"; $array_result['data'] = array( 'id' => $user_id, 'email' => $param['email'], 'username' => $param['username'], ); } else { $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "register_fail"; $array_result['message'] = "Register Fail"; $array_result['data'] = array( 'id' => 0, 'email' => "", 'username' => "", ); } } else { $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "register_fail"; $array_result['message'] = "Email already registered"; $array_result['data'] = array( 'id' => 0, 'email' => "", 'username' => "", ); } } else { $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "register_fail"; $array_result['message'] = "User name already registered"; $array_result['data'] = array( 'id' => 0, 'email' => "", 'username' => "", ); } } // update stripe user id if($section=="update_stripe_user"){ update_user_meta($param['user_id'], "wp__stripe_customer_id", $param['stripe_customer_id']); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "update Success"; } if($section=="lost_password") { $user_login = sanitize_text_field($param['login']); if ( empty( $user_login) ) { $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "Retrieve Password Fail"; $array_result['message'] = "Please fill in User Name / Email"; } else if ( strpos( $user_login, '@' ) ) { $user_data = get_user_by( 'email', trim( $user_login ) ); } else { $login = trim($user_login); $user_data = get_user_by('login', $login); } do_action('lostpassword_post'); if ( !$user_data ) { $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "Retrieve Password Fail"; $array_result['message'] = "User Name / Email not Found"; } else { // redefining user_login ensures we return the right case in the email $user_login = $user_data->user_login; $user_email = $user_data->user_email; do_action('retreive_password', $user_login); // Misspelled and deprecated do_action('retrieve_password', $user_login); $key = wp_generate_password( 20, false ); do_action( 'retrieve_password_key', $user_login, $key ); if ( empty( $wp_hasher ) ) { require_once ABSPATH . 'wp-includes/class-phpass.php'; $wp_hasher = new PasswordHash( 8, true ); } $hashed = time() . ':' . $wp_hasher->HashPassword( $key ); $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user_login ) ); $message = __('Hi ').$user_login.",\r\n\r\n

"; $message .= __('Someone has requested a password reset for the following account:') . "\r\n\r\n

"; $message .= network_home_url( '/' ) . "\r\n\r\n

"; $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n

"; $message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n
"; $message .= __('To reset your password, visit the following address:') . "\r\n\r\n

"; $message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "\r\n

"; $message .= __('Bread Secret') . "\r\n\r\n

"; if ( is_multisite() ) $blogname = $GLOBALS['current_site']->site_name; else $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $title = sprintf( __('[%s] Password Reset'), $blogname ); $title = apply_filters('retrieve_password_title', $title); if ( $message && !wp_mail($user_email, $title, $message) ) wp_die( __('The e-mail could not be sent.') . "
\n" . __('Possible reason: your host may have disabled the mail() function...') ); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Retrieve Password Success"; $array_result['message'] = "Link for password reset has been emailed to ".$user_email.". Please check your email."; } } if($section=="change_password") { $userdata = get_user_by('ID', $param['id']); $result = wp_check_password($param['cpw'], $userdata->user_pass, $userdata->ID); if(!$result){ $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "Error"; $array_result['message'] ="Incorrect current password"; }elseif($param['npw']!=$param['cnpw']){ $array_result['success'] = false; $array_result['statusCode'] = 403; $array_result['code'] = "Error"; $array_result['message'] ="New password and confirm new password not match"; }else{ wp_set_password(trim($param['cnpw']), $param['id']); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Change Password Success"; } } if($section=="delivery_date_list") { $arr_holiday = get_holiday_list(); $array_result = array(); $dummy_option = array("actualValue"=>"", "displayValue"=>"", "dayOfWeek"=>""); array_push($array_result, $dummy_option); $param['cart'] = str_replace("&Amp&", "&", $param['cart']) ; $arr_cart = json_decode($param['cart'], true); $now = time(); /* if(date('H', $now)>=16){ $now+=86400; } */ for($i = $now-16*86400; $i< $now+16*86400; $i=$i+86400){ if(date('N',$i)==7){ continue; } /* if(in_array(date('Y-m-d',$i),$arr_holiday)){ continue; } */ $avail = true; foreach($arr_cart['item'] as $cart) { $sku = $cart['sku']; $stock_sku = get_master_sku($sku); $unit_qty = 1; if(has_master_sku($sku)){ $unit_qty = get_master_sku_unit_qty($sku); }else{ //check variation for old product $variation_id = $cart['variationID']; if($variation_id!=0){ $unit_qty = get_variation_unit_qty($variation_id); }else{ $unit_qty = 1; } } $count = $cart['quantity']*$unit_qty; if($count>get_sku_stock_by_date($stock_sku,date('Y-m-d', $i))) $avail = false; } /* if(!$avail){ continue; } */ $array_option = array("actualValue"=>date('Y-m-d', $i), "displayValue"=>date('Y-m-d', $i), "dayOfWeek"=>date('l', $i)); array_push($array_result, $array_option); } //echo "array count: ".count($arr_option); if(count($array_result)==1){ $array_option = array("actualValue"=>"", "displayValue"=>"Please contact (WhatsApp: +852 5612 5381) for help", "dayOfWeek"=>""); array_push($array_result, $array_option); } //print_r($array_result); } if($section=="region_list") { $total = (isset($_GET['total']) && $_GET['total']!="")?$_GET['total']:0; $dummy_method_list = array(); $dummy_method = array("id"=>"", "instance_id"=>0, "title"=>"", "nice_name"=>"", "requires"=>"", "min_amount"=>0, "cost"=>0); array_push($dummy_method_list, $dummy_method); $dummy_option = array("id"=>0, "code"=>"", "name"=>"", "location"=>"", "method"=>$dummy_method_list); $array_result = array(); array_push($array_result, $dummy_option); $delivery_zones = WC_Shipping_Zones::get_zones(); foreach ((array) $delivery_zones as $key => $zone ) { $methodList = array(); $methodArr = array("id"=>"", "instance_id"=>0, "title"=>"", "nice_name"=>"", "requires"=>"", "min_amount"=>0, "cost"=>0); array_push($methodList, $methodArr); foreach($zone['shipping_methods'] as $idx => $method) { $show = false; if($method->enabled == "yes") { if($method->instance_settings['requires']=="" || is_null($method->instance_settings['requires'])){ $show = true; }elseif($method->instance_settings['requires']=="min_amount"){ $min_amount = (isset($method->instance_settings['min_amount']) && $method->instance_settings['min_amount']!="")?$method->instance_settings['min_amount']:0; if($total>=$min_amount){ $show = true; } } } if($show) { $result = $wpdb->get_results("SELECT name FROM `custom_shipping_method` WHERE code = '".trim($method->instance_settings['title'])."' LIMIT 1"); if(count($result)==1){ $nice_name = $result[0]->name; }else{ $nice_name = $method->instance_settings['title']; } $methodArr = array("id"=>$method->id, "instance_id"=>$method->instance_id, "title"=>$method->instance_settings['title'], "nice_name"=>$nice_name, "requires"=>isset($method->instance_settings['requires'])?$method->instance_settings['requires']:"", "min_amount"=>intval((isset($method->instance_settings['min_amount']) && $method->instance_settings['min_amount']!="")?$method->instance_settings['min_amount']:0), "cost"=>intval((isset($method->instance_settings['cost']) && $method->instance_settings['cost']!="")?$method->instance_settings['cost']:0)); array_push($methodList, $methodArr); } } $code = explode(":",$zone['zone_locations'][0]->code); $array_option = array("id"=>$zone['id'], "code"=>$code[1], "name"=>$zone['zone_name'], "location"=>$zone['formatted_zone_location'], "method"=>$methodList); array_push($array_result, $array_option); } $keys = array_column($array_result, 'location'); array_multisort($keys, SORT_ASC, $array_result); } if($section=="verify_coupon") { $array_result['success'] = true; $param['cart'] = str_replace("&Amp&", "&", $param['cart']) ; $cart = json_decode($param['cart'], true); $code = $param['code']; if(count($product) == 0 ){ $array_result['success'] = false; } $subTotal = 0; foreach($cart['item'] as $cartItem){ $subTotal += ($cartItem['quantity'] * $cartItem['productPrice']); } $coupon = new WC_Coupon($code); if($code!=""){ if($coupon->id != 0){ // check coupon exist $coupon_post = get_post($coupon->id); $coupon_data = array( 'id' => $coupon->id, 'code' => $coupon->code, 'type' => $coupon->type, 'created_at' => $coupon_post->post_date_gmt, 'updated_at' => $coupon_post->post_modified_gmt, 'amount' => wc_format_decimal($coupon->coupon_amount, 2), 'individual_use' => ( 'yes' === $coupon->individual_use ), 'product_ids' => array_map('absint', (array) $coupon->product_ids), 'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids), 'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null, 'usage_count' => (int) $coupon->usage_count, 'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', strtotime($coupon->expiry_date)) : null, 'enable_free_shipping' => $coupon->enable_free_shipping(), 'product_category_ids' => array_map('absint', (array) $coupon->product_categories), 'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories), 'exclude_sale_items' => $coupon->exclude_sale_items(), 'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2), 'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2), 'customer_emails' => $coupon->customer_email, 'description' => $coupon_post->post_excerpt, ); $discount = 0.00; if($coupon_data['type'] == 'percent') { //$subTotal = (float) $subTotal; //$coupon_data['amount'] = (float) $coupon_data['amount']; //$discount = number_format(($subTotal * $coupon_data['amount'] / 100),2); $discount = $subTotal * $coupon_data['amount']/100; //$discount = number_format($discount, 2, ""); } elseif($coupon_data['type'] == 'fixed_cart'){ $discount = number_format($coupon_data['amount'],2); } if($coupon_data['expiry_date']=="" || date('Y-m-d') <= $coupon_data['expiry_date']) { //check coupon expire if($coupon_data['minimum_amount']==0.00 || $subTotal >= $coupon_data['minimum_amount']){ //check min. cart amount if($coupon_data['maximum_amount']==0.00 || $subTotal <= $coupon_data['maximum_amount']){ //check max. cart amount if($coupon_data['usage_limit']==0.00 || $coupon_data['usage_limit'] > $coupon_data['usage_count']) { // check usage limit if(count($coupon_data['product_ids'])>0) { //check allowable list $check_allowable = true; foreach($cart as $cartItem){ if(!in_array($cartItem['productID'],$coupon_data['product_ids'])) { $check_allowable = false; } } if(!$check_allowable){ $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Coupon cannot be applied on some products"; $array_result['discount'] = 0.00; } else { $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Coupon Validated"; $array_result['discount'] = (float)$discount;/////////////////////////////// } } elseif(count($coupon_data['exclude_product_ids'])>0) { //check exclude list $check_exlude = true; foreach($cart as $cartItem){ if(!in_array($cartItem['productID'],$coupon_data['exclude_product_ids'])) { $check_exlude = false; } } if(!$check_exlude) { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Coupon cannot be applied on some products"; $array_result['discount'] = 0.00; } else { $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Coupon Validated"; $array_result['discount'] = (float)$discount; /////////////////////////////// } } else { $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Coupon Validated"; $array_result['discount'] = (float)$discount; /////////////////////////////// } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Coupon reached usage limit"; $array_result['discount'] = 0.00; } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Coupon does not meet the max. order amount"; $array_result['discount'] = 0.00; } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Coupon does not meet the min. order amount"; $array_result['discount'] = 0.00; } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Coupon expired"; $array_result['discount'] = 0.00; } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Invalid coupon code"; $array_result['discount'] = 0.00; } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Empty coupon code"; $array_result['discount'] = 0.00; } } if($section=="create_order") { $array_result['success'] = true; $param['cart'] = str_replace("&Amp&", "&", $param['cart']) ; //print_r($param['cart']); $product = json_decode($param['cart'], true); $info = json_decode($param['data'], true); if(count($product) == 0 ){ $array_result['success'] = false; } $user_id = $info['userID']; $delivery_date = $info['deliveryDate']; $status = $info['status']; $first_name = $info['firstName']; $last_name = $info['lastName']; $email = $info['email']; $phone = $info['phone']; $address_1 = $info['address']; $address_2 = $info['address2']; $company = $info['company']; $city = ""; $state = $info['state']; $postal_code = $info['postalCode']; $shipping_method_title = $info['shippingMethodTitle']; $shipping_method_id = $info['shippingMethodID']; $shipping_method_total = $info['shippingMethodTotal']; $payment_method_title = $info['paymentMethodTitle']; $payment_method_id = $info['paymentMethodID']; $order_comments = $info['orderComment']; $paymentIntent = $info['paymentIntentID']; $coupon_code = $info['couponCode']; $adjust_stock = $info['adjustStock']; $arr_item = array(); foreach($product['item'] as $item_info){ $stock_sku = get_master_sku($item_info['sku']); $unit_qty = 1; if(has_master_sku($item_info['sku'])){ $unit_qty = get_master_sku_unit_qty($item_info['sku']); $description = $item_info['productName']; }else{ $variation_id = $item_info['variationID']; if($variation_id!=0){ $description = $item_info['productName']; $unit_qty = get_variation_unit_qty($variation_id); }else{ $description = $item_info['productName']; $unit_qty = 1; } } $quantity = $item_info['quantity']*$unit_qty; /* if(get_sku_stock_by_date($stock_sku, $delivery_date) < $quantity) { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = $description." is out of stock in the selected date. Please select another delivery date"; } */ $arr_content = array(); $arr_content['quantity'] = $item_info['quantity']; $arr_content['args'] = array(); $arr_content['args']['sku'] = $item_info['sku']; $arr_content['args']['product_id'] = $item_info['productID']; $arr_content['args']['variation_id'] = $item_info['variationID']; $arr_content['args']['variation'] = array(); $arr_content['args']['subtotal'] = $item_info['productPrice']; $arr_content['args']['total'] = $item_info['quantity'] * $item_info['productPrice']; array_push($arr_item, $arr_content); } if($array_result['success']==true) { // build data array $order_id = create_wc_order( array( 'address' => array( 'first_name' => $first_name, 'last_name' => $last_name, 'company' => $company, 'email' => $email, 'phone' => $phone, 'address_1' => $address_1, 'address_2' => $address_2, 'city' => $city, 'state' => $state, 'postcode' => $postal_code, 'country' => 'HK', ), 'user_id' => $user_id, 'order_comments' => $order_comments, 'payment_method' => $payment_method_title, 'order_status' => array( 'status' => $status, //'status' => 'on-hold', 'note' => '', ), 'line_items' => $arr_item, 'coupon_items' => array( array( 'code' => $coupon_code ), ), 'shipping_lines' => array( 'method_id' => $shipping_method_id, 'method_title' => $shipping_method_title, 'total' => $shipping_method_total ), 'delivery_date' => $delivery_date, 'payment_intent' => $paymentIntent, 'customer_ip' => getCustomerIpAddr(), 'adjust_stock' => $adjust_stock ) ); if(isset($order_id) && $order_id>0) { $new_order = new WC_Order($order_id); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = $paymentIntent; //$array_result['message'] = "Order created: #".$order_id; $array_result['message'] = "Order# created: ".$new_order->get_order_number(); $array_result['id'] = $order_id; $array_result['number'] = $new_order->get_order_number(); } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] ="Fail to create order"; $array_result['id'] = 0; $array_result['number'] = ""; } } } if($section=="update_order") { global $wpdb; if($param['order_id']!="0" && $param['payment_intent']!="") { update_post_meta($param['order_id'], '_stripe_intent_id', $param['payment_intent']); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = $param['payment_intent']; $array_result['message'] = "Order Updated: #".$order_id; $array_result['id'] = intval($param['order_id']); } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] ="Fail to update order"; $array_result['id'] = 0; } } // no longer use if($section=="cancel_order") { global $wpdb; if($param['order_id']!="0") { $order = new WC_Order($param['order_id']); if (!empty($order)) { $order->update_status('cancelled'); //change_status_to_cancelled($param['order_id']); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Order is cancelled"; $array_result['id'] = intval($param['order_id']); } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Fail to cancel order"; $array_result['id'] = intval($param['order_id']) ; } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] ="Fail to cancel order"; $array_result['id'] = 0; } } // no longer use if($section=="mark_order_complete"){ $array_result = array(); if($param['order_id']!=""){ $orderDetail = new WC_Order( $param['order_id'] ); $orderDetail->update_status("wc-completed", 'Completed', TRUE); if($param['payment_method']!=""){ if(metadata_exists('post', $param['order_id'], 'Payment')) { update_post_meta($param['order_id'], 'Payment', $param['payment_method']); wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true); } else { add_post_meta($param['order_id'], 'Payment', $param['payment_method'], TRUE); wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true); } } $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] ="Order is marked as completed"; $array_result['id'] = intval($param['order_id']); }else{ $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] ="Fail to complete order"; $array_result['id'] = 0; } } // update order detail if($section=="update_order_detail"){ $array_result = array(); if(!empty($param['order_id'])){ $orderDetail = new WC_Order($param['order_id']); $oldStatus = $orderDetail->get_status(); $oldPaymenyMethod = get_post_meta($param['order_id'], 'Payment', true); if($param['status']=="on-hold" || $param['status']=="pending" || $param['status']=="processing"){ if($oldStatus!=$param['status']){ $orderDetail->update_status($param['status'], ucwords($param['status']), TRUE); } if($param['payment_method']!=""){ if(metadata_exists('post', $param['order_id'], 'Payment')) { update_post_meta($param['order_id'], 'Payment', $param['payment_method']); if($oldPaymenyMethod!=$param['payment_method']){ wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true); } } else { add_post_meta($param['order_id'], 'Payment', $param['payment_method'], TRUE); wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true); } } $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] ="Order data is updated"; $array_result['id'] = intval($param['order_id']); } elseif($param['status']=="completed") { if($oldStatus!=$param['status']){ $orderDetail->update_status("completed", 'Completed', TRUE); } if($param['payment_method']!=""){ if(metadata_exists('post', $param['order_id'], 'Payment')) { update_post_meta($param['order_id'], 'Payment', $param['payment_method']); if($oldPaymenyMethod!=$param['payment_method']){ wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true); } } else { add_post_meta($param['order_id'], 'Payment', $param['payment_method'], TRUE); wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true); } } $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] ="Order data is updated"; $array_result['id'] = intval($param['order_id']); } elseif($param['status']=="cancelled") { if($oldStatus!=$param['status']){ $orderDetail->update_status("cancelled", 'Cancelled', TRUE); } $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Order data is updated"; $array_result['id'] = intval($param['order_id']); } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] ="Unknow process"; $array_result['id'] = 0; } } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] ="Fail to change order status"; $array_result['id'] = 0; } } if($section=="product_list"){ $arr_holiday = get_holiday_list(); $url = "https://www.breadsecret.com/wp-json/wc/v3/products?consumer_key=".API_KEY."&consumer_secret=".API_SECRET."&orderby=id&order=desc&per_page=100&status=publish"; $stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d"); $content = file_get_contents($url); $api_product_data = json_decode($content, true); $today = date("Y-m-d"); if($today==$stock_date){ $isToday = true; } else { $isToday = false; } $array_result = array(); foreach($api_product_data as $api_product){ if($api_product['catalog_visibility'] == "visible"){ if($api_product['type']=="variable"){ foreach($api_product['variations'] as $idx=>$variation_id){ $array_product_result = array(); $array_product_result['id'] = intval($api_product['id']); $array_product_result['name'] = $api_product['name']; $zh_post_id = 0; $trid = $sitepress->get_element_trid($api_product['id'], 'post_product'); $translations = $sitepress->get_element_translations($trid, 'product'); foreach( $translations as $lang=>$translation){ if($translation->language_code == "zh-hant") $zh_post_id = $translation->element_id; } $array_product_result['id_zh'] = intval($zh_post_id); $array_product_result['name_zh'] = get_the_title($zh_post_id); $array_product_result['short_description_zh'] = get_the_excerpt($zh_post_id); $array_product_result['create_date'] = $api_product['date_created']; $array_product_result['categories'] = $api_product['categories']; $array_product_result['status'] = $api_product['status']; $array_product_result['catalog_visibility'] = $api_product['catalog_visibility']; $array_product_result['short_description'] = $api_product['short_description']; $array_product_result['sku'] = $api_product['sku']; $array_product_result['stock_date'] = $stock_date; $stock_sku = get_master_sku($api_product['sku']); //$array_product_result['stock_quantity'] = intval(get_sku_stock_by_date($stock_sku,$stock_date)); $array_product_result['stock_quantity'] = 999; $unit_qty = get_master_sku_unit_qty($api_product['sku']); $array_product_result['stock_sku'] = $stock_sku; $array_product_result['unit_qty'] = intval($unit_qty); //$limit = floor($array_product_result['stock_quantity']/$unit_qty); $limit = floor(intval(get_sku_stock_by_date($stock_sku,$stock_date))/$unit_qty); $array_product_result['stock_status'] = $api_product['stock_status']=="onbackorder"?"instock":$api_product['stock_status']; $notice = ""; $notice_zh = ""; $array_product_result['purchasable'] = true; if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){ $notice = "It's holiday today"; $notice_zh = "是日店休"; $array_product_result['purchasable'] = true; $array_product_result['color'] = "red"; }else{ // 0 = discontinued; 1 = selling; 2 = coming soon $init_status = check_stock_init($stock_sku, $stock_date); if($init_status == 0) { $notice = "Sales Ended"; $notice_zh = "售賣期已完結"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "gray"; } elseif($init_status == 2){ $notice = "Coming soon"; $notice_zh = "即將推出"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "blue"; } elseif($init_status == 1) { if($stock_date==date("Y-m-d") && date('H')>=16){ $notice = "Sold Out ".($isToday?'Today':''); $notice_zh = ($isToday?'今天已':'')."售罄"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "red"; }elseif($limit <= 0){ $notice = "Sold Out ".($isToday?'Today':''); $notice_zh = ($isToday?'今天已':'')."售罄"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "red"; }else{ $notice = $limit." Left"; $notice_zh = "餘".$limit."份"; $array_product_result['color'] = "yellow"; }/*else{ $notice = "In Stock"; $notice_zh = "有貨"; $array_product_result['color'] = "green"; }*/ } } $array_product_result['notice'] = $notice; $array_product_result['notice_zh'] = $notice_zh; $array_product_result['price'] = $api_product['price']; $array_product_result['unit'] = get_post_meta($api_product['id'], '_woo_uom_input', true); $array_product_result['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true); //$array_product_result['variations'] = $api_product['variations']; //$array_product_result['attributes'] = $api_product['attributes']; $array_product_result['variations'] = $variation_id; $array_product_result['attributes'] = $api_product['attributes'][0]['options'][$idx]; $array_product_result['images'] = $api_product['images']; //$array_product_result['stock_status'] = $api_product['stock_status']; $array_product_result['publish_date'] = get_the_date('Y-m-d', $api_product['id']); $array_product_result['sequence'] = get_sequence($stock_sku, $stock_date); $array_product_result['hasStock'] = ($limit>0)?((date("Y-m-d") == $stock_date && date("H")>=16)?"0":"1"):"0"; array_push($array_result, $array_product_result); } // end foreach } else { // simple product $array_product_result = array(); $array_product_result['id'] = intval($api_product['id']); $array_product_result['name'] = $api_product['name']; $zh_post_id = 0; $trid = $sitepress->get_element_trid($api_product['id'], 'post_product'); $translations = $sitepress->get_element_translations($trid, 'product'); foreach( $translations as $lang=>$translation){ if($translation->language_code == "zh-hant") $zh_post_id = $translation->element_id; } $array_product_result['id_zh'] = intval($zh_post_id); $array_product_result['name_zh'] = get_the_title($zh_post_id); $array_product_result['short_description_zh'] = get_the_excerpt($zh_post_id); $array_product_result['create_date'] = $api_product['date_created']; $array_product_result['categories'] = $api_product['categories']; $array_product_result['status'] = $api_product['status']; $array_product_result['catalog_visibility'] = $api_product['catalog_visibility']; $array_product_result['short_description'] = $api_product['short_description']; $array_product_result['sku'] = $api_product['sku']; $array_product_result['stock_date'] = $stock_date; $stock_sku = get_master_sku($api_product['sku']); $array_product_result['stock_quantity'] = 999; //$array_product_result['stock_quantity'] = intval(get_sku_stock_by_date($stock_sku,$stock_date)); $unit_qty = get_master_sku_unit_qty($api_product['sku']); $array_product_result['stock_sku'] = $stock_sku; $array_product_result['unit_qty'] = intval($unit_qty); //$limit = floor($array_product_result['stock_quantity']/$unit_qty); $limit = floor(intval(get_sku_stock_by_date($stock_sku,$stock_date))/$unit_qty); $array_product_result['stock_status'] = $api_product['stock_status']=="onbackorder"?"instock":$api_product['stock_status']; $notice = ""; $notice_zh = ""; $array_product_result['purchasable'] = true; if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){ $notice = "It's holiday today"; $notice_zh = "是日店休"; $array_product_result['purchasable'] = true; $array_product_result['color'] = "red"; }else{ // 0 = discontinued; 1 = selling; 2 = coming soon $init_status = check_stock_init($stock_sku, $stock_date); if($init_status == 0) { $notice = "Sales Ended"; $notice_zh = "售賣期已完結"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "gray"; } elseif($init_status == 2){ $notice = "Coming soon"; $notice_zh = "即將推出"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "blue"; } elseif($init_status == 1) { if($stock_date==date("Y-m-d") && date('H')>=16){ $notice = "Sold Out ".($isToday?'Today':''); $notice_zh = ($isToday?'今天已':'')."售罄"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "red"; }elseif($limit <= 0){ $notice = "Sold Out ".($isToday?'Today':''); $notice_zh = ($isToday?'今天已':'')."售罄"; //$array_product_result['purchasable'] = false; $array_product_result['purchasable'] = true; $array_product_result['color'] = "red"; }else{ $notice = $limit." Left"; $notice_zh = "餘".$limit."份"; $array_product_result['color'] = "yellow"; }/*else{ $notice = "In Stock"; $notice_zh = "有貨"; $array_product_result['color'] = "green"; }*/ } } $array_product_result['notice'] = $notice; $array_product_result['notice_zh'] = $notice_zh; $array_product_result['price'] = $api_product['price']; $array_product_result['unit'] = get_post_meta($api_product['id'], '_woo_uom_input', true); $array_product_result['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true); $array_product_result['variations'] = 0; $array_product_result['attributes'] = ""; $array_product_result['images'] = $api_product['images']; $array_product_result['publish_date'] = get_the_date('Y-m-d', $api_product['id']); $array_product_result['sequence'] = get_sequence($stock_sku, $stock_date); $array_product_result['hasStock'] = ($limit>0)?((date("Y-m-d") == $stock_date && date("H")>=16)?"0":"1"):"0"; //$array_product_result['stock_status'] = $api_product['stock_status']; array_push($array_result, $array_product_result); } } //end if } // end foreach usort($array_result,function($a,$b){ return $a['sequence'] <=> $b['sequence'] //first asc ?: $b['hasStock'] <=> $a['hasStock'] //second desc ?: $b['publish_date'] <=> $a['publish_date'] //third desc ?: $a['name'] <=> $b['name'] //forth asc ; }); } if($section=="get_payment_method_list") { $array_result = array(array('name'=>'')); foreach(get_customer_payment_method_list() as $payment_method){ $arr = array(); $arr['name'] = $payment_method; array_push($array_result, $arr); } } if($section=="get_customer_list"){ $array_result = array(); foreach(get_users() as $user){ $customer = new WC_Customer( $user->ID ); $arr_user = array(); $arr_user['customerID'] = $user->ID; $arr_user['firstName'] = $customer->get_shipping_first_name()==""?($customer->get_billing_first_name()==""?($customer->get_first_name()==""?$customer->get_display_name():$customer->get_first_name()):$customer->get_billing_first_name()):$customer->get_shipping_first_name(); $arr_user['lastName'] = $customer->get_shipping_last_name()==""?($customer->get_billing_last_name()==""?$customer->get_last_name():$customer->get_billing_last_name()):$customer->get_shipping_last_name(); $arr_user['email'] = $customer->get_billing_email()==""?$customer->get_email():$customer->get_billing_email(); $arr_user['phone'] = $customer->get_billing_phone(); $arr_user['state'] = $customer->get_shipping_state()==""?$customer->get_billing_state():$customer->get_shipping_state(); $arr_user['address'] = $customer->get_shipping_address_1()==""?$customer->get_billing_address_1():$customer->get_shipping_address_1(); $arr_user['company'] = $customer->get_shipping_company()==""?$customer->get_billing_company():$customer->get_shipping_company(); array_push($array_result, $arr_user); } } if($section=="customer_list"){ $array_result = array(); foreach(get_users() as $user){ $customer = new WC_Customer( $user->ID ); $arr_user = array(); $arr_user['customerID'] = $user->ID; $arr_user['firstName'] = $customer->get_first_name(); $arr_user['lastName'] = $customer->get_last_name(); $arr_user['email'] = $customer->get_email(); $arr_billing = array(); $arr_billing['first_name'] = $customer->get_billing_first_name(); $arr_billing['last_name'] = $customer->get_billing_last_name(); $arr_billing['company'] = $customer->get_billing_company(); $arr_billing['address_1'] = $customer->get_billing_address_1(); $arr_billing['address_2'] = $customer->get_billing_address_2(); $arr_billing['city'] = $customer->get_billing_city(); $arr_billing['state'] = $customer->get_billing_state(); $arr_billing['postcode'] = $customer->get_billing_postcode(); $arr_billing['country'] = $customer->get_billing_country(); $arr_billing['email'] = $customer->get_billing_email(); $arr_billing['phone'] = $customer->get_billing_phone(); $arr_user['billing_address'] = $arr_billing; $arr_shipping = array(); $arr_shipping['first_name'] = $customer->get_shipping_first_name(); $arr_shipping['last_name'] = $customer->get_shipping_last_name(); $arr_shipping['company'] = $customer->get_shipping_company(); $arr_shipping['address_1'] = $customer->get_shipping_address_1(); $arr_shipping['address_2'] = $customer->get_shipping_address_2(); $arr_shipping['city'] = $customer->get_shipping_city(); $arr_shipping['state'] = $customer->get_shipping_state(); $arr_shipping['postcode'] = $customer->get_shipping_postcode(); $arr_shipping['country'] = $customer->get_shipping_country(); $arr_user['shipping_address'] = $arr_shipping; array_push($array_result, $arr_user); } } // no longer used if($section=="daily_sku_stock") { $array_result = array(); $stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d"); $stockRecord = $wpdb->get_results("SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 "); foreach($stockRecord as $dataObj){ $dataArr = (Array)$dataObj; //loop all column name in the stock table (except id and stock date), in order to get the sku# automatically $skuList = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date')" ); foreach($skuList as $skuObj){ //create product object from sku# $arr_sku = array(); if(check_stock_init($skuObj->Field, $dataArr['stock_date'])){ //check if sku is already discontinued $product = wc_get_product(wc_get_product_id_by_sku($skuObj->Field)); $arr_sku['product_id'] = $product->get_id(); $arr_sku['sku'] = $skuObj->Field; $arr_sku['name'] = $product->get_name(); $zh_post_id = 0; $trid = $sitepress->get_element_trid($product->get_id(), 'post_product'); $translations = $sitepress->get_element_translations($trid, 'product'); foreach( $translations as $lang=>$translation){ if($translation->language_code == "zh-hant") $zh_post_id = $translation->element_id; } $arr_sku['name_zh'] = get_the_title($zh_post_id); $arr_sku['remain'] = floatval($dataArr[$skuObj->Field]); $arr_sku['production'] = get_production_qty($skuObj->Field, $dataArr['stock_date']); $arr_sku['stock_date'] = $dataArr['stock_date']; array_push($array_result, $arr_sku); } } } usort($array_result,function($a,$b){ return $a['name'] <=> $b['name']; }); } if($section=="sku_stock") { $array_result = array(); $stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d"); $arrSkuList = array(); $stockRecord = $wpdb->get_results("SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 "); foreach($stockRecord as $dataObj){ $dataArr = (Array)$dataObj; //loop all column name in the stock table (except id and stock date), in order to get the sku# automatically $skuList = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date','stock_dayofweek')" ); foreach($skuList as $skuObj){ //create product object from sku# $arr_sku = array(); $product_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $skuObj->Field) ); if ( $product_check ) { if(check_stock_init($skuObj->Field, $dataArr['stock_date'])){ //check if sku is already discontinued //array_push($arrSkuList, $skuObj->Field); $arrSkuList[$skuObj->Field] = true; } else { $product = wc_get_product(wc_get_product_id_by_sku($skuObj->Field)); $post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') ); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['stock_date']."'"); foreach ($result as $order_obj ){ $order = wc_get_order( $order_obj->ID ); foreach ( $order->get_items() as $item ) { if($item->get_product()->get_sku() == $product->get_sku()) { //array_push($arrSkuList, $product->get_sku()); $arrSkuList[$skuObj->Field] = false; } } } } } } } foreach($arrSkuList as $productSKU=>$editable){ $product = wc_get_product(wc_get_product_id_by_sku($productSKU)); $arr_sku['product_id'] = $product->get_id(); $arr_sku['sku'] = $productSKU; $arr_sku['name'] = $product->get_name(); $zh_post_id = 0; $trid = $sitepress->get_element_trid($product->get_id(), 'post_product'); $translations = $sitepress->get_element_translations($trid, 'product'); foreach( $translations as $lang=>$translation){ if($translation->language_code == "zh-hant") $zh_post_id = $translation->element_id; } $arr_sku['name_zh'] = get_the_title($zh_post_id); $checkStock = $wpdb->get_results("SELECT `".$productSKU."` FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 "); $stockObj = $checkStock[0]; $arr_sku['remain'] = floatval($stockObj->$productSKU); $arr_sku['production'] = get_production_qty($productSKU, $_GET['stock_date']); $arr_sku['stock_date'] = $_GET['stock_date']; $arr_sku['editable'] = $editable; array_push($array_result, $arr_sku); } usort($array_result,function($a,$b){ return $a['name'] <=> $b['name']; }); } if($section=="update_sku_stock") { global $wpdb; if($param['stock_date']==""){ $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Stock Date is Missing!"; $array_result['sku'] = $param['sku']; $array_result['stockDate'] = $param['stock_date']; $array_result['qty'] = floatval($param['qty']); } elseif($param['sku']=="") { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "SKU is Missing!"; $array_result['sku'] = $param['sku']; $array_result['stockDate'] = $param['stock_date']; $array_result['qty'] = floatval($param['qty']); } elseif($param['qty']==""){ $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Qty is Missing!"; $array_result['sku'] = $param['sku']; $array_result['stockDate'] = $param['stock_date']; $array_result['qty'] = floatval($param['qty']); } else { $sql = "SELECT * FROM sku_stock WHERE stock_date = '".$param['stock_date']."' LIMIT 1"; $result = $wpdb->get_results($sql); $data = (array)$result[0]; $oqty = floatval($data[$param['sku']]); if($wpdb->update('sku_stock', array( $param['sku'] => $param['qty']),array('stock_date'=>$param['stock_date']))){ $product = wc_get_product(wc_get_product_id_by_sku($param['sku'])); $sql_statement = "UPDATE sku_stock SET `".$param['sku']."` = '".$param['qty']."' WHERE stock_date = '".$param['stock_date']."' LIMIT 1"; write_log($param['stock_date'], "Adjust Stock", "Back End (Mobile)", "0", $param['sku'], esc_sql($product->get_name()), $oqty, $param['qty'], $param['user_id'], get_client_ip(), $sql_statement); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Stock Updated"; $array_result['sku'] = $param['sku']; $array_result['stockDate'] = $param['stock_date']; $array_result['qty'] = floatval($param['qty']); }else{ $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Fail to write data"; $array_result['sku'] = $param['sku']; $array_result['stockDate'] = $param['stock_date']; $array_result['qty'] = floatval($param['qty']); } } } if($section=="clear_sku_stock") { $array_result = array(); $stock_date = isset($param['stock_date']) && $param['stock_date']!=""?$param['stock_date']:date("Y-m-d"); $arrSkuList = array(); $stockRecord = $wpdb->get_results("SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 "); foreach($stockRecord as $dataObj){ $dataArr = (Array)$dataObj; //loop all column name in the stock table (except id and stock date), in order to get the sku# automatically $skuList = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date','stock_dayofweek')" ); foreach($skuList as $skuObj){ //create product object from sku# $arr_sku = array(); if(check_stock_init($skuObj->Field, $dataArr['stock_date'])){ //check if sku is already discontinued //array_push($arrSkuList, $skuObj->Field); $arrSkuList[$skuObj->Field] = true; } else { $product = wc_get_product(wc_get_product_id_by_sku($skuObj->Field)); $post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') ); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$stock_date."'"); foreach ($result as $order_obj ){ $order = wc_get_order( $order_obj->ID ); foreach ( $order->get_items() as $item ) { if($item->get_product()->get_sku() == $product->get_sku()) { //array_push($arrSkuList, $product->get_sku()); $arrSkuList[$skuObj->Field] = false; } } } } } } $success = true; foreach($arrSkuList as $productSKU=>$editable){ $product = wc_get_product(wc_get_product_id_by_sku($productSKU)); //$arr_sku['product_id'] = $product->get_id(); //$arr_sku['sku'] = $productSKU; //$arr_sku['name'] = $product->get_name(); $sql = "SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1"; $result = $wpdb->get_results($sql); $data = (array)$result[0]; $oqty = floatval($data[$productSKU]); if($wpdb->update('sku_stock', array( $productSKU => 0),array('stock_date'=>$stock_date))){ $sql_statement = "UPDATE sku_stock SET `".$productSKU."` = 0 WHERE stock_date = '".$stock_date."' LIMIT 1"; write_log($stock_date, "Clear Stock", "Back End (Mobile)", "0", $productSKU, esc_sql($product->get_name()), $oqty, 0, $param['user_id'], get_client_ip(), $sql_statement); } /*else { $success = false; } */ } if($success==true) { $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "Success"; $array_result['message'] = "Stock Updated"; $array_result['stockDate'] = $stock_date; } else { $array_result['success'] = false; $array_result['statusCode'] = 200; $array_result['code'] = "Error"; $array_result['message'] = "Fail to write data"; $array_result['stockDate'] = $stock_date; } } // no longer used if($section=="daily_production_summary") { global $wpdb; $post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') ); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'"); $free_gift = 0; $summary = array(); foreach ($result as $order_obj ){ //get order object from order id $order = wc_get_order( $order_obj->ID ); $ship_method = $order->get_shipping_method(); if($ship_method=="送貨" || $ship_method=="Delivery"){ $display_ship_method = "Delivery"; //$display_delivery_region = true; }elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="自取" || $ship_method=="Pick-up"){ $display_ship_method = "Pick-up"; }elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) { $display_ship_method = "Collect"; //$display_pickup_location = true; }else{ $display_ship_method = $ship_method; } $delivery_date = $order->get_meta('delivery_date', true); if($delivery_date == $_GET['delivery_date']){ //free gift period is from 5/2/2021 to 11/2/2021 $date = new DateTime("02/12/2021"); //check for free gift, order $ >= 300, and order date is before 12/2/2021. if($order->get_subtotal() >= 300 && $order->get_date_created()<$date) $free_gift++; $arr_qyt_by_ship_method = array(); foreach ( $order->get_items() as $item ) { //print each order line item $array_line = array(); $prod = $item->get_product(); $sku = $prod->get_sku(); $variation_id = $item->get_variation_id(); $variation = new WC_Product_Variation($variation_id); // get variation object from variation id $variationName = implode(" / ", $variation->get_variation_attributes()); // get variation name from ariation object $product = wc_get_product(wc_get_product_id_by_sku($sku)); if($variation_id!=0){ $id = $product->get_name()." - ".$variationName; // make a unique key }else{ $id = $product->get_name(); // make a unique key } $summary[$id]['variationName'] = $variationName; $summary[$id]['productID']=$item->get_product_id(); if (array_key_exists($id, $summary)) { //product id already exist in summary array, then add ordered qty to its corresonding array value $summary[$id]['qty']+=$item->get_quantity(); }else{ $summary[$id]['qty']=$item->get_quantity(); //insert new product id to summary array } $summary[$id]['method'][$display_ship_method]+=$item->get_quantity(); } } } ksort($summary); //print_r($summary); $array_data = array(); foreach($summary as $name => $contentObj){ $line = array(); $line['product'] = $name; $trid = $sitepress->get_element_trid($contentObj['productID'], 'post_product'); $translations = $sitepress->get_element_translations($trid, 'product'); foreach( $translations as $lang=>$translation){ if($translation->language_code == "zh-hant") $zh_post_id = $translation->element_id; } $line['product_zh'] = get_the_title($zh_post_id); //$line['post_id'] = $zh_post_id; $line['variation_name'] = $contentObj['variationName']; //$line['product_zh'] = $contentObj['productID']; $line['counts'] = intval($contentObj['qty']); $line['method'] = array(); foreach($contentObj['method'] as $methodName => $qty){ $method_line = array('name'=>$methodName, 'quantity'=>intval($qty)); array_push($line['method'], $method_line); } array_push($array_data, $line); } $array_result = $array_data; } if($section=="production_summary") { global $wpdb; $post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') ); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'"); $free_gift = 0; $summary = array(); foreach ($result as $order_obj ){ //get order object from order id $order = wc_get_order( $order_obj->ID ); $ship_method = $order->get_shipping_method(); if($ship_method=="送貨" || $ship_method=="Delivery"){ $display_ship_method = "Delivery"; //$display_delivery_region = true; }elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="自取" || $ship_method=="Pick-up"){ $display_ship_method = "Pick-up"; }elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) { $display_ship_method = "Collect"; //$display_pickup_location = true; }else{ $display_ship_method = $ship_method; } $delivery_date = $order->get_meta('delivery_date', true); if($delivery_date == $_GET['delivery_date']){ //free gift period is from 5/2/2021 to 11/2/2021 $date = new DateTime("02/12/2021"); //check for free gift, order $ >= 300, and order date is before 12/2/2021. if($order->get_subtotal() >= 300 && $order->get_date_created()<$date) $free_gift++; $arr_qyt_by_ship_method = array(); foreach ( $order->get_items() as $item ) { //print each order line item $array_line = array(); $prod = $item->get_product(); $sku = $prod->get_sku(); $variation_id = $item->get_variation_id(); $variation = new WC_Product_Variation($variation_id); // get variation object from variation id $variationName = implode(" / ", $variation->get_variation_attributes()); // get variation name from ariation object $product = wc_get_product(wc_get_product_id_by_sku($sku)); if($variation_id!=0){ $id = $product->get_name()." - ".$variationName; // make a unique key }else{ $id = $product->get_name(); // make a unique key } $summary[$id]['variationName'] = $variationName; $summary[$id]['productID']=$item->get_product_id(); $summary[$id]['variationID'] = $variation_id; if (array_key_exists($id, $summary)) { //product id already exist in summary array, then add ordered qty to its corresonding array value $summary[$id]['qty']+=$item->get_quantity(); }else{ $summary[$id]['qty']=$item->get_quantity(); //insert new product id to summary array } $summary[$id]['method'][$display_ship_method]+=$item->get_quantity(); } } } ksort($summary); //print_r($summary); $array_data = array(); foreach($summary as $name => $contentObj){ $line = array(); $line['product'] = $name; $trid = $sitepress->get_element_trid($contentObj['productID'], 'post_product'); $translations = $sitepress->get_element_translations($trid, 'product'); foreach( $translations as $lang=>$translation){ if($translation->language_code == "zh-hant") $zh_post_id = $translation->element_id; } $line['product_id'] = $contentObj['productID']; $line['variation_id'] = $contentObj['variationID']; $line['product_zh'] = get_the_title($zh_post_id); //$line['post_id'] = $zh_post_id; $line['variation_name'] = $contentObj['variationName']; //$line['product_zh'] = $contentObj['productID']; $line['total'] = intval($contentObj['qty']); $line['pickup'] = intval($contentObj['method']['Pick-up']); $line['collect'] = intval($contentObj['method']['Collect']); $line['delivery'] = intval($contentObj['method']['Delivery']); /* $line['method'] = array(); foreach($contentObj['method'] as $methodName => $qty){ $method_line = array('name'=>$methodName, 'quantity'=>intval($qty)); array_push($line['method'], $method_line); } */ array_push($array_data, $line); } $array_result = $array_data; } if($section=="production_summary_detail") { global $wpdb; $array_result = array(); $post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') ); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'"); $free_gift = 0; $summary = array(); foreach ($result as $order_obj ){ //get order object from order id $order = wc_get_order( $order_obj->ID ); $ship_method = $order->get_shipping_method(); if($ship_method=="送貨" || $ship_method=="Delivery"){ $display_ship_method = "Delivery"; //$display_delivery_region = true; }elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="自取" || $ship_method=="Pick-up"){ $display_ship_method = "Pick-up"; }elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) { $display_ship_method = "Collect"; //$display_pickup_location = true; }else{ $display_ship_method = $ship_method; } $delivery_date = $order->get_meta('delivery_date', true); $qty = 0; $show = false; foreach ( $order->get_items() as $item ) { //print each order line item if($item->get_product_id() == $_GET['product_id'] && $item->get_variation_id() == $_GET['variation_id']){ $show = true; $qty = $item->get_quantity(); } } if ($show) { $orderArr = array(); $orderArr['id'] = $order->get_id(); $orderArr['number'] = $order->get_order_number(); $orderArr['date_created'] = date("Y-m-d\TH:i:s", strtotime($order_obj->post_date)); $orderArr['delivery_date'] = get_post_meta($order->get_id(), 'delivery_date', true); $orderArr['total'] = $order->get_total(); $orderArr['status'] = $order->get_status(); $orderArr['ship_method'] = $display_ship_method; $orderArr['billing_first_name'] = $order->get_billing_first_name(); $orderArr['billing_last_name'] = $order->get_billing_last_name(); $orderArr['billing_company'] = $order->get_billing_company(); $orderArr['billing_email'] = $order->get_billing_email(); $orderArr['billing_phone'] = $order->get_billing_phone(); $orderArr['shipping_phone'] = get_post_meta($order->get_id(), '_shipping_phone', true); $orderArr['qty'] = $qty; array_push($array_result, $orderArr); } } // $array_result = $array_data; } if($section=="sku_stock_detail") { global $wpdb; $array_result = array(); $post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') ); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'"); $free_gift = 0; $summary = array(); foreach ($result as $order_obj ){ //get order object from order id $order = wc_get_order( $order_obj->ID ); $ship_method = $order->get_shipping_method(); if($ship_method=="送貨" || $ship_method=="Delivery"){ $display_ship_method = "Delivery"; //$display_delivery_region = true; }elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){ $display_ship_method = "Delivery"; //$display_pickup_location = true; }elseif($ship_method=="自取" || $ship_method=="Pick-up"){ $display_ship_method = "Pick-up"; }elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) { $display_ship_method = "Collect"; //$display_pickup_location = true; }else{ $display_ship_method = $ship_method; } $delivery_date = $order->get_meta('delivery_date', true); $qty = 0; $show = false; $productMaster = wc_get_product($_GET['product_id']); $sku = $productMaster->get_sku(); foreach ( $order->get_items() as $item ) { //print each order line item $product = $item->get_product(); $stock_sku = get_master_sku($product->get_sku()); $unit_qty = 1; if(has_master_sku($product->get_sku())){ $unit_qty = get_master_sku_unit_qty($product->get_sku()); //get master sku unit qty }else{ $variation_id = $item->get_variation_id(); if($variation_id!=0){ $unit_qty = get_variation_unit_qty($variation_id); //get variation unit qty }else{ $unit_qty = 1; } } if($stock_sku == $sku){ $show = true; $qty = $item->get_quantity()*$unit_qty; } } if ($show) { $orderArr = array(); $orderArr['id'] = $order->get_id(); $orderArr['number'] = $order->get_order_number(); $orderArr['date_created'] = date("Y-m-d\TH:i:s", strtotime($order_obj->post_date)); $orderArr['delivery_date'] = get_post_meta($order->get_id(), 'delivery_date', true); $orderArr['total'] = $order->get_total(); $orderArr['status'] = $order->get_status(); $orderArr['ship_method'] = $display_ship_method; $orderArr['billing_first_name'] = $order->get_billing_first_name(); $orderArr['billing_last_name'] = $order->get_billing_last_name(); $orderArr['billing_company'] = $order->get_billing_company(); $orderArr['billing_email'] = $order->get_billing_email(); $orderArr['billing_phone'] = $order->get_billing_phone(); $orderArr['shipping_phone'] = get_post_meta($order->get_id(), '_shipping_phone', true); $orderArr['qty'] = floatval($qty); array_push($array_result, $orderArr); } } // $array_result = $array_data; } if($section=="sales_summary") { global $wpdb; $array_result = array(); $post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') ); $result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value LIKE '".$_GET['year']."%'"); //$array_result = array(10000,11000,12000,33330,44440,22220,50000,70000,72000,67000,80000,0); $array_result = array(0,0,0,0,0,0,0,0,0,0,0,0); foreach ($result as $order_obj ){ $order = wc_get_order( $order_obj->ID ); $delivery_date = $order->get_meta('delivery_date', true); $month = date("n",strtotime($delivery_date)); $index = $month - 1; $total = $order->get_total(); $refund = get_post_meta($order_obj->ID, "_refund_amount", true)==""?0:get_post_meta($order_obj->ID, "_refund_amount", true); $net_total = $total - $refund; $array_result[$index] += $net_total; } } // testing use only if($section=="create_order_test") { sleep(5); $array_result['success'] = true; $array_result['statusCode'] = 200; $array_result['code'] = "TEST CODE"; //$array_result['message'] = "Order created: #".$order_id; $array_result['message'] = "Order# created: TEST"; $array_result['id'] = 1111; $array_result['number'] = "Test"; } } echo json_encode($array_result); ?>