File: /var/www/html/breadsecret.com/ajax_data.php.bak20240112
<?php
//include wp libriries and set timezone to HK
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
require_once('wp-load.php');
session_start();
date_default_timezone_set("Asia/Hong_Kong");
global $wpdb, $sitepress;
/*
By Samiel on 2021-03-03
function to get new order information in every ? seconds
critiria:
(1) order date = today
(2) delivery date = today
(3) message not yet read
*/
if($_POST['section']=="get_today_new_order"){
//get today date (remember to set timezone to HK)
$today = date('Y-m-d');
$arr_result = array();
//order status to check...
$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed'));
//find order matched critria (1)
$result = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'shop_order' AND post_status IN ('{$post_status}') AND post_date LIKE '".$today."%'");
//loop all found orders
foreach ($result as $order_obj ){
$order = wc_get_order($order_obj->ID);
//get order delivery date from order meta table
$delivery_date = $order->get_meta('delivery_date', true);
// if delivery date is today
if($delivery_date == $today ){
//check if the order is already notified
$master_read_record = $wpdb->get_results("SELECT * FROM `notification_master_read` WHERE order_id = '".$order_obj->ID."' LIMIT 1");
if(count($master_read_record)==0){
//check if the order is notified by specific user
$user_read_record = $wpdb->get_results("SELECT * FROM `notification_user_read` WHERE order_id = '".$order_obj->ID."' AND user_id = '".$_POST['user_id']."' LIMIT 1");
if(count($user_read_record)==0){
$order = wc_get_order( $order_obj->ID );
$arr_ord = array();
$arr_ord['order_id'] = $order_obj->ID;
$arr_ord['order_number'] = $order->get_order_number();
$arr_ord['product'] = array();
//loop all line item in order
foreach ( $order->get_items() as $item ) {
//get line item product info.
$prod = $item->get_product();
$sku = $prod->get_sku();
// get variation name
$variation_id = $item->get_variation_id();
$variation = new WC_Product_Variation($variation_id);
$variationName = implode(" / ", $variation->get_variation_attributes());
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if($variation_id!=0){
$prod_name = $product->get_name()." - ".$variationName;
}else{
$prod_name = $product->get_name();
}
$arr_item = array();
$arr_item['name'] = $prod_name;
$arr_item['qty'] = $item->get_quantity();
$arr_ord['product'][]= $arr_item;
}
array_push($arr_result,$arr_ord);
}
}
}
}
//return result to ajax call in json format
echo json_encode($arr_result);
}
/*
By Samiel on 2021-03-03 // last edit : 2021-05-11
function to let system know an order notification is already read and do not display again
*/
if($_POST['section']=="remove_notification"){
$json = str_replace("\\","",$_POST['order_id']);
foreach(json_decode($json) as $ord_id){
$wpdb->replace('notification_master_read', array(
'order_id' => $ord_id,
'status' => 1
)
);
}
}
/*
By Samiel on 2021-03-03 // last edit : 2021-05-11
function to let system know an order notification is already read by specific user
*/
if($_POST['section']=="read_notification"){
$json = str_replace("\\","",$_POST['order_id']);
foreach(json_decode($json) as $ord_id){
$wpdb->replace('notification_user_read', array(
'order_id' => $ord_id,
'user_id' => $_POST['user_id'],
'status' => 1
)
);
}
}
/*
By Samiel on 2021-03-11
function to adjust sku stock in sku stock page
*/
if($_POST['section']=="adjust_sku_stock"){
$arr_result = array();
if($wpdb->update('sku_stock', array( $_POST['sku'] => $_POST['nqty']),array('stock_date'=>$_POST['stock_date']))){
$arr_result['condition']='success';
$arr_result['callout'] = $_POST['nqty'];
$arr_result['id'] = $_POST['sku']."__".$_POST['stock_date'];
$product = wc_get_product(wc_get_product_id_by_sku($_POST['sku']));
$sql_statement = "UPDATE sku_stock SET `".$_POST['sku']."` = '".$_POST['nqty']."' WHERE stock_date = '".$_POST['stock_date']."' LIMIT 1";
write_log($_POST['stock_date'], "Adjust Stock", "Back End", "0", $_POST['sku'], esc_sql($product->get_name()), $_POST['oqty'], $_POST['nqty'], $_POST['user_id'], get_client_ip(), $sql_statement);
}else{
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
/*
By Samiel on 2021-04-07
function to mark an order is completed in order summary page
*/
if($_POST['section']=="mark_completed"){
$arr_result = array();
$arr_result['id'] = $_POST['ord_id'];
if($_POST['ord_id']!=""){
$order = wc_get_order($_POST['ord_id']);
$arr_result['number'] = $order->get_order_number();
$orderDetail = new WC_Order( $_POST['ord_id'] );
$orderDetail->update_status("wc-completed", 'Completed', TRUE);
if($_POST['payment']!=""){
if(metadata_exists('post', $_POST['ord_id'], 'Payment')) {
update_post_meta($_POST['ord_id'], 'Payment', $_POST['payment']);
wc_create_order_note($_POST['ord_id'], "Payment: ".sanitize_text_field( $_POST['payment'] ), false, true);
} else {
add_post_meta($_POST['ord_id'], 'Payment', $_POST['payment'], TRUE);
wc_create_order_note($_POST['ord_id'], "Payment: ".sanitize_text_field( $_POST['payment'] ), false, true);
}
}
$arr_result['condition'] = "success";
}else{
$arr_result['condition'] = "fail";
}
echo json_encode($arr_result);
}
/*
By Samiel on 2021-05-07
function to check payment and load a customer payment method list
*/
if($_POST['section']=="check_payment"){
$arr_result = array();
$arr_result['id'] = $_POST['ord_id'];
if($_POST['ord_id']!=""){
$order = new WC_Order( $_POST['ord_id'] );
$arr_result['payment'] = $order->get_payment_method_title();
$arr_result['number'] = $order->get_order_number();
$button = "<br><p class='woocommerce'>";
$button .= "<button style='font-size:10px; float:right;line-height: 25px !important;height: 25px !important;margin-top: -22px;padding: 0px 10px 0px 10px;' class='button btn_ok' id='btn_ok_".$_POST['ord_id']."'>Confirm<button>";
//$button .= "<button style='float:right;line-height: 30px !important;height: 30px !important;' class='button btn_cancel' id='btn_cancel_".$_POST['ord_id']."'>CANCEL<button>";
$button .= "</p>";
$content = "<br>";
if($arr_result['payment']!="Credit Card (Stripe)" && $arr_result['payment']!="AlipayHK" && $arr_result['payment']!="WeChat Pay" && strpos($arr_result['payment'],"FiberConnect")===false){
$custom_payment_method_list = get_customer_payment_method_list();
if(count($custom_payment_method_list) > 0 ){
$content .= "Paid by: <select name='customer_payment_method' id='select_".$_POST['ord_id']."'>";
foreach($custom_payment_method_list as $custom_payment_method){
$selected_custom_payment_method = get_post_meta($_POST['ord_id'], 'Payment', true);
$content .= "<option value='".$custom_payment_method."' ";
if($custom_payment_method==$selected_custom_payment_method)
$content .= "selected";
$content .= ">".$custom_payment_method."</option>";
}
$content .= "</select>";
}
}
$arr_result['content'] = $content.$button;
$arr_result['condition'] = "success";
}else{
$arr_result['condition'] = "fail";
}
echo json_encode($arr_result);
}
/*
By Samiel on 2021-08-16
Last updated by Sameil on 2022-03-02
function to update stock status label of each product in STORE page
*/
if($_POST['section']=="update_stock_notice"){
$arr_result = array();
$arr_result['condition'] = "success";
$arr_result['content'] = array();
$date = $_POST['date'];
$lang = $_POST['lang'];
$today = date("Y-m-d");
if($today == $date) {
$isToday = true;
} else {
$isToday = false;
}
$data = json_decode(str_replace("\\", "", $_POST['data']));
//$arr_result['data'] = $data;
foreach($data as $item){
$arr_key = explode("_",$item);
$product_id = $arr_key[0];
$sku = $arr_key[2];
$sku_result = array();
$notice = "";
//if(in_array($date, $arr_holiday) || date('N',strtotime($date))==7){ // check if today is in holiday list
if(in_array($date, $arr_holiday) || (date('N',strtotime($date))==7 && $date!="2022-10-30")){ // check if today is in holiday list
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-outofstock'>是日店休</p>";
}else{
$sku_result['notice'] = "<p class='status-outofstock'>It's holiday today</p>";
}
}else{
$stock_sku = get_master_sku($sku);
$unit_qty = get_master_sku_unit_qty($sku);
$result = $wpdb->get_results("SELECT `".$stock_sku."` FROM sku_stock WHERE stock_date = '".$date."' LIMIT 1");
$init_info = get_sku_init_info($stock_sku);
$end_date = $init_info->end_date;
$array = (array) $result[0];
$limit = floor($array[$stock_sku]/$unit_qty);
if(check_stock_init($stock_sku, $date)==1){ // within selling period
$earliest_date = get_earliest_available_date($sku);
if(count($result)>0){
if(date("Y-m-d") == $date && date("H")>=16){
$sku_result['cartContent'] = "none";
if ($lang == 'chi') {
//$sku_result['notice'] = "<p class='status-outofstock'>".($isToday?'今天已':'')."售罄</p>";
$sku_result['notice'] = "<p class='status-outofstock'>".($earliest_date==false?'售罄':'售罄。最早有貨日期: '.$earliest_date)."</p>";
}else{
//$sku_result['notice'] = "<p class='status-outofstock'>Sold Out ".($isToday?'Today':'')."</p>";
$sku_result['notice'] = "<p class='status-outofstock'>".($earliest_date==false?'Sold out':'Sold out. Next Available Date: '.$earliest_date)."</p>";
}
}elseif($limit<=0){
$sku_result['cartContent'] = "none";
if($end_date==$date){ // check if last date of selling
if ($lang == 'chi') {
//$sku_result['notice'] = "<p class='status-outofstock'>".($isToday?'今天已':'')."售罄</p>";
$sku_result['notice'] = "<p class='status-outofstock'>".($earliest_date==false?'售罄':'售罄。最早有貨日期: '.$earliest_date)."</p>";
}else{
//$sku_result['notice'] = "<p class='status-outofstock'>Sold Out ".($isToday?'Today':'')."</p>";
$sku_result['notice'] = "<p class='status-outofstock'>".($earliest_date==false?'Sold out':'Sold out. Next Available Date: '.$earliest_date)."</p>";
}
}else{
if ($lang == 'chi') {
//$sku_result['notice'] = "<p class='status-outofstock'>".($isToday?'今天已':'')."售罄</p>";
$sku_result['notice'] = "<p class='status-outofstock'>".($earliest_date==false?'售罄':'售罄。最早有貨日期: '.$earliest_date)."</p>";
}else{
//$sku_result['notice'] = "<p class='status-outofstock'>Sold Out ".($isToday?'Today':'')."</p>";
$sku_result['notice'] = "<p class='status-outofstock'>".($earliest_date==false?'Sold out':'Sold out. Next Available Date: '.$earliest_date)."</p>";
}
}
}elseif($limit<=3){
$sku_result['cartContent'] = "block";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-littlestock'>餘".$limit."份</p>";
}else{
$sku_result['notice'] = "<p class='status-littlestock'>".$limit." Left</p>";
}
}else{
$sku_result['cartContent'] = "block";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-instock'>有貨</p>";
}else{
$sku_result['notice'] = "<p class='status-instock'>In Stock</p>";
}
}
}
} elseif(check_stock_init($stock_sku, $date)==0) {
$sku_result['cartContent'] = "none";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-ended'>限定期間已售完</p>";
}else{
$sku_result['notice'] = "<p class='status-ended'>Sales Ended</p>";
}
} elseif(check_stock_init($stock_sku, $date)==2) {
$sku_result['cartContent'] = "none";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-coming'>即將推出</p>";
}else{
$sku_result['notice'] = "<p class='status-coming'>Coming Soon</p>";
}
}
}
$sku_result['id'] = $item;
$sku_result['cartContentID'] = "cart_".$product_id;
array_push($arr_result['content'], $sku_result);
} // end for each item
echo json_encode($arr_result);
}
/*
if($_POST['section']=="update_stock_notice"){
$arr_result = array();
$arr_result['condition'] = "success";
$arr_result['content'] = array();
$date = $_POST['date'];
$lang = $_POST['lang'];
$today = date("Y-m-d");
if($today == $date) {
$isToday = true;
} else {
$isToday = false;
}
$data = json_decode(str_replace("\\", "", $_POST['data']));
//$arr_result['data'] = $data;
foreach($data as $item){
$arr_key = explode("_",$item);
$product_id = $arr_key[0];
$sku = $arr_key[2];
$sku_result = array();
$notice = "";
if(in_array($date, $arr_holiday) || date('N',strtotime($date))==7){ // check if today is in holiday list
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='b50442'>是日店休</p>";
}else{
$sku_result['notice'] = "<p class='b50442'>It's holiday today</p>";
}
}else{
$stock_sku = get_master_sku($sku);
$unit_qty = get_master_sku_unit_qty($sku);
$result = $wpdb->get_results("SELECT `".$stock_sku."` FROM sku_stock WHERE stock_date = '".$date."' LIMIT 1");
$init_info = get_sku_init_info($stock_sku);
$end_date = $init_info->end_date;
$array = (array) $result[0];
$limit = floor($array[$stock_sku]/$unit_qty);
if(check_stock_init($stock_sku, $date)==1){ // within selling period
if(count($result)>0){
if(date("Y-m-d") == $date && date("H")>=16){
$sku_result['cartContent'] = "none";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-outofstock'>".($isToday?'今天已':'')."售罄</p>";
}else{
$sku_result['notice'] = "<p class='status-outofstock'>Sold Out ".($isToday?'Today':'')."</p>";
}
}elseif($limit<=0){
$sku_result['cartContent'] = "none";
if($end_date==$date){ // check if last date of selling
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-outofstock'>".($isToday?'今天已':'')."售罄</p>";
}else{
$sku_result['notice'] = "<p class='status-outofstock'>Sold Out ".($isToday?'Today':'')."</p>";
}
}else{
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-outofstock'>".($isToday?'今天已':'')."售罄</p>";
}else{
$sku_result['notice'] = "<p class='status-outofstock'>Sold Out ".($isToday?'Today':'')."</p>";
}
}
}elseif($limit<=3){
$sku_result['cartContent'] = "block";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-littlestock'>餘".$limit."份</p>";
}else{
$sku_result['notice'] = "<p class='status-littlestock'>".$limit." Left</p>";
}
}else{
$sku_result['cartContent'] = "block";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-instock'>有貨</p>";
}else{
$sku_result['notice'] = "<p class='status-instock'>In Stock</p>";
}
}
}
} elseif(check_stock_init($stock_sku, $date)==0) {
$sku_result['cartContent'] = "none";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-ended'>限定期間已售完</p>";
}else{
$sku_result['notice'] = "<p class='status-ended'>Sales Ended</p>";
}
} elseif(check_stock_init($stock_sku, $date)==2) {
$sku_result['cartContent'] = "none";
if ($lang == 'chi') {
$sku_result['notice'] = "<p class='status-coming'>即將推出</p>";
}else{
$sku_result['notice'] = "<p class='status-coming'>Coming Soon</p>";
}
}
}
$sku_result['id'] = $item;
$sku_result['cartContentID'] = "cart_".$product_id;
array_push($arr_result['content'], $sku_result);
} // end for each item
echo json_encode($arr_result);
}
*/
/*
By Samiel on 2021-08-16
function to set session variable
*/
if($_POST['section']=="set_session_variable"){
if(isset($_POST['field']) && $_POST['field']!=""){
if(isset($_POST['value']) && $_POST['value']!=""){
$_SESSION[$_POST['field']] = $_POST['value'];
}
}
}
/*
By Samiel on 2021-08-24
function for wholeseller page setting
*/
if($_POST['section']=="edit_sku_wholesaler_field"){
$arr_result = array();
if($_POST['period']!="" && $_POST['sku']!="" && $_POST['field_name']!=""){
if($_POST['ovalue']!=$_POST['nvalue']){
$arr_result['id'] = $_POST['field_name']."_".$_POST['period']."_".$_POST['sku'];
switch($_POST['field_name']){
case "factor":
$field = "price_factor";
break;
case "lowerlimit":
$field = "lower_limit";
break;
case "upperlimit":
$field = "upper_limit";
break;
case "visibility":
$field = "visibility";
break;
default:
$field = "";
break;
}
if($wpdb->update('sku_wholesaler', array( $field => $_POST['nvalue']),array('sku_id'=>$_POST['sku'], 'period_id'=>$_POST['period']))){
$arr_result['condition'] = 'success';
$arr_result['callout'] = $_POST['nvalue'];
} else {
if($wpdb->insert('sku_wholesaler', array('period_id' => $_POST['period'], 'sku_id' => $_POST['sku'], $field => $_POST['nvalue']))){
$arr_result['condition'] = 'success';
$arr_result['callout'] = $_POST['nvalue'];
} else {
$arr_result['condition']='fail';
}
}
} else {
$arr_result['condition']='fail';
}
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_sku_wholesaler_period"){
$arr_result = array();
if($_POST['period']!=""){
if($_POST['field']!=""){
if($_POST['value']!=""){
if($wpdb->update('sku_wholesaler_period', array( $_POST['field'] => $_POST['value']),array('id'=>$_POST['period']))){
$arr_result['condition'] = 'success';
} else {
$arr_result['condition'] = 'fail';
}
} else {
$arr_result['condition']='fail';
}
} else {
$arr_result['condition']='fail';
}
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="remove_sku_wholesaler_period"){
$arr_result = array();
if($_POST['id']!=""){
if($wpdb->update('sku_wholesaler_period', array( 'status' => 0),array('id'=>$_POST['id']))){
$arr_result['condition'] = 'success';
} else {
$arr_result['condition'] = 'fail';
}
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="add_sku_wholesaler_period"){
$arr_result = array();
if($wpdb->insert('sku_wholesaler_period', array( 'status' => 1))){
$arr_result['condition'] = 'success';
$arr_result['id'] = $wpdb->insert_id;
} else {
$arr_result['condition'] = 'fail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="sku_init"){
if(isset($_POST['show_in_home_page'])){
$show_in_home_page = "1";
} else {
$show_in_home_page = "0";
}
if(isset($_POST['show_in_app'])){
$show_in_app = "Y";
} else {
$show_in_app = "N";
}
if(isset($_POST['show_in_preparation_list'])){
$show_in_preparation_list = "Y";
} else {
$show_in_preparation_list = "N";
}
if(isset($_POST['init_stock'])){
//$init_stock = true;
$init_stock = "Y";
} else {
//$init_stock = false;
$init_stock = "N";
}
/*
$product_id = wc_get_product_id_by_sku($_POST['sku']);
$zh_product_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_product_id = $translation->element_id;
}
*/
$holiday_list = get_holiday_list();
$arr_result = array();
if($_POST['action']=="Add"){
if(trim($_POST['sku'])=="") {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing SKU";
} elseif($_POST['start_date']=="") {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing Start Date";
} elseif($_POST['limits']=="") {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing Limit";
} else {
$product_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", trim($_POST['sku'])) );
if ( $product_check ) {
$result = $wpdb->get_results("SELECT * FROM stock_init WHERE sku = '".trim($_POST['sku'])."' LIMIT 1");
if(count($result)>0){
$arr_result['condition'] = "fail";
$arr_result['message'] = "SKU already exist";
} else {
$block_date_from_holiday = "0";
$arr_block_date_from_holiday = array_map('trim', explode(',', $_POST['block_date_from_holiday']));
if(trim($_POST['block_date_from_holiday'])!=""){
$block_date_from_holiday .= ",".implode(",",$arr_block_date_from_holiday);
}
if($wpdb->insert('stock_init',
array(
'sku' => $_POST['sku'],
'description' => $_POST['description'],
'start_date' => $_POST['start_date'] ,
'end_date' => $_POST['end_date'],
'block_date_from_holiday' => $block_date_from_holiday,
'block_dayofweek' => implode(",",$_POST['block_dayofweek']),
'limits' => $_POST['limits'],
'min_production_qty' => $_POST['min_production_qty'],
'oven_qty' => $_POST['oven_qty'],
'bake_qty_per_round' => $_POST['bake_qty_per_round'],
'display_unit' => $_POST['display_unit'],
'packing_unit' => $_POST['packing_unit'],
'unit_qty' => $_POST['unit_qty'],
'custom_formula' => $_POST['custom_formula'],
'show_in_app' => $show_in_app,
'show_in_preparation_list' => $show_in_preparation_list,
'remark' => $_POST['remark'],
'ingredient' => $_POST['ingredient'],
'preparation_day' => $_POST['preparation_day'],
'init_stock' => $init_stock
))
){
if($wpdb->insert('sku_wholesaler_sku',
array(
'sku' => $_POST['sku'],
'remark' => $_POST['description']
))
){
if(has_slave_sku($_POST['sku'])){
$skus = get_salve_sku($_POST['sku']);
foreach($skus as $skuObj){
echo $sku = $skuObj->slave_sku;
$product_id = wc_get_product_id_by_sku($sku);
$zh_product_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_product_id = $translation->element_id;
}
update_post_meta($product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($product_id, '_lets_review_onoff', $show_in_home_page);
update_post_meta($zh_product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($zh_product_id, '_lets_review_onoff', $show_in_home_page);
}
} else {
$product_id = wc_get_product_id_by_sku($_POST['sku']);
$zh_product_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_product_id = $translation->element_id;
}
update_post_meta($product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($product_id, '_lets_review_onoff', $show_in_home_page);
update_post_meta($zh_product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($zh_product_id, '_lets_review_onoff', $show_in_home_page);
}
/*
update_post_meta($product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($product_id, '_lets_review_onoff', $show_in_home_page);
update_post_meta($zh_product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($zh_product_id, '_lets_review_onoff', $show_in_home_page);
*/
if($init_stock=="Y"){
if($wpdb->query("ALTER TABLE sku_stock ADD `".$_POST['sku']."` FLOAT NOT NULL DEFAULT '0' COMMENT '".$_POST['description']."'")){
$update_sql = "SELECT * FROM sku_stock WHERE stock_date >= '".$_POST['start_date']."' ";
if($_POST['end_date']!=""){
$update_sql .= "AND stock_date <= '".$_POST['end_date']."' ";
}
$results = $wpdb->get_results($update_sql);
foreach($results as $stockObj){
$date = $stockObj->stock_date;
$stock_dayofweek = date('N', strtotime($date));
$is_blocked = false;
$arr_block_dates = array_map("trim", explode(",", $block_date_from_holiday));
// check block_date_from_holiday
foreach($holiday_list as $holiday) {
foreach($arr_block_dates as $buffer){
if($date == date("Y-m-d",strtotime($buffer." days",strtotime($holiday)))){
$is_blocked = true;
}
}
}
if(!$is_blocked){ // check block date
$arr_block_dayofweeks = $_POST['block_dayofweek'];
if(!in_array($stock_dayofweek, $arr_block_dayofweeks)) { // check block dayofweek
$wpdb->query("UPDATE sku_stock SET `".$_POST['sku']."` = ".$_POST['limits']." WHERE id = '".$stockObj->id."'");
}
}
}
$arr_result['condition'] = "success";
$arr_result['message'] = "Initialization Success";
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Initialization Fail in sku_stock Table";
}
} else {
$arr_result['condition'] = "success";
$arr_result['message'] = "Initialization Success";
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Initialization Fail in Wholesaler Table";
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Initialization Fail in stock_init Table";
}
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Invalid SKU";
}
}
} elseif($_POST['action']=="Edit"){
if($_POST['id']==""){
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing ID";
} elseif(trim($_POST['sku'])=="") {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing SKU";
} elseif($_POST['start_date']=="") {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing Start Date";
} elseif($_POST['limits']=="") {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing Limit";
} else {
$product_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", trim($_POST['sku'])) );
if ( $product_check ) {
$result = $wpdb->get_results("SELECT * FROM stock_init WHERE sku = '".trim($_POST['sku'])."' AND id != '".$_POST['id']."' LIMIT 1");
if(count($result)>0){
$arr_result['condition'] = "fail";
$arr_result['message'] = "SKU already exist";
} else {
$block_date_from_holiday = "0";
$arr_block_date_from_holiday = array_map('trim', explode(',', $_POST['block_date_from_holiday']));
if(trim($_POST['block_date_from_holiday'])!=""){
$block_date_from_holiday .= ",".implode(",",$arr_block_date_from_holiday);
}
if(is_bool($wpdb->update('stock_init',
array(
'sku' => $_POST['sku'],
'description' => $_POST['description'],
'start_date' => $_POST['start_date'],
'end_date' => $_POST['end_date'],
'block_date_from_holiday' => $block_date_from_holiday,
'block_dayofweek' => implode(",",$_POST['block_dayofweek']),
'limits' => $_POST['limits'],
'min_production_qty' => $_POST['min_production_qty'],
'oven_qty' => $_POST['oven_qty'],
'bake_qty_per_round' => $_POST['bake_qty_per_round'],
'display_unit' => $_POST['display_unit'],
'packing_unit' => $_POST['packing_unit'],
'unit_qty' => $_POST['unit_qty'],
'custom_formula' => $_POST['custom_formula'],
'show_in_app' => $show_in_app,
'show_in_preparation_list' => $show_in_preparation_list,
'remark' => $_POST['remark'],
'ingredient' => $_POST['ingredient'],
'preparation_day' => $_POST['preparation_day'],
'init_stock' => $init_stock
),
array('id'=>$_POST['id']))!=1)
){
if(is_bool($wpdb->update('sku_wholesaler_sku',
array(
'sku' => $_POST['sku'],
'remark' => $_POST['description']
),array('sku' => $_POST['o_sku']))!=1)
){
if(has_slave_sku($_POST['sku'])){ // checked work
$skus = get_salve_sku($_POST['sku']);
foreach($skus as $skuObj){
$sku = $skuObj->slave_sku;
$product_id = wc_get_product_id_by_sku($sku);
$zh_product_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_product_id = $translation->element_id;
}
update_post_meta($product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($product_id, '_lets_review_onoff', $show_in_home_page);
update_post_meta($zh_product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($zh_product_id, '_lets_review_onoff', $show_in_home_page);
}
} else { // checked work
$product_id = wc_get_product_id_by_sku($_POST['sku']);
$zh_product_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_product_id = $translation->element_id;
}
update_post_meta($product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($product_id, '_lets_review_onoff', $show_in_home_page);
update_post_meta($zh_product_id, '_lets_review_final_score_100', $_POST['sort_seq']);
update_post_meta($zh_product_id, '_lets_review_onoff', $show_in_home_page);
}
if($init_stock=="Y"){
if($wpdb->query("ALTER TABLE sku_stock CHANGE `".$_POST['o_sku']."` `".$_POST['sku']."` FLOAT NOT NULL DEFAULT '0' COMMENT '".$_POST['description']."'")!=false){
if($_POST['o_start_date'] > $_POST['start_date']){
for($i = strtotime($_POST['start_date']); $i < strtotime($_POST['o_start_date']); $i+=86400){
$date = date('Y-m-d', $i);
$stock_dayofweek = date('N', strtotime($date));
$is_blocked = false;
$arr_block_dates = array_map("trim", explode(",", $block_date_from_holiday));
// check block_date_from_holiday
foreach($holiday_list as $holiday) {
foreach($arr_block_dates as $buffer){
if($date == date("Y-m-d",strtotime($buffer." days",strtotime($holiday)))){
$is_blocked = true;
}
}
}
if(!$is_blocked){ // check block date
$arr_block_dayofweeks = $_POST['block_dayofweek'];
if(!in_array($stock_dayofweek, $arr_block_dayofweeks)) { // check block dayofweek
$wpdb->query("UPDATE sku_stock SET `".$_POST['sku']."` = ".$_POST['limits']." WHERE stock_date = '".date('Y-m-d', $i)."'");
}
}
}
}
if($_POST['o_start_date'] < $_POST['start_date']){
for($j = strtotime($_POST['o_start_date']); $j < strtotime($_POST['start_date']); $j+=86400){
$wpdb->query("UPDATE sku_stock SET `".$_POST['sku']."` = 0 WHERE stock_date = '".date('Y-m-d', $j)."'");
}
}
if($_POST['o_end_date']!=""){
$o_end_date = $_POST['o_end_date'];
} else {
$o_end_date = date('Y-m-d', strtotime("+15 day"));
}
if($_POST['end_date']!=""){
$end_date = $_POST['end_date'];
} else {
$end_date = date('Y-m-d', strtotime("+15 day"));
}
if($o_end_date > $end_date){
for($k = strtotime($o_end_date); $k > strtotime($end_date); $k-=86400){
$wpdb->query("UPDATE sku_stock SET `".$_POST['sku']."` = 0 WHERE stock_date = '".date('Y-m-d', $k)."'");
}
}
if($o_end_date < $end_date){
for($l = strtotime($end_date); $l > strtotime($o_end_date); $l-=86400){
$date = date('Y-m-d', $l);
$stock_dayofweek = date('N', strtotime($date));
$is_blocked = false;
$arr_block_dates = array_map("trim", explode(",", $block_date_from_holiday));
// check block_date_from_holiday
foreach($holiday_list as $holiday) {
foreach($arr_block_dates as $buffer){
if($date == date("Y-m-d",strtotime($buffer." days",strtotime($holiday)))){
$is_blocked = true;
}
}
}
if(!$is_blocked){ // check block date
$arr_block_dayofweeks = $_POST['block_dayofweek'];
if(!in_array($stock_dayofweek, $arr_block_dayofweeks)) { // check block dayofweek
$wpdb->query("UPDATE sku_stock SET `".$_POST['sku']."` = ".$_POST['limits']." WHERE stock_date = '".date('Y-m-d', $l)."'");
}
}
}
}
$arr_result['condition'] = "success";
$arr_result['message'] = "Update Success";
} else {
/****new added ****/
if($wpdb->query("ALTER TABLE sku_stock ADD `".$_POST['sku']."` FLOAT NOT NULL DEFAULT '0' COMMENT '".$_POST['description']."'")){
$update_sql = "SELECT * FROM sku_stock WHERE stock_date >= '".$_POST['start_date']."' ";
if($_POST['end_date']!=""){
$update_sql .= "AND stock_date <= '".$_POST['end_date']."' ";
}
$results = $wpdb->get_results($update_sql);
foreach($results as $stockObj){
$date = $stockObj->stock_date;
$stock_dayofweek = date('N', strtotime($date));
$is_blocked = false;
$arr_block_dates = array_map("trim", explode(",", $block_date_from_holiday));
// check block_date_from_holiday
foreach($holiday_list as $holiday) {
foreach($arr_block_dates as $buffer){
if($date == date("Y-m-d",strtotime($buffer." days",strtotime($holiday)))){
$is_blocked = true;
}
}
}
if(!$is_blocked){ // check block date
$arr_block_dayofweeks = $_POST['block_dayofweek'];
if(!in_array($stock_dayofweek, $arr_block_dayofweeks)) { // check block dayofweek
$wpdb->query("UPDATE sku_stock SET `".$_POST['sku']."` = ".$_POST['limits']." WHERE id = '".$stockObj->id."'");
}
}
}
$arr_result['condition'] = "success";
$arr_result['message'] = "Update Success";
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Initialization Fail in sku_stock Table";
}
/***end *new added ****/
//$arr_result['condition'] = "fail";
//$arr_result['message'] = "Update fail in sku_stock table";
}
} else {
$arr_result['condition'] = "success";
$arr_result['message'] = "Update Success";
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Update fail in wholesaler table";
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Update Fail";
}
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Invalid SKU";
}
}
} elseif($_POST['action']=="Remove"){
if($_POST['id']==""){
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing ID";
} elseif($_POST['sku']=="") {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Missing SKU";
} else {
$wpdb->delete("stock_init", array( 'id' => $_POST['id'] ));
$wpdb->delete("sku_wholesaler_sku", array( 'sku' => $_POST['sku'] ));
$wpdb->query("ALTER TABLE `sku_stock` DROP COLUMN `".$_POST['sku']."`");
$arr_result['condition'] = "success";
$arr_result['message'] = $_POST['sku']." is removed from Sku Stock Initialization table";
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Unknown Action";
}
echo json_encode($arr_result);
}
if($_POST['section']=="add_reservation"){
$number = strtoupper(substr(md5(rand()), 0, 6));
if($_POST['hash']=="" || !isset($_POST['hash'])){
$arr_result['condition'] = "fail";
$arr_result['message'] = "Invalid hash value";
} else {
if(get_user_id_from_hash($_POST['hash'])){
$user_id = get_user_id_from_hash($_POST['hash']);
$userObj = get_userdata($user_id);
if($wpdb->insert('reservation_record',
array(
'reservation_number' => $number,
'delivery_date' => $_POST['delivery_date'],
'user_id' => $user_id,
'company_name' => get_user_meta( $user_id, 'billing_company', true ),
'user_name' => $userObj->display_name,
'user_phone' => get_user_meta( $user_id, 'billing_phone', true ),
'user_email' => get_user_meta( $user_id, 'billing_email', true ),
'user_ip' => getClientIpAddr()
))
){
$reservation_id = $wpdb->insert_id;
$ttl_amount = 0;
foreach($_POST['qty'] as $idx=>$value){
if($value!="" && $value!=0){
$product = wc_get_product($_POST['productID'][$idx]);
$trid = $sitepress->get_element_trid($product->get_id(), 'post_product');
$translations = $sitepress->get_element_translations($trid, 'post_product');
foreach( $translations as $lang=>$translation){
if($translation->language_code == "zh-hant")
$zh_post_id = $translation->element_id;
}
$item_amount = $_POST['priceValue'][$idx]*$value;
$trid = $sitepress->get_element_trid($_POST['attributeID'][$idx], 'tax_pa_cut');
$variation_name = "";
$variation_name_zh = "";
$translations = $sitepress->get_element_translations($trid, 'tax_pa_cut');
foreach( $translations as $lang=>$translation){
if($translation->language_code == "zh-hant"){
$variation_name_zh = $translation->name;
}
if($translation->language_code == "en"){
$variation_name = $translation->name;
}
}
if($wpdb->insert('reservation_detail',
array(
'reservation_id' => $reservation_id,
'sku' => $product->get_sku(),
'product_id' => $_POST['productID'][$idx],
'product_name' => $product->get_name(),
'product_name_zh' => get_the_title($zh_post_id),
'variation_id' => $_POST['variationID'][$idx],
'variation_name' => $variation_name,
'variation_name_zh' => $variation_name_zh,
'qty' => $value,
'unit_price' => $_POST['priceValue'][$idx],
'item_amount' => $item_amount
)
)){
$ttl_amount += $item_amount;
}
}
}
if($wpdb->update('reservation_record', array('total_amount' => $ttl_amount),array('reservation_number' => $number))){
$arr_result['condition'] = "success";
$arr_result['message'] = "Your reservation is received.<br>Reservation No.: ".$number."<br>Submission Time: ".date("Y-m-d H:i:s");
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Database error";
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Database error";
}
} else {
$arr_result['condition'] = "fail";
$arr_result['message'] = "Invalid hash value";
}
}
echo json_encode($arr_result);
/*
$arr_result = array();
if($_POST['id']!=""){
if($wpdb->update('sku_wholesaler_period', array( 'status' => 0),array('id'=>$_POST['id']))){
$arr_result['condition'] = 'success';
} else {
$arr_result['condition'] = 'fail';
}
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
*/
}
if($_POST['section']=="get_daily_reservation_chart"){
$arr_key = explode("-",$_POST['key']);
$arr_id = explode("_",$arr_key[1]);
$data = array();
$results = $wpdb->get_results("SELECT a.company_name, SUM(b.qty) as total FROM reservation_record a LEFT JOIN reservation_detail b on a.id = b.reservation_id WHERE a.delivery_date = '".$_POST['date']."' AND b.product_id = '".$arr_id[0]."' AND b.variation_id = '".$arr_id[1]."'
GROUP BY a.company_name, b.product_id, b.variation_id");
foreach($results as $reserveObj){
$arr_reserve = array('language'=>$reserveObj->company_name,'total'=>$reserveObj->total,'color'=>'#'.rand(100000, 999999).'');
array_push($data, $arr_reserve);
}
echo json_encode($data);
}
if($_POST['section']=="get_daily_production_chart"){
$arr_key = explode("-",$_POST['key']);
$arr_id = explode("_",$arr_key[1]);
$data = array();
$arr_data = array('type'=>"Group",'total'=>$arr_key[2],'color'=>'rgba(255, 99, 132, 0.8)');
array_push($data, $arr_data);
$arr_data = array('type'=>"Individual",'total'=>$arr_key[3],'color'=>'rgba(255, 205, 86, 0.8)');
array_push($data, $arr_data);
/*
$results = $wpdb->get_results("SELECT a.company_name, SUM(b.qty) as total FROM reservation_record a LEFT JOIN reservation_detail b on a.id = b.reservation_id WHERE a.delivery_date = '".$_POST['date']."' AND b.product_id = '".$arr_id[0]."' AND b.variation_id = '".$arr_id[1]."'
GROUP BY a.company_name, b.product_id, b.variation_id");
foreach($results as $reserveObj){
$arr_reserve = array('language'=>$reserveObj->company_name,'total'=>$reserveObj->total,'color'=>'#'.rand(100000, 999999).'');
array_push($data, $arr_reserve);
}
*/
echo json_encode($data);
}
if($_POST['section']=="get_calculated_qty"){
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
if($_POST['section']=="update_completed_qty"){
$year = "2022";
if($_POST['lunar_year']) {
$year = $_POST['lunar_year'];
}
$table = "sku_giftbox_".$year;
$arr_result = array();
$arr_result['sku'] = $_POST['sku'];
if($wpdb->update( $table, array( 'completed_qty' => trim($_POST['completed_qty']) ), array( 'sku' => trim($_POST['sku']) ) )){
$arr_result['condition'] = "success";
$arr_result['remaining_qty'] = $_POST['order_qty'] - $_POST['completed_qty'];
} else {
$arr_result['condition'] = "fail";
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_sequence"){
if(has_slave_sku($_POST['sku'])){
$skus = get_salve_sku($_POST['sku']);
foreach($skus as $skuObj){
$sku = $skuObj->slave_sku;
$product_id = wc_get_product_id_by_sku($sku);
$zh_product_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_product_id = $translation->element_id;
}
update_post_meta($product_id, '_lets_review_final_score_100', $_POST['score']);
update_post_meta($zh_product_id, '_lets_review_final_score_100', $_POST['score']);
/*
echo $product_id;
echo "<br>";
echo $zh_product_id;
echo "<br>";
*/
}
} else {
$zh_product_id = 0;
$trid = $sitepress->get_element_trid($_POST['product_id'], 'post_product');
$translations = $sitepress->get_element_translations($trid, 'product');
foreach( $translations as $lang=>$translation){
if($translation->language_code == "zh-hant")
$zh_product_id = $translation->element_id;
}
update_post_meta($_POST['product_id'], '_lets_review_final_score_100', $_POST['score']);
update_post_meta($zh_product_id, '_lets_review_final_score_100', $_POST['score']);
/*
echo $_POST['product_id'];
echo "<br>";
echo $zh_product_id;
echo "<br>";
*/
}
$arr_result['condition'] = "success";
echo json_encode($arr_result);
}
if($_POST['section']=="update_onoff"){
if(has_slave_sku($_POST['sku'])){
$skus = get_salve_sku($_POST['sku']);
foreach($skus as $skuObj){
$sku = $skuObj->slave_sku;
$product_id = wc_get_product_id_by_sku($sku);
$zh_product_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_product_id = $translation->element_id;
}
update_post_meta($product_id, '_lets_review_onoff', $_POST['checked']);
update_post_meta($zh_product_id, '_lets_review_onoff', $_POST['checked']);
echo $product_id;
echo "<br>";
echo $zh_product_id;
echo "<br>";
}
} else {
$zh_product_id = 0;
$trid = $sitepress->get_element_trid($_POST['product_id'], 'post_product');
$translations = $sitepress->get_element_translations($trid, 'product');
foreach( $translations as $lang=>$translation){
if($translation->language_code == "zh-hant")
$zh_product_id = $translation->element_id;
}
update_post_meta($_POST['product_id'], '_lets_review_onoff', $_POST['checked']);
update_post_meta($zh_product_id, '_lets_review_onoff', $_POST['checked']);
echo $_POST['product_id'];
echo "<br>";
echo $zh_product_id;
echo "<br>";
}
}
if($_POST['section']=="update_showapp"){
$wpdb->update('stock_init', array( "show_in_app" => $_POST['checked']),array('sku'=>$_POST['sku']));
}
if($_POST['section']=="update_showpreparationlist"){
$wpdb->update('stock_init', array( "show_in_preparation_list" => $_POST['checked']),array('sku'=>$_POST['sku']));
}
if($_POST['section']=="update_grouping_in_sfproduct"){
$wpdb->update('inventory_sfproduct', array( "grouping" => $_POST['checked']),array('id'=>$_POST['sfproduct_id']));
}
if($_POST['section']=="update_show_in_sfproduct"){
$wpdb->update('inventory_sfproduct', array( "show_in_preparation_list" => $_POST['checked']),array('id'=>$_POST['sfproduct_id']));
}
if($_POST['section']=="update_stock_qty"){
$arr_result['condition'] = 'fail';
if($_POST['component_type_id']=="1"){
if($wpdb->update('inventory_product', array( "stock_qty" => $_POST['stock_qty']),array('id'=>$_POST['reference_id']))>=0){
$arr_result['condition'] = 'success';
}
} elseif($_POST['component_type_id']=="2") {
if($wpdb->update('inventory_sfproduct', array( "stock_qty" => $_POST['stock_qty']),array('id'=>$_POST['reference_id']))>=0){
$arr_result['condition'] = 'success';
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="clear_stock"){
$arr_result = array();
if($wpdb->query($wpdb->prepare("UPDATE `sku_stock` SET `".$_POST['sku']."` = 0 WHERE `stock_date` >= '".$_POST['start_date']."' AND `stock_date` <= '".$_POST['end_date']."'"))){
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Stock cleared!';
}else{
$arr_result['condition'] = 'fail';
$arr_result['message'] = 'Unable to clear stock';
}
echo json_encode($arr_result);
}
// update inventory material info for single field //
if($_POST['section']=="update_material"){
$arr_result = array();
if($wpdb->query($wpdb->prepare("UPDATE `inventory_material` SET `".$_POST['field']."` = '".$_POST['value']."' WHERE `id` = '".$_POST['id']."' LIMIT 1"))){
$arr_result['condition'] = 'success';
$arr_result['message'] = 'material detail updated';
}else{
$arr_result['condition'] = 'fail';
$arr_result['message'] = 'Unable to update material detail';
}
echo json_encode($arr_result);
}
// generate material code //
if($_POST['section']=="generate_material_code") {
$arr_result = array();
if($_POST['category']=='ingredient') {
$prefix = 'I';
} elseif($_POST['category']=='packing'){
$prefix = 'P';
}
$record = $wpdb->get_results("SELECT code FROM `inventory_material` WHERE `code` LIKE '".$prefix."%' ORDER BY LENGTH(code) DESC, code DESC LIMIT 1");
if(count($record)>0){
$maxCode = $record[0]->code;
$nextNumber = substr($maxCode,1,strlen($maxCode)-1)+1;
$nextCode = str_pad($nextNumber,4,"0",STR_PAD_LEFT);
$code = $prefix.$nextCode;
} else {
$code = $prefix."0001";
}
$arr_result['condition'] = 'success';
$arr_result['code'] = $code;
echo json_encode($arr_result);
}
// generate process code //
if($_POST['section']=="generate_process_code") {
$prefix = "T";
$arr_result = array();
$record = $wpdb->get_results("SELECT code FROM `inventory_process` ORDER BY LENGTH(code) DESC, code DESC LIMIT 1");
if(count($record)>0){
$maxCode = $record[0]->code;
$nextNumber = substr($maxCode,1,strlen($maxCode)-1)+1;
$nextCode = str_pad($nextNumber,4,"0",STR_PAD_LEFT);
$code = $prefix.$nextCode;
} else {
$code = $prefix."0001";
}
$arr_result['condition'] = 'success';
$arr_result['code'] = $code;
echo json_encode($arr_result);
}
// generate sfproduct code //
if($_POST['section']=="generate_sfproduct_code") {
$prefix = "S";
$arr_result = array();
$record = $wpdb->get_results("SELECT code FROM `inventory_sfproduct` ORDER BY LENGTH(code) DESC, code DESC LIMIT 1");
if(count($record)>0){
$maxCode = $record[0]->code;
$nextNumber = substr($maxCode,1,strlen($maxCode)-1)+1;
$nextCode = str_pad($nextNumber,4,"0",STR_PAD_LEFT);
$code = $prefix.$nextCode;
} else {
$code = $prefix."0001";
}
$arr_result['condition'] = 'success';
$arr_result['code'] = $code;
echo json_encode($arr_result);
}
// add/edit inventory material //
if($_POST['section']=="material_init"){
if($_POST['action']=='Add') {
$record = $wpdb->get_results("SELECT code FROM `inventory_material` WHERE `code` = '".$_POST['code']."' LIMIT 1");
if(count($record)>0){
$arr_result['condition']='fail';
$arr_result['message'] = 'Material Code is already used by another item';
} else {
if($wpdb->insert(
'inventory_material',
array(
'category' => $_POST['category'],
'code' => $_POST['code'],
'type_id' => $_POST['type_id'],
'name' => $_POST['name'],
'display_name' => $_POST['display_name'],
'brand_id' => $_POST['brand_id'],
'moq_qty' => $_POST['moq_qty'],
'moq_qty_unit_id' => $_POST['moq_qty_unit_id'],
'moq_price' => $_POST['moq_price'],
'unit_id' => $_POST['unit_id'],
'unit_price' => $_POST['unit_price'],
'quotation_date' => $_POST['quotation_date'],
'is_default' => isset($_POST['is_default'])?"Y":"N",
'supplier_id' => $_POST['supplier_id'],
'safety_qty' => $_POST['safety_qty'],
'safety_qty_unit_id' => $_POST['safety_qty_unit_id'],
'show_in_label' => isset($_POST['show_in_label'])?"Y":"N",
'attribute_id' => $_POST['attribute_id'],
'status' => '1',
'create_date' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_date' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Material is added successfully';
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Unable to create new material';
}
}
} elseif($_POST['action']=='Edit') {
if($_POST['ocode']==$_POST['code']){
$pass = true;
} else {
$record = $wpdb->get_results("SELECT code FROM `inventory_material` WHERE `code` = '".$_POST['code']."' LIMIT 1");
if(count($record)>0){
$pass = false;
} else {
$pass = true;
}
}
if($pass==true){
if($wpdb->update(
'inventory_material',
array(
'category' => $_POST['category'],
'code' => $_POST['code'],
'type_id' => $_POST['type_id'],
'name' => $_POST['name'],
'display_name' => $_POST['display_name'],
'brand_id' => $_POST['brand_id'],
'moq_qty' => $_POST['moq_qty'],
'moq_qty_unit_id' => $_POST['moq_qty_unit_id'],
'moq_price' => $_POST['moq_price'],
'unit_id' => $_POST['unit_id'],
'unit_price' => $_POST['unit_price'],
'quotation_date' => $_POST['quotation_date'],
'is_default' => isset($_POST['is_default'])?"Y":"N",
'supplier_id' => $_POST['supplier_id'],
'safety_qty' => $_POST['safety_qty'],
'safety_qty_unit_id' => $_POST['safety_qty_unit_id'],
'show_in_label' => isset($_POST['show_in_label'])?"Y":"N",
'attribute_id' => $_POST['attribute_id'],
'status' => '1',
'mod_date' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)){
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Material is updated successfully';
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Unable to update material detail';
}
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Material Code is already used by another item';
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="calculate_unit_price"){
$arr_result = array();
$measure_unit = $wpdb->get_results("SELECT name FROM `inventory_measure_unit` WHERE `id` = '".$_POST['moq_qty_unit']."' LIMIT 1");
if(count($measure_unit)>0){
$unit_name = $measure_unit[0]->name;
if(in_array($unit_name, array('kg','l'))){
$unit_price = $_POST['moq_price'] / ($_POST['moq_qty'] * 1000);
} else {
$unit_price = $_POST['moq_price'] / $_POST['moq_qty'];
}
$unit_price = ceil($unit_price*1000)/1000;
$arr_result['condition'] = 'success';
$arr_result['unit_price'] = $unit_price;
}else{
$arr_result['condition'] = 'fail';
$arr_result['message'] = 'Unable to calculate unit price';
}
echo json_encode($arr_result);
}
if($_POST['section']=="add_value_to_list"){
$arr_result = array();
if($_POST['type']=="Type"){
$table = "inventory_material_type";
$return_div_id = 'type_section';
$selector_id = 'type_id';
$title_id = 'type_list_title';
$title = 'Material Type';
$table_id = 'dataTable_type';
} elseif($_POST['type']=="Brand") {
$table = "inventory_material_brand";
$return_div_id = 'brand_section';
$selector_id = 'brand_id';
$title_id = 'brand_list_title';
$title = 'Brand';
$table_id = 'dataTable_brand';
} elseif($_POST['type']=="Supplier") {
$table = "inventory_material_supplier";
$return_div_id = 'supplier_section';
$selector_id = 'supplier_id';
$title_id = 'supplier_list_title';
$title = 'Supplier';
$table_id = 'dataTable_supplier';
} elseif($_POST['type']=="Unit") {
$table = "inventory_measure_unit";
$return_div_id = 'unit_section';
$selector_id = 'unit_id';
$title_id = 'unit_list_title';
$title = 'Measure Unit';
$table_id = 'dataTable_unit';
} elseif($_POST['type']=="Procedure") {
$table = "inventory_material_procedure";
$return_div_id = 'procedure_section';
$selector_id = 'procedure_id';
$title_id = 'procedure_list_title';
$title = 'Procedure';
$table_id = 'dataTable_procedure';
} elseif($_POST['type']=="Attribute") {
$table = "inventory_material_attribute";
$return_div_id = 'attribute_section';
$selector_id = 'attribute_id';
$title_id = 'attribute_list_title';
$title = 'Attribute';
$table_id = 'dataTable_attribute';
} elseif($_POST['type']=="Sfattribute") {
$table = "inventory_sfproduct_attribute";
$return_div_id = 'sfattribute_section';
$selector_id = 'sfattribute_id';
$title_id = 'sfattribute_list_title';
$title = 'SFAttribute';
$table_id = 'dataTable_sfattribute';
} elseif($_POST['type']=="Sfcategory") {
$table = "inventory_sfproduct_category";
$return_div_id = 'sfcategory_section';
$selector_id = 'sfcategory_id';
$title_id = 'sfcategory_list_title';
$title = 'SFCategory';
$table_id = 'dataTable_sfcategory';
} elseif($_POST['type']=="Domain") {
$table = "custom_keyword_blacklist";
$return_div_id = 'domain_section';
$selector_id = 'domain_id';
$title_id = 'domain_list_title';
$title = 'Doamin';
$table_id = 'dataTable_domain';
$extraField = "type";
$extraValue = "D";
} elseif($_POST['type']=="Phrase") {
$table = "custom_keyword_blacklist";
$return_div_id = 'phrase_section';
$selector_id = 'phrase_id';
$title_id = 'phrase_list_title';
$title = 'Phrase';
$table_id = 'dataTable_phrase';
$extraField = "type";
$extraValue = "U";
}
if(isset($extraField) && $extraField!=""){
$dataArr = array('name' => $_POST['value'], $extraField => $extraValue);
} else {
$dataArr = array('name' => $_POST['value']);
}
if($wpdb->insert($table,$dataArr)){
//echo $wpdb->last_query;
$material_type_list = get_material_type_list();
$material_brand_list = get_material_brand_list();
$material_supplier_list = get_material_supplier_list();
$material_attribute_list = get_material_attribute_list();
$sfproduct_attribute_list = get_sfproduct_attribute_list();
$sfproduct_category_list = get_sfproduct_category_list();
//$measure_unit_list = get_measure_unit_list();
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Value is added successfully';
$arr_result['return_div_id'] = $return_div_id;
$arr_result['selector_id'] = $selector_id;
$arr_result['title_id'] = $title_id;
$arr_result['title'] = $title;
$arr_result['table_id'] = $table_id;
if($_POST['type']=="Type"){
$html_output = "<select name='type_id' id='type_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($material_type_list as $idx=>$type){
$html_output .= "<option value='".$idx."' data-tokens='".$type."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $type;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_type_btn' value='New Type' title='Click here to add a new type into list'>";
} elseif($_POST['type']=="Brand") {
$html_output = "<select name='brand_id' id='brand_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($material_brand_list as $idx=>$brand){
$html_output .= "<option value='".$idx."' data-tokens='".$brand."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $brand;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_brand_btn' value='New Brand' title='Click here to add a new brand into list'>";
} elseif($_POST['type']=="Supplier") {
$html_output = "<select name='supplier_id' id='supplier_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($material_supplier_list as $idx=>$supplier){
$html_output .= "<option value='".$idx."' data-tokens='".$supplier."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $supplier;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_supplier_btn' value='New Supplier' title='Click here to add a new supplier into list'>";
} elseif($_POST['type']=="Attribute") {
$html_output = "<select name='attribute_id' id='attribute_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($material_attribute_list as $idx=>$attribute){
$html_output .= "<option value='".$idx."' data-tokens='".$attribute."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $attribute;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_attribute_btn' value='New Attribute' title='Click here to add a new addtibute into list'>";
} elseif($_POST['type']=="Sfattribute") {
$html_output = "<select name='sfattribute_id' id='sfattribute_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($sfproduct_attribute_list as $idx=>$attribute){
$html_output .= "<option value='".$idx."' data-tokens='".$attribute."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $attribute;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_sfattribute_btn' value='New Semi-finshed Product Attribute' title='Click here to add a new semi-finished product attribute into list'>";
} elseif($_POST['type']=="Sfcategory") {
$html_output = "<select name='sfcategory_id' id='sfcategory_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($sfproduct_category_list as $idx=>$category){
$html_output .= "<option value='".$idx."' data-tokens='".$category."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $category;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_sfcategory_btn' value='New Semi-finshed Product Category' title='Click here to add a new semi-finished product category into list'>";
}
$arr_result['html_output'] = $html_output;
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Unable to add value';
}
echo json_encode($arr_result);
}
if($_POST['section']=="get_material_type_list"){
$arr_result = array();
$arr_result['data'] = array();
$material_type_list = get_material_type_list();
foreach($material_type_list as $idx=>$type){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$type."</span><input type='text' id='".$idx."-type' name='".$idx."-type' value='".$type."' callout='".$type."' class='edit_type'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_material_brand_list"){
$arr_result = array();
$arr_result['data'] = array();
$material_brand_list = get_material_brand_list();
foreach($material_brand_list as $idx=>$brand){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$brand."</span><input type='text' id='".$idx."-brand' name='".$idx."-brand' value='".$brand."' callout='".$brand."' class='edit_brand'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_material_supplier_list"){
$arr_result = array();
$arr_result['data'] = array();
$material_supplier_list = get_material_supplier_list();
foreach($material_supplier_list as $idx=>$supplier){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$supplier."</span><input type='text' id='".$idx."-supplier' name='".$idx."-supplier' value='".$supplier."' callout='".$supplier."' class='edit_supplier'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_measure_unit_list"){
$arr_result = array();
$arr_result['data'] = array();
$measure_unit_list = get_measure_unit_list();
foreach($measure_unit_list as $idx=>$unit){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$unit."</span><input type='text' id='".$idx."-unit' name='".$idx."-unit' value='".$unit."' callout='".$unit."' class='edit_unit'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_procedure_list"){
$arr_result = array();
$arr_result['data'] = array();
$procedure_list = get_procedure_list();
foreach($procedure_list as $idx=>$procedure){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$procedure."</span><input type='text' id='".$idx."-procedure' name='".$idx."-procedure' value='".$procedure."' callout='".$procedure."' class='edit_procedure'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_material_attribute_list"){
$arr_result = array();
$arr_result['data'] = array();
$attribute_list = get_material_attribute_list();
foreach($attribute_list as $idx=>$attribute){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$attribute."</span><input type='text' id='".$idx."-attribute' name='".$idx."-attribute' value='".$attribute."' callout='".$attribute."' class='edit_attribute'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_sfproduct_attribute_list"){
$arr_result = array();
$arr_result['data'] = array();
$attribute_list = get_sfproduct_attribute_list();
foreach($attribute_list as $idx=>$attribute){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$attribute."</span><input type='text' id='".$idx."-sfattribute' name='".$idx."-sfattribute' value='".$attribute."' callout='".$attribute."' class='edit_sfattribute'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_sfproduct_category_list"){
$arr_result = array();
$arr_result['data'] = array();
$category_list = get_sfproduct_category_list();
foreach($category_list as $idx=>$category){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$category."</span><input type='text' id='".$idx."-sfcategory' name='".$idx."-sfcategory' value='".$category."' callout='".$category."' class='edit_sfcategory'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="edit_bom_misc_setting"){
$arr_result = array();
if($_POST['id']!="" && $_POST['type']!="") {
if($_POST['type']=="type"){
$table = "inventory_material_type";
} elseif($_POST['type']=="brand") {
$table = "inventory_material_brand";
} elseif($_POST['type']=="supplier") {
$table = "inventory_material_supplier";
} elseif($_POST['type']=="unit") {
$table = "inventory_measure_unit";
} elseif($_POST['type']=="procedure") {
$table = "inventory_material_procedure";
} elseif($_POST['type']=="attribute") {
$table = "inventory_material_attribute";
} elseif($_POST['type']=="sfattribute") {
$table = "inventory_sfproduct_attribute";
} elseif($_POST['type']=="sfcategory") {
$table = "inventory_sfproduct_category";
}
$wpdb->update($table, array( "name" => $_POST['nvalue']),array('id'=>$_POST['id']));
$arr_result['id'] = $_POST['id']."-".$_POST['type'];
$arr_result['callout'] = $_POST['nvalue'];
$arr_result['condition']='success';
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="get_material_info"){
$arr_result = array();
if($_POST['id']!="") {
$result = $wpdb->get_results("
SELECT mat.category as category, mat.code as code, mat.id as material_id, mat.name as material_name, type.name as type_name, brand.name as brand_name, sup.name as supplier_name, mat.unit_price, mat_unit.name as unit_name
FROM inventory_material mat
LEFT JOIN inventory_material_type type ON type.id = mat.type_id
LEFT JOIN inventory_material_brand brand ON brand.id = mat.brand_id
LEFT JOIN inventory_material_supplier sup ON sup.id = mat.supplier_id
LEFT JOIN inventory_measure_unit mat_unit ON mat_unit.id = mat.unit_id
WHERE mat.id = '".$_POST['id']."' LIMIT 1
");
$arr_result['condition']='success';
$arr_result['data']=$result[0];
$arr_result['selector']=$_POST['selector'];
} else {
$arr_result['condition']='fail';
$arr_result['message']='unable to lookup material detail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_bom_test"){
if($_POST['method']=="calculate"){
$wastage = get_constant_value("Ingredient Wastage");
$arr_result['condition']='success';
$arr_result['content']=array();
$total_cost=0;
foreach($_POST['row'] as $idx=>$row){
$arr_line = array();
$material_id = $_POST['material_id'][$idx];
$materialObj = get_material_item_info($material_id);
$arr_line['row'] = $row;
$arr_line['material_id'] = $material_id;
$arr_line['type'] = $materialObj->type_name;
$arr_line['brand'] = $materialObj->brand_name;
$arr_line['supplier'] = $materialObj->supplier_name;
$arr_line['unit_price'] = $materialObj->unit_price;
$arr_line['unit'] = $materialObj->unit_name;
$arr_line['price'] = round($_POST['qty'][$idx] * $materialObj->unit_price, 3);
$total_cost+=$arr_line['price'];
array_push($arr_result['content'],$arr_line);
}
$arr_result['total_cost']=round($total_cost,3);
$arr_result['total_cost_with_wastage'] = round($total_cost * (1+$wastage),3);
$arr_result['unit_cost'] = round($arr_result['total_cost_with_wastage']/$_POST['production_qty'],3);
} else {
if($_POST['action']=='Add') {
if($wpdb->insert(
'sku_bom',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $_POST['total_cost'],
'total_cost_with_wastage' => $_POST['total_cost_with_wastage'],
'unit_cost' => $_POST['unit_cost'],
'create_time' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$bom_id = $wpdb->insert_id;
foreach($_POST['material_id'] as $idx => $material_id){
$wpdb->insert(
'sku_bom_detail',
array(
'bom_id' => $bom_id,
'material_id' => $material_id,
'procedure_id' => $_POST['procedure_id'][$idx],
'unit_price' => $_POST['unit_price'][$idx],
'qty' => $_POST['qty'][$idx],
'price' => $_POST['price'][$idx],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOM updated';
$arr_result['id']= $bom_id;
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to insert BOM';
}
} elseif($_POST['action']=='Edit') {
if($wpdb->update(
'sku_bom',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $_POST['total_cost'],
'total_cost_with_wastage' => $_POST['total_cost_with_wastage'],
'unit_cost' => $_POST['unit_cost'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)>=0){
if($wpdb->delete('sku_bom_detail', array( 'bom_id' => $_POST['id'] ))>=0){
foreach($_POST['material_id'] as $idx => $material_id){
$wpdb->insert(
'sku_bom_detail',
array(
'bom_id' => $_POST['id'],
'material_id' => $material_id,
'procedure_id' => $_POST['procedure_id'][$idx],
'unit_price' => $_POST['unit_price'][$idx],
'qty' => $_POST['qty'][$idx],
'price' => $_POST['price'][$idx],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOM updated';
$arr_result['id']= $_POST['id'];
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOM';
}
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOM';
}
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_bom"){
$wastage = get_constant_value("Ingredient Wastage");
$total_cost = 0;
$total_cost_with_wastage = 0;
$unit_cost = 0;
$arr_data = array();
foreach($_POST['row'] as $idx=>$row){
$arr_line = array();
$material_id = $_POST['material_id'][$idx];
$materialObj = get_material_item_info($material_id);
$arr_line['row'] = $row;
$arr_line['procedure_id'] = $_POST['procedure_id'][$idx];
$arr_line['material_id'] = $material_id;
$arr_line['type'] = $materialObj->type_name;
$arr_line['brand'] = $materialObj->brand_name;
$arr_line['supplier'] = $materialObj->supplier_name;
$arr_line['qty'] = $_POST['qty'][$idx];
$arr_line['unit_price'] = number_format($materialObj->unit_price,3,".","");
$arr_line['unit'] = $materialObj->unit_name;
$arr_line['price'] = number_format($_POST['qty'][$idx] * $materialObj->unit_price,4,".","");
$total_cost += $arr_line['price'];
array_push($arr_data,$arr_line);
}
$total_cost = round($total_cost,3);
$total_cost_with_wastage = round($total_cost * (1+$wastage),3);
$unit_cost = round($total_cost_with_wastage/$_POST['production_qty'],3);
if($_POST['method']=="calculate"){
$arr_result['condition'] = 'success';
$arr_result['content'] = $arr_data;
$arr_result['total_cost'] = $total_cost;
$arr_result['total_cost_with_wastage'] = $total_cost_with_wastage;
$arr_result['unit_cost'] = $unit_cost;
} else {
if($_POST['action']=='Add') {
//print_r($arr_data);
if($wpdb->insert(
'sku_bom',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => $unit_cost,
'create_time' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$bom_id = $wpdb->insert_id;
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'sku_bom_detail',
array(
'bom_id' => $bom_id,
'material_id' => $line_data['material_id'],
'procedure_id' => $line_data['procedure_id'],
'unit_price' => $line_data['unit_price'],
'qty' => $line_data['qty'],
'price' => $line_data['price'],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOM updated';
$arr_result['id']= $bom_id;
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to insert BOM';
}
} elseif($_POST['action']=='Edit') {
if($wpdb->update(
'sku_bom',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => $unit_cost,
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)>=0){
if($wpdb->delete('sku_bom_detail', array( 'bom_id' => $_POST['id'] ))>=0){
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'sku_bom_detail',
array(
'bom_id' => $_POST['id'],
'material_id' => $line_data['material_id'],
'procedure_id' => $line_data['procedure_id'],
'unit_price' => $line_data['unit_price'],
'qty' => $line_data['qty'],
'price' => $line_data['price'],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOM updated';
$arr_result['id']= $_POST['id'];
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOM';
}
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOM';
}
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_sfproduct"){
$iWastage = get_constant_value("Ingredient Wastage");
$pWastage = get_constant_value("Packing Wastage");
$tWastage = get_constant_value("Process Wastage");
$total_cost = 0;
$total_cost_with_wastage = 0;
$production_qty = $_POST['production_qty'];
$arr_data = array();
foreach($_POST['row'] as $idx=>$row){
$arr_line = array();
$component_type_id = $_POST['component_type_id'][$idx];
$show = $_POST['show'][$idx];
$arr_line['row'] = $row;
$arr_line['show'] = $show;
$arr_line['component_type_id'] = $component_type_id;
$arr_line['reference_id'] = $_POST['reference_id'][$idx];
$arr_line['qty'] = $_POST['qty'][$idx];
$arr_line['remark'] = $_POST['remark'][$idx];
// set default value
$arr_line['material_cost'] = 0;
$arr_line['wage_cost'] = 0;
$arr_line['misc_cost'] = 0;
$arr_line['machine_cost'] = 0;
$arr_line['ttl_cost'] = 0;
switch($component_type_id){
case "1": //成品
//$cost_without_packing_material = get_item_total_cost_without_packing_material($component_type_id, $arr_line['reference_id']);
$productObj = get_product_item_info($arr_line['reference_id']);
$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $productObj->total_cost/$productObj->production_qty,4,".","");
//$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $cost_without_packing_material/$productObj->production_qty,4,".","");
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $iWastage);
break;
case "2": //半成品
//$cost_without_packing_material = get_item_total_cost_without_packing_material($component_type_id, $arr_line['reference_id']);
$sfproductObj = get_sfproduct_item_info($arr_line['reference_id']);
$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $sfproductObj->total_cost/$sfproductObj->production_qty,4,".","");
//$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $cost_without_packing_material/$sfproductObj->production_qty,4,".","");
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $iWastage);
break;
case "3": //食材
$materialObj = get_material_item_info($arr_line['reference_id']);
$arr_line['material_cost'] = number_format($arr_line['qty'] * $materialObj->unit_price,4,".","");
$arr_line['ttl_cost'] = $arr_line['material_cost'];
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $iWastage);
break;
case "4": //包裝物料
$materialObj = get_material_item_info($arr_line['reference_id']);
$arr_line['material_cost'] = number_format($arr_line['qty'] * $materialObj->unit_price,4,".","");
$arr_line['ttl_cost'] = $arr_line['material_cost'];
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $pWastage);
break;
case "5": //工序
$processObj = get_process_item_info($arr_line['reference_id']);
$arr_line['wage_cost'] = number_format($arr_line['qty'] * $processObj->baker_wage_per_minute,4,".","");
$arr_line['machine_cost'] = number_format($arr_line['qty'] * $processObj->machine_cost_per_minute,4,".","");
if($processObj->need_misc=="1"){
$arr_line['misc_cost'] = number_format($arr_line['qty'] * preset_total_misc_cost("minutely_cost"),4,".","");
} else {
$arr_line['misc_cost'] = number_format(0,4,".","");
}
$arr_line['ttl_cost'] = $arr_line['wage_cost'] + $arr_line['machine_cost'] + $arr_line['misc_cost'];
$total_cost += $arr_line['ttl_cost'];
$arr_line['ttl_cost'] = number_format($arr_line['ttl_cost'],4,".","");
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $tWastage);
break;
default:
break;
}
array_push($arr_data,$arr_line);
}
if($_POST['method']=="calculate"){ // update cost action
$arr_result['condition'] = 'success';
$arr_result['content'] = $arr_data;
$arr_result['total_cost'] = number_format($total_cost,3,".","");
$arr_result['total_cost_with_wastage'] = number_format($total_cost_with_wastage,3,".","");
$arr_result['unit_cost'] = number_format($total_cost/$production_qty,3,".","");
$arr_result['unit_cost_with_wastage'] = number_format($arr_result['total_cost_with_wastage']/$production_qty,3,".","");
} else {
if($_POST['action']=='Add') { // add new sfproduct
if($wpdb->insert(
'inventory_sfproduct',
array(
'code' => $_POST['code'],
'name' => $_POST['name'],
'sfattribute_id' => $_POST['sfattribute_id'],
'sfcategory_id' => $_POST['sfcategory_id'],
'production_qty' => $production_qty,
'stock_qty' => $_POST['stock_qty'],
'safety_qty' => $_POST['safety_qty'],
'unit_id' => $_POST['unit_id'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => number_format($total_cost/$production_qty,3,".",""),
'unit_cost_with_wastage' => number_format($total_cost_with_wastage/$production_qty,3,".",""),
'total_weight' => $_POST['total_weight'],
'total_time' => $_POST['total_time'],
'status' => '1',
'create_time' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$sfproduct_id = $wpdb->insert_id;
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'inventory_sfproduct_detail',
array(
'sfproduct_id' => $sfproduct_id,
'component_type_id' => $line_data['component_type_id'],
'reference_id' => $line_data['reference_id'],
'qty' => $line_data['qty'],
'material_cost' => $line_data['material_cost'],
'wage_cost' => $line_data['wage_cost'],
'misc_cost' => $line_data['misc_cost'],
'machine_cost' => $line_data['machine_cost'],
'ttl_cost' => $line_data['ttl_cost'],
'remark' => $line_data['remark'],
'sequence' => ($idx+1),
'show_in_preparation_list' => $line_data['show']
)
);
}
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Semi-finsihed product updated';
$arr_result['id'] = $sfproduct_id;
$arr_result['action'] = 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to insert semi-finsihed product';
}
} elseif($_POST['action']=='Edit') {
if($wpdb->update(
'inventory_sfproduct',
array(
'code' => $_POST['code'],
'name' => $_POST['name'],
'sfattribute_id' => $_POST['sfattribute_id'],
'sfcategory_id' => $_POST['sfcategory_id'],
'production_qty' => $production_qty,
'stock_qty' => $_POST['stock_qty'],
'safety_qty' => $_POST['safety_qty'],
'unit_id' => $_POST['unit_id'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => number_format($total_cost/$production_qty,3,".",""),
'unit_cost_with_wastage' => number_format($total_cost_with_wastage/$production_qty,3,".",""),
'total_weight' => $_POST['total_weight'],
'total_time' => $_POST['total_time'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)>=0){
if($wpdb->delete('inventory_sfproduct_detail', array('sfproduct_id' => $_POST['id']))>=0){
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'inventory_sfproduct_detail',
array(
'sfproduct_id' => $_POST['id'],
'component_type_id' => $line_data['component_type_id'],
'reference_id' => $line_data['reference_id'],
'qty' => $line_data['qty'],
'material_cost' => $line_data['material_cost'],
'wage_cost' => $line_data['wage_cost'],
'misc_cost' => $line_data['misc_cost'],
'machine_cost' => $line_data['machine_cost'],
'ttl_cost' => $line_data['ttl_cost'],
'remark' => $line_data['remark'],
'sequence' => ($idx+1),
'show_in_preparation_list' => $line_data['show']
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'Semi-finsihed product updated';
$arr_result['id']= $_POST['id'];
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update semi-finsihed product';
}
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update semi-finsihed product';
}
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_product"){
$iWastage = get_constant_value("Ingredient Wastage");
$pWastage = get_constant_value("Packing Wastage");
$tWastage = get_constant_value("Process Wastage");
$total_cost = 0;
$total_cost_with_wastage = 0;
$production_qty = $_POST['production_qty'];
$arr_data = array();
foreach($_POST['row'] as $idx=>$row){
$arr_line = array();
$component_type_id = $_POST['component_type_id'][$idx];
$show = $_POST['show'][$idx];
$arr_line['row'] = $row;
$arr_line['show'] = $show;
$arr_line['component_type_id'] = $component_type_id;
$arr_line['reference_id'] = $_POST['reference_id'][$idx];
$arr_line['qty'] = $_POST['qty'][$idx];
$arr_line['remark'] = $_POST['remark'][$idx];
// set default value
$arr_line['material_cost'] = 0;
$arr_line['wage_cost'] = 0;
$arr_line['misc_cost'] = 0;
$arr_line['machine_cost'] = 0;
$arr_line['ttl_cost'] = 0;
switch($component_type_id){
case "1": //成品
//$cost_without_packing_material = get_item_total_cost_without_packing_material($component_type_id, $arr_line['reference_id']);
$productObj = get_product_item_info($arr_line['reference_id']);
$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $productObj->total_cost/$productObj->production_qty,4,".","");
//$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $cost_without_packing_material/$productObj->production_qty,4,".","");
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $iWastage);
break;
case "2": //半成品
//$cost_without_packing_material = get_item_total_cost_without_packing_material($component_type_id, $arr_line['reference_id']);
$sfproductObj = get_sfproduct_item_info($arr_line['reference_id']);
$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $sfproductObj->total_cost/$sfproductObj->production_qty,4,".","");
//$arr_line['ttl_cost'] = number_format($arr_line['qty'] * $cost_without_packing_material/$sfproductObj->production_qty,4,".","");
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $iWastage);
break;
case "3": //食材
$materialObj = get_material_item_info($arr_line['reference_id']);
$arr_line['material_cost'] = number_format($arr_line['qty'] * $materialObj->unit_price,4,".","");
$arr_line['ttl_cost'] = $arr_line['material_cost'];
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $iWastage);
break;
case "4": //包裝物料
$materialObj = get_material_item_info($arr_line['reference_id']);
$arr_line['material_cost'] = number_format($arr_line['qty'] * $materialObj->unit_price,4,".","");
$arr_line['ttl_cost'] = $arr_line['material_cost'];
$total_cost += $arr_line['ttl_cost'];
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $pWastage);
break;
case "5": //工序
$processObj = get_process_item_info($arr_line['reference_id']);
$arr_line['wage_cost'] = number_format($arr_line['qty'] * $processObj->baker_wage_per_minute,4,".","");
$arr_line['machine_cost'] = number_format($arr_line['qty'] * $processObj->machine_cost_per_minute,4,".","");
if($processObj->need_misc=="1"){
$arr_line['misc_cost'] = number_format($arr_line['qty'] * preset_total_misc_cost("minutely_cost"),4,".","");
} else {
$arr_line['misc_cost'] = number_format(0,4,".","");
}
$arr_line['ttl_cost'] = $arr_line['wage_cost'] + $arr_line['machine_cost'] + $arr_line['misc_cost'];
$total_cost += $arr_line['ttl_cost'];
$arr_line['ttl_cost'] = number_format($arr_line['ttl_cost'],4,".","");
$total_cost_with_wastage += $arr_line['ttl_cost'] * (1 + $tWastage);
break;
default:
break;
}
array_push($arr_data,$arr_line);
}
if($_POST['method']=="calculate"){ // update cost action
$arr_result['condition'] = 'success';
$arr_result['content'] = $arr_data;
$arr_result['total_cost'] = number_format($total_cost,4,".","");
$arr_result['total_cost_with_wastage'] = number_format($total_cost_with_wastage,3,".","");
$arr_result['unit_cost'] = number_format($total_cost/$production_qty,3,".","");
$arr_result['unit_cost_with_wastage'] = number_format($arr_result['total_cost_with_wastage']/$production_qty,3,".","");
} else {
if($_POST['action']=='Add') { // add new sfproduct
if($wpdb->insert(
'inventory_product',
array(
'sku' => $_POST['sku'],
'sku_id' => $_POST['sku_id'],
'name' => $_POST['name'],
'production_qty' => $production_qty,
'stock_qty' => $_POST['stock_qty'],
'safety_qty' => $_POST['safety_qty'],
'unit_id' => $_POST['unit_id'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => number_format($total_cost/$production_qty,3,".",""),
'unit_cost_with_wastage' => number_format($total_cost_with_wastage/$production_qty,3,".",""),
'total_weight' => $_POST['total_weight'],
'total_time' => $_POST['total_time'],
'status' => '1',
'create_time' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$product_id = $wpdb->insert_id;
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'inventory_product_detail',
array(
'product_id' => $product_id,
'component_type_id' => $line_data['component_type_id'],
'reference_id' => $line_data['reference_id'],
'qty' => $line_data['qty'],
'material_cost' => $line_data['material_cost'],
'wage_cost' => $line_data['wage_cost'],
'misc_cost' => $line_data['misc_cost'],
'machine_cost' => $line_data['machine_cost'],
'ttl_cost' => $line_data['ttl_cost'],
'remark' => $line_data['remark'],
'sequence' => ($idx+1),
'show_in_preparation_list' => $line_data['show']
)
);
}
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Product recipe updated';
$arr_result['id'] = $product_id;
$arr_result['sku_id']= $_POST['sku_id'];
$arr_result['action'] = 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to insert product recipet';
}
} elseif($_POST['action']=='Edit') {
if($wpdb->update(
'inventory_product',
array(
'sku' => $_POST['sku'],
'sku_id' => $_POST['sku_id'],
'name' => $_POST['name'],
'production_qty' => $production_qty,
'stock_qty' => $_POST['stock_qty'],
'safety_qty' => $_POST['safety_qty'],
'unit_id' => $_POST['unit_id'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => number_format($total_cost/$production_qty,3,".",""),
'unit_cost_with_wastage' => number_format($total_cost_with_wastage/$production_qty,3,".",""),
'total_weight' => $_POST['total_weight'],
'total_time' => $_POST['total_time'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)>=0){
if($wpdb->delete('inventory_product_detail', array('product_id' => $_POST['id']))>=0){
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'inventory_product_detail',
array(
'product_id' => $_POST['id'],
'component_type_id' => $line_data['component_type_id'],
'reference_id' => $line_data['reference_id'],
'qty' => $line_data['qty'],
'material_cost' => $line_data['material_cost'],
'wage_cost' => $line_data['wage_cost'],
'misc_cost' => $line_data['misc_cost'],
'machine_cost' => $line_data['machine_cost'],
'ttl_cost' => $line_data['ttl_cost'],
'remark' => $line_data['remark'],
'sequence' => ($idx+1),
'show_in_preparation_list' => $line_data['show']
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'Product recipet updated';
$arr_result['id']= $_POST['id'];
$arr_result['sku_id']= $_POST['sku_id'];
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update product recipet';
}
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update product recipet';
}
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="showIngredientTable"){
if(empty($_POST['qty']) || empty($_POST['component_type_id']) || empty($_POST['reference_id'])){
$arr_result['condition'] = 'fail';
$arr_result['message'] = 'qty/component_type_id/reference_id is missing';
} else {
$arr_result['condition'] = 'success';
$arr_result['message'] = 'success';
$arr_result['content'] = getIngredientTable($_POST['component_type_id'],$_POST['reference_id'],$_POST['qty']);
}
echo json_encode($arr_result);
}
if($_POST['section']=="get_process_type_list"){
$arr_result = array();
$arr_result['data'] = array();
$process_type_list = get_process_type_list();
foreach($process_type_list as $idx=>$type){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$type."</span><input type='text' id='".$idx."-type-name' name='".$idx."-type-name' value='".$type."' callout='".$type."' class='edit_type-name'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_process_constant_list"){
$arr_result = array();
$arr_result['data'] = array();
$process_constant_list = get_process_constant_list();
foreach($process_constant_list as $idx=>$constant){
array_push($arr_result['data'],
array(
$constant->id,
"<input type='text' id='".$constant->id."-constant-name' name='".$constant->id."-constant-name' value='".$constant->name."' callout='".$constant->name."' class='edit_constant-name'>",
"<input type='text' id='".$constant->id."-constant-value' name='".$constant->id."-constant-value' value='".$constant->value."' callout='".$constant->value."' class='edit_constant-value'>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_process_baker_type_list"){
$arr_result = array();
$arr_result['data'] = array();
$process_baker_type_list = get_process_baker_type_list();
foreach($process_baker_type_list as $idx=>$baker){
array_push($arr_result['data'],
array(
$baker->id,
"<input type='text' id='".$baker->id."-baker-name' name='".$baker->id."-baker-name' value='".$baker->name."' callout='".$baker->name."' class='edit_baker-name'>",
"<input type='text' id='".$baker->id."-baker-monthly_wage' name='".$baker->id."-baker-monthly_wage' value='".$baker->monthly_wage."' callout='".$baker->monthly_wage."' class='edit_baker-monthly_wage'>",
"<span id='".$baker->id."-baker-daily_wage'>".$baker->daily_wage."</span>",
"<span id='".$baker->id."-baker-hourly_wage'>".$baker->hourly_wage."</span>",
"<span id='".$baker->id."-baker-minutely_wage'>".$baker->minutely_wage."</span>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_process_machine_list"){
$arr_result = array();
$arr_result['data'] = array();
$process_machine_list = get_process_machine_list();
foreach($process_machine_list as $idx=>$machine){
array_push($arr_result['data'],
array(
$machine->id,
"<input type='text' id='".$machine->id."-machine-name' name='".$machine->id."-machine-name' value='".$machine->name."' callout='".$machine->name."' class='edit_machine-name'>",
"<input type='text' id='".$machine->id."-machine-price' name='".$machine->id."-machine-price' value='".$machine->price."' callout='".$machine->price."' class='edit_machine-price'>",
"<span id='".$machine->id."-machine-price_per_year'>".$machine->price_per_year."</span>",
"<span id='".$machine->id."-machine-price_per_month'>".$machine->price_per_month."</span>",
"<span id='".$machine->id."-machine-price_per_day'>".$machine->price_per_day."</span>",
"<span id='".$machine->id."-machine-price_per_hour'>".$machine->price_per_hour."</span>",
"<span id='".$machine->id."-machine-price_per_minute'>".$machine->price_per_minute."</span>",
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_process_misc_cost_list"){
$arr_result = array();
$arr_result['data'] = array();
$process_misc_cost_list = get_process_misc_cost_list();
foreach($process_misc_cost_list as $idx=>$misc){
array_push($arr_result['data'],
array(
$misc->id,
"<input type='text' id='".$misc->id."-misc-name' name='".$misc->id."-misc-name' value='".$misc->name."' callout='".$misc->name."' class='edit_misc-name'>",
"<input type='text' id='".$misc->id."-misc-monthly_cost' name='".$misc->id."-monthly_cost' value='".$misc->monthly_cost."' callout='".$misc->monthly_cost."' class='edit_misc-monthly_cost'>",
"<span id='".$misc->id."-misc-daily_cost'>".$misc->daily_cost."</span>",
"<span id='".$misc->id."-misc-hourly_cost'>".$misc->hourly_cost."</span>",
"<span id='".$misc->id."-misc-minutely_cost'>".$misc->minutely_cost."</span>",
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_process_info"){
$arr_result = array();
if($_POST['id']!="") {
/*
$result = $wpdb->get_results("
SELECT process.code as code, process.id as process_id, process.name as process_name, type.name as type_name,
IFNULL(baker_type.minutely_wage, 0) as baker_wage_per_minute,
process.is_misc as need_misc, IFNULL(machine.price_per_minute, 0) as machine_cost_per_minute
FROM inventory_process process
LEFT JOIN inventory_process_type type ON type.id = process.type_id
LEFT JOIN inventory_process_baker_type baker_type ON baker_type.id = process.baker_type_id
LEFT JOIN inventory_process_machine machine ON machine.id = process.machine_id
WHERE process.id = '".$_POST['id']."' LIMIT 1
");
*/
$result = $wpdb->get_results("
SELECT type.name as type_name,
IFNULL(baker_type.minutely_wage, 0) as baker_wage_per_minute,
process.is_misc as need_misc, IFNULL(machine.price_per_minute, 0) as machine_cost_per_minute
FROM inventory_process process
LEFT JOIN inventory_process_type type ON type.id = process.type_id
LEFT JOIN inventory_process_baker_type baker_type ON baker_type.id = process.baker_type_id
LEFT JOIN inventory_process_machine machine ON machine.id = process.machine_id
WHERE process.id = '".$_POST['id']."' LIMIT 1
");
$arr_data = array();
$arr_data['type_name'] = $result[0]->type_name;
$arr_data['wage_cost'] = number_format($_POST['minute'] * $result[0]->baker_wage_per_minute,4,".","");
$arr_data['machine_cost'] = number_format($_POST['minute'] * $result[0]->machine_cost_per_minute,4,".","");
if($result[0]->need_misc=="1"){
$arr_data['misc_cost'] = number_format($_POST['minute'] * preset_total_misc_cost("minutely_cost"),4,".","");
} else {
$arr_data['misc_cost'] = 0;
}
$arr_data['ttl_cost'] = $arr_data['wage_cost'] + $arr_data['machine_cost'] + $arr_data['misc_cost'];
/*
$result[0]->wage_cost = number_format($_POST['minute'] * $result[0]->baker_wage_per_minute,3,".","");
$result[0]->machine_cost = number_format($_POST['minute'] * $result[0]->machine_cost_per_minute,3,".","");
if($result[0]->need_misc=="1"){
$result[0]->misc_cost = number_format($_POST['minute'] * preset_total_misc_cost("minutely_cost"),3,".","");
} else {
$result[0]->misc_cost = 0;
}
$result[0]->ttl_cost = $result[0]->wage_cost + $result[0]->machine_cost + $result[0]->misc_cost;
*/
$arr_result['condition']='success';
$arr_result['data']=$arr_data;
//$arr_result['data']=$result[0];
} else {
$arr_result['condition']='fail';
$arr_result['message']='unable to lookup process detail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="get_min_process_info"){
$arr_result = array();
if($_POST['id']!="") {
$result = $wpdb->get_results("
SELECT type.name as type_name
FROM inventory_process process
LEFT JOIN inventory_process_type type ON type.id = process.type_id
WHERE process.id = '".$_POST['id']."' LIMIT 1
");
$arr_data = array();
$arr_data['type_name'] = $result[0]->type_name;
$arr_result['condition']='success';
$arr_result['data']=$arr_data;
} else {
$arr_result['condition']='fail';
$arr_result['message']='unable to lookup process detail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="add_value_to_bop_list"){
$arr_result = array();
$depreciation_year = get_constant_value("Depreciation Year");
$month_per_year = get_constant_value("Month per Year");
$day_per_year = get_constant_value("Day per Year");
$working_day_per_month = get_constant_value("Working Day per Month");
$hour_per_day = get_constant_value("Hour per Day");
$working_hour_per_day = get_constant_value("Working Hour per Day");
if($_POST['type']=="Type"){
$table = "inventory_process_type";
$title_id = 'type_list_title';
$title = 'Process Type';
$table_id = 'dataTable_type';
$return_div_id = 'type_section';
$selector_id = 'type_id';
$arr_data = array('name' => $_POST['value']);
$html_output = "<select name='type_id' id='type_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($process_type_list as $idx=>$type){
$html_output .= "<option value='".$idx."' data-tokens='".$type."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $type;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_type_btn' value='New Type' title='Click here to add a new type into list'>";
} elseif($_POST['type']=="Constant") {
$table = "inventory_process_constant";
$title_id = 'constant_list_title';
$title = 'Constant';
$table_id = 'dataTable_constant';
$return_div_id = 'constant_section';
$selector_id = 'constant_id';
$arr_data = array('name' => $_POST['value'], 'value' => $_POST['price']);
$html_output = "";
} elseif($_POST['type']=="Baker") {
$table = "inventory_process_baker_type";
$title_id = 'baker_type_list_title';
$title = 'Baker Type';
$table_id = 'dataTable_baker';
$return_div_id = 'baker_section';
$selector_id = 'baker_type_id';
$monthly_wage = $_POST['price'];
$daily_wage = round($monthly_wage / $working_day_per_month,4);
$hourly_wage = round($daily_wage / $working_hour_per_day,4);
$minutely_wage = round($hourly_wage / 60, 4);
$arr_data = array('name' => $_POST['value'], 'monthly_wage' => $monthly_wage, 'daily_wage' => $daily_wage, 'hourly_wage' => $hourly_wage, 'minutely_wage' => $minutely_wage);
$html_output = "<select name='baker_type_id' id='baker_type_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($process_baker_list as $idx=>$baker){
$html_output .= "<option value='".$idx."' data-tokens='".$baker."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $baker;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_baker_btn' value='New Baker Wage Type' title='Click here to add a new baker wage type into list'>";
} elseif($_POST['type']=="Machine") {
$table = "inventory_process_machine";
$title_id = 'machine_list_title';
$title = 'Machine List';
$table_id = 'dataTable_machine';
$return_div_id = 'machine_section';
$selector_id = 'machine_id';
$price = $_POST['price'];
$price_per_year = round($price / $depreciation_year, 4);
$price_per_month = round($price_per_year / $month_per_year, 4);
$price_per_day = round($price_per_month / $working_day_per_month, 4);
$price_per_hour = round($price_per_day / $working_hour_per_day, 4);
$price_per_minute = round($price_per_hour / 60, 4);
$arr_data = array('name' => $_POST['value'], 'price' => $price, 'price_per_year' => $price_per_year, 'price_per_month' => $price_per_month, 'price_per_day' => $price_per_day, 'price_per_hour' => $price_per_hour, 'price_per_minute' => $price_per_minute);
$html_output = "<select name='machine_id' id='machine_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($process_machine_list as $idx=>$machine){
$html_output .= "<option value='".$idx."' data-tokens='".$machine."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $machine;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_baker_btn' value='New Baker Wage Type' title='Click here to add a new baker wage type into list'>";
} elseif($_POST['type']=="Misc") {
$table = "inventory_process_misc_cost";
$title_id = 'misc_list_title';
$title = 'Misc. Cost';
$table_id = 'dataTable_misc';
$return_div_id = 'misc_section';
$selector_id = 'misc_id';
$monthly_cost = $_POST['price'];
$daily_cost = round($monthly_cost / $working_day_per_month, 4);
$hourly_cost = round($daily_cost / $working_hour_per_day, 4);
$minutely_cost = round($hourly_cost / 60, 4);
$arr_data = array('name' => $_POST['value'], 'monthly_cost' => $monthly_cost, 'daily_cost' => $daily_cost, 'hourly_cost' => $hourly_cost, 'minutely_cost' => $minutely_cost);
$html_output = "";
}
if($wpdb->insert($table, $arr_data)){
$process_type_list = get_process_type_list();
$process_baker_list = get_process_baker_wage_type_list();
$process_machine_list = get_process_machine_type_list();
if($_POST['type']=="Type"){
$html_output = "<select name='type_id' id='type_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($process_type_list as $idx=>$type){
$html_output .= "<option value='".$idx."' data-tokens='".$type."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $type;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_type_btn' value='New Type' title='Click here to add a new type into list'>";
} elseif($_POST['type']=="Constant") {
$html_output = "";
} elseif($_POST['type']=="Baker") {
$html_output = "<select name='baker_type_id' id='baker_type_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($process_baker_list as $idx=>$baker){
$html_output .= "<option value='".$idx."' data-tokens='".$baker."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $baker;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_baker_btn' value='New Baker Wage Type' title='Click here to add a new baker wage type into list'>";
} elseif($_POST['type']=="Machine") {
$html_output = "<select name='machine_id' id='machine_id' data-live-search='true' class='selectpicker'><option></option>";
foreach($process_machine_list as $idx=>$machine){
$html_output .= "<option value='".$idx."' data-tokens='".$machine."' ";
if($idx==$_POST['default_value']){
$html_output .= "selected";
}
$html_output .= ">";
$html_output .= $machine;
$html_output .= "</option>";
}
$html_output .= "</select> <input type='button' class='new_baker_btn' value='New Baker Wage Type' title='Click here to add a new baker wage type into list'>";
} elseif($_POST['type']=="Misc") {
$html_output = "";
}
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Value is added successfully';
$arr_result['title_id'] = $title_id;
$arr_result['title'] = $title;
$arr_result['table_id'] = $table_id;
$arr_result['return_div_id'] = $return_div_id;
$arr_result['selector_id'] = $selector_id;
$arr_result['html_output'] = $html_output;
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Unable to add value';
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_bop_test"){
if($_POST['method']=='calculate'){
/*
echo "<pre>";
print_r($_POST);
echo "</pre>";
*/
$wastage = get_constant_value("Process Wastage");
$arr_result['condition']='success';
$arr_result['content']=array();
$total_cost=0;
foreach($_POST['row'] as $idx=>$row){
$arr_line = array();
$process_id = $_POST['process_id'][$idx];
$processObj = get_process_item_info($process_id);
$arr_line['row'] = $row;
$arr_line['process_id'] = $process_id;
$arr_line['type'] = $processObj->type_name;
$arr_line['minute'] = $_POST['minute'][$idx];
$arr_line['wage_cost'] = number_format($_POST['minute'][$idx] * $processObj->baker_wage_per_minute,4,".","");
$arr_line['machine_cost'] = number_format($_POST['minute'][$idx] * $processObj->machine_cost_per_minute,4,".","");
if($processObj->need_misc=="1"){
$arr_line['misc_cost'] = number_format($_POST['minute'][$idx] * preset_total_misc_cost("minutely_cost"),4,".","");
} else {
$arr_line['misc_cost'] = number_format(0,4,".","");
}
$arr_line['ttl_cost'] = $arr_line['wage_cost'] + $arr_line['machine_cost'] + $arr_line['misc_cost'];
$total_cost+=$arr_line['ttl_cost'];
$arr_line['ttl_cost'] = number_format($arr_line['ttl_cost'],4,".","");
array_push($arr_result['content'],$arr_line);
}
$arr_result['total_cost']=round($total_cost,4);
$arr_result['total_cost_with_wastage'] = round($total_cost * (1+$wastage),4);
$arr_result['unit_cost'] = round($arr_result['total_cost_with_wastage']/$_POST['production_qty'],4);
} else {
if($_POST['action']=='Add') {
if($wpdb->insert(
'sku_bop',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $_POST['total_cost'],
'total_cost_with_wastage' => $_POST['total_cost_with_wastage'],
'unit_cost' => $_POST['unit_cost'],
'create_time' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$bop_id = $wpdb->insert_id;
foreach($_POST['process_id'] as $idx => $process_id){
$wpdb->insert(
'sku_bop_detail',
array(
'bop_id' => $bop_id,
'process_id' => $process_id,
'minute' => $_POST['minute'][$idx],
'wage_cost' => $_POST['wage_cost'][$idx],
'misc_cost' => $_POST['misc_cost'][$idx],
'machine_cost' => $_POST['machine_cost'][$idx],
'ttl_cost' => $_POST['ttl_cost'][$idx],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOP updated';
$arr_result['id']= $bop_id;
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to insert BOP';
}
} elseif($_POST['action']=='Edit') {
if($wpdb->update(
'sku_bop',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $_POST['total_cost'],
'total_cost_with_wastage' => $_POST['total_cost_with_wastage'],
'unit_cost' => $_POST['unit_cost'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)>=0){
if($wpdb->delete('sku_bop_detail', array('bop_id' => $_POST['id']))>=0){
foreach($_POST['process_id'] as $idx => $process_id){
$wpdb->insert(
'sku_bop_detail',
array(
'bop_id' => $_POST['id'],
'process_id' => $process_id,
'minute' => $_POST['minute'][$idx],
'wage_cost' => $_POST['wage_cost'][$idx],
'misc_cost' => $_POST['misc_cost'][$idx],
'machine_cost' => $_POST['machine_cost'][$idx],
'ttl_cost' => $_POST['ttl_cost'][$idx],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOP updated';
$arr_result['id']= $_POST['id'];
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOP2';
}
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOP1';
}
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="update_bop"){
$wastage = get_constant_value("Ingredient Wastage");
$total_cost = 0;
$total_cost_with_wastage = 0;
$unit_cost = 0;
$arr_data = array();
foreach($_POST['row'] as $idx=>$row){
$arr_line = array();
$process_id = $_POST['process_id'][$idx];
$processObj = get_process_item_info($process_id);
$arr_line['row'] = $row;
$arr_line['process_id'] = $process_id;
$arr_line['type'] = $processObj->type_name;
$arr_line['minute'] = $_POST['minute'][$idx];
$arr_line['wage_cost'] = number_format($_POST['minute'][$idx] * $processObj->baker_wage_per_minute,4,".","");
$arr_line['machine_cost'] = number_format($_POST['minute'][$idx] * $processObj->machine_cost_per_minute,4,".","");
if($processObj->need_misc=="1"){
$arr_line['misc_cost'] = number_format($_POST['minute'][$idx] * preset_total_misc_cost("minutely_cost"),4,".","");
} else {
$arr_line['misc_cost'] = number_format(0,4,".","");
}
$arr_line['ttl_cost'] = $arr_line['wage_cost'] + $arr_line['machine_cost'] + $arr_line['misc_cost'];
$total_cost += $arr_line['ttl_cost'];
$arr_line['ttl_cost'] = number_format($arr_line['ttl_cost'],4,".","");
array_push($arr_data,$arr_line);
}
//print_r($arr_data);
$total_cost = round($total_cost,4);
$total_cost_with_wastage = round($total_cost * (1+$wastage),4);
$unit_cost = round($total_cost_with_wastage/$_POST['production_qty'],4);
if($_POST['method']=='calculate'){
$arr_result['condition'] = 'success';
$arr_result['content'] = $arr_data;
$arr_result['total_cost'] = $total_cost;
$arr_result['total_cost_with_wastage'] = $total_cost_with_wastage;
$arr_result['unit_cost'] = $unit_cost;
} else {
if($_POST['action']=='Add') {
if($wpdb->insert(
'sku_bop',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => $unit_cost,
'create_time' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$bop_id = $wpdb->insert_id;
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'sku_bop_detail',
array(
'bop_id' => $bop_id,
'process_id' => $line_data['process_id'],
'minute' => $line_data['minute'],
'wage_cost' => $line_data['wage_cost'],
'misc_cost' => $line_data['misc_cost'],
'machine_cost' => $line_data['machine_cost'],
'ttl_cost' => $line_data['ttl_cost'],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOP updated';
$arr_result['id']= $bop_id;
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to insert BOP';
}
} elseif($_POST['action']=='Edit') {
if($wpdb->update(
'sku_bop',
array(
'sku_id' => $_POST['sku_id'],
'sku' => $_POST['sku'],
'production_qty' => $_POST['production_qty'],
'total_cost' => $total_cost,
'total_cost_with_wastage' => $total_cost_with_wastage,
'unit_cost' => $unit_cost,
'mod_time' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)>=0){
if($wpdb->delete('sku_bop_detail', array('bop_id' => $_POST['id']))>=0){
foreach($arr_data as $idx => $line_data){
$wpdb->insert(
'sku_bop_detail',
array(
'bop_id' => $_POST['id'],
'process_id' => $line_data['process_id'],
'minute' => $line_data['minute'],
'wage_cost' => $line_data['wage_cost'],
'misc_cost' => $line_data['misc_cost'],
'machine_cost' => $line_data['machine_cost'],
'ttl_cost' => $line_data['ttl_cost'],
'sequence' => ($idx+1)
)
);
}
$arr_result['condition']='success';
$arr_result['message']= 'BOP updated';
$arr_result['id']= $_POST['id'];
$arr_result['action']= 'Edit';
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOP2';
}
} else {
$arr_result['condition']='fail';
$arr_result['message']= 'Unable to update BOP1';
}
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="edit_bop_misc_setting"){
$depreciation_year = get_constant_value("Depreciation Year");
$month_per_year = get_constant_value("Month per Year");
$day_per_year = get_constant_value("Day per Year");
$working_day_per_month = get_constant_value("Working Day per Month");
$hour_per_day = get_constant_value("Hour per Day");
$working_hour_per_day = get_constant_value("Working Hour per Day");
$arr_result = array();
$arr_result["type"] = $_POST['type'];
$arr_result["element_id"] = $_POST['id'];
if($_POST['id']!="" && $_POST['type']!="" && $_POST['field']!="") {
if($_POST['type']=="type"){
$table = "inventory_process_type";
$arrData = array( $_POST['field'] => $_POST['nvalue']);
} elseif($_POST['type']=="constant") {
$table = "inventory_process_constant";
$arrData = array( $_POST['field'] => $_POST['nvalue']);
} elseif($_POST['type']=="baker") {
$table = "inventory_process_baker_type";
if($_POST['field']=="name"){
$arrData = array( $_POST['field'] => $_POST['nvalue']);
} elseif($_POST['field']=="monthly_wage") {
$monthly_wage = $_POST['nvalue'];
$daily_wage = round($monthly_wage / $working_day_per_month, 4);
$hourly_wage = round($daily_wage / $working_hour_per_day, 4);
$minutely_wage = round($hourly_wage / 60, 4);
$arrData = array('monthly_wage' => $monthly_wage, 'daily_wage' => $daily_wage, 'hourly_wage' => $hourly_wage, 'minutely_wage' => $minutely_wage);
$arr_result["daily_wage"] = $daily_wage;
$arr_result["hourly_wage"] = $hourly_wage;
$arr_result["minutely_wage"] = $minutely_wage;
}
} elseif($_POST['type']=="machine") {
$table = "inventory_process_machine";
if($_POST['field']=="name"){
$arrData = array( $_POST['field'] => $_POST['nvalue']);
} elseif($_POST['field']=="price") {
$price = $_POST['nvalue'];
$price_per_year = round($price / $depreciation_year, 4);
$price_per_month = round($price_per_year / $month_per_year, 4);
$price_per_day = round($price_per_month / $working_day_per_month, 4);
$price_per_hour = round($price_per_day / $working_hour_per_day, 4);
$price_per_minute = round($price_per_hour / 60, 4);
$arrData = array('price' => $price, 'price_per_year' => $price_per_year, 'price_per_month' => $price_per_month, 'price_per_day' => $price_per_day, 'price_per_hour' => $price_per_hour, 'price_per_minute' => $price_per_minute);
$arr_result["price_per_year"] = $price_per_year;
$arr_result["price_per_month"] = $price_per_month;
$arr_result["price_per_day"] = $price_per_day;
$arr_result["price_per_hour"] = $price_per_hour;
$arr_result["price_per_minute"] = $price_per_minute;
}
} elseif($_POST['type']=="misc") {
$table = "inventory_process_misc_cost";
if($_POST['field']=="name"){
$arrData = array( $_POST['field'] => $_POST['nvalue']);
} elseif($_POST['field']=="monthly_cost") {
$monthly_cost = $_POST['nvalue'];
$daily_cost = round($monthly_cost / $working_day_per_month, 4);
$hourly_cost = round($daily_cost / $working_hour_per_day, 4);
$minutely_cost = round($hourly_cost / 60, 4);
$arrData = array('monthly_cost' => $monthly_cost, 'daily_cost' => $daily_cost, 'hourly_cost' => $hourly_cost, 'minutely_cost' => $minutely_cost);
$arr_result["daily_cost"] = $daily_cost;
$arr_result["hourly_cost"] = $hourly_cost;
$arr_result["minutely_cost"] = $minutely_cost;
}
}
if($wpdb->update($table, $arrData, array('id'=>$_POST['id']))){
$arr_result['id'] = $_POST['id']."-".$_POST['type']."-".$_POST['field'];
$arr_result['callout'] = $_POST['nvalue'];
$arr_result['condition']='success';
} else {
$arr_result['condition']='fail';
}
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
// add/edit inventory process //
if($_POST['section']=="process_init"){
if($_POST['action']=='Add') {
$record = $wpdb->get_results("SELECT code FROM `inventory_process` WHERE `code` = '".$_POST['code']."' LIMIT 1");
if(count($record)>0){
$arr_result['condition']='fail';
$arr_result['message'] = 'Process Code is already used by another item';
} else {
if($wpdb->insert(
'inventory_process',
array(
'code' => $_POST['code'],
'type_id' => $_POST['type_id'],
'name' => $_POST['name'],
'baker_type_id' => $_POST['baker_type_id'],
'is_misc' => $_POST['is_misc'],
'machine_id' => $_POST['machine_id'],
'status' => '1',
'create_date' => current_time('mysql'),
'create_by' => $_POST['user_id'],
'mod_date' => current_time('mysql'),
'mod_by' => $_POST['user_id']
)
)){
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Process is added successfully';
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Unable to create new process';
}
}
} elseif($_POST['action']=='Edit') {
if($_POST['ocode']==$_POST['code']){
$pass = true;
} else {
$record = $wpdb->get_results("SELECT code FROM `inventory_process` WHERE `code` = '".$_POST['code']."' LIMIT 1");
if(count($record)>0){
$pass = false;
} else {
$pass = true;
}
}
if($pass==true){
if($wpdb->update(
'inventory_process',
array(
'code' => $_POST['code'],
'type_id' => $_POST['type_id'],
'name' => $_POST['name'],
'baker_type_id' => $_POST['baker_type_id'],
'is_misc' => $_POST['is_misc'],
'machine_id' => $_POST['machine_id'],
'status' => '1',
'mod_date' => current_time('mysql'),
'mod_by' => $_POST['user_id']
),
array('id'=>$_POST['id'])
)){
$arr_result['condition'] = 'success';
$arr_result['message'] = 'Process is updated successfully';
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Unable to update process detail';
}
} else {
$arr_result['condition']='fail';
$arr_result['message'] = 'Process Code is already used by another item';
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="sku_more_menu"){
$arr_result = array();
$result = $wpdb->get_results("SELECT * FROM stock_init WHERE id = '".$_POST['id']."' LIMIT 1 ");
$bomResult = $wpdb->get_results("SELECT * FROM sku_bom WHERE sku_id = '".$_POST['id']."' LIMIT 1");
if(count($bomResult)>0){
$hasBOM = true;
$btnBOMBadge = '';
} else {
$hasBOM = false;
$btnBOMBadge = '<span class="badge badge-pill badge-danger">!</span>';
}
$bopResult = $wpdb->get_results("SELECT * FROM sku_bop WHERE sku_id = '".$_POST['id']."' LIMIT 1");
if(count($bopResult)>0){
$hasBOP = true;
$btnBOPBadge = '';
} else {
$hasBOP = false;
$btnBOPBadge = '<span class="badge badge-pill badge-danger">!</span>';
}
$recipeResult = $wpdb->get_results("SELECT * FROM inventory_product WHERE sku_id = '".$_POST['id']."' LIMIT 1");
if(count($recipeResult)>0){
$hasRecipe = true;
$btnRecipeBadge = '';
$printRecipeStyle = '';
} else {
$hasRecipe = false;
$btnRecipeBadge = '<span class="badge badge-pill badge-danger">!</span>';
$printRecipeStyle = 'disabled';
}
$arr_result['content'] = "<tr><td colspan='3'><h4>".$result[0]->sku." (".$result[0]->description.")</h4></td><td class='text-right'><button id='cancel' name='cancel' class='btn btn-danger'><i class='fas fa-times'></i></button></td></tr>";
/*
$arr_result['content'] .= "<tr>
<td><button id='bom_".$_POST['id']."' type='button' class='btn btn-block btnBOM btn-outline-dark'>BOM ".$btnBOMBadge."</button></td>
<td><button id='bop_".$_POST['id']."' type='button' class='btn btn-block btnBOP btn-outline-dark'>BOP ".$btnBOPBadge."</button></td>
<td><button id='recipe_".$_POST['id']."' type='button' class='btn btn-block btnRECIPE btn-outline-dark'>Recipe ".$btnRecipeBadge."</button></td>
<td><button id='printRcipe_".$recipeResult[0]->id."' type='button' class='btn btn-block btnPRINTRECIPE btn-outline-dark' ".$printRecipeStyle.">Print Recipe</button></td>
</tr>";
$arr_result['content'] .= "<tr>
<td><button id='btn_".$_POST['id']."_".$result[0]->sku."' type='button' class='btn btn-block btnRemove btn-outline-dark'>Remove SKU</button></td>
</tr>";
*/
$arr_result['content'] .= "<tr>
<td><button id='recipe_".$_POST['id']."' type='button' class='btn btn-block btnRECIPE btn-outline-dark'>Recipe ".$btnRecipeBadge."</button></td>
<td><button id='printRcipe_".$recipeResult[0]->id."' type='button' class='btn btn-block btnPRINTRECIPE btn-outline-dark' ".$printRecipeStyle.">Print Recipe</button></td>
<td><button id='btn_".$_POST['id']."_".$result[0]->sku."' type='button' class='btn btn-block btnRemove btn-outline-dark'>Remove SKU</button></td>
</tr>";
//<td><button id='ing_".$_POST['id']."' type='button' class='btn btn-block btnING btn-outline-dark'>Ingredient Table</button></td>
echo json_encode($arr_result);
}
if($_POST['section']=="save_ipl"){
//$wpdb->query('TRUNCATE TABLE `inventory_preparation_list`');
$wpdb->delete("inventory_preparation_list", array( 'delivery_date' => $_POST['delivery_date'] ) );
$hash = md5(time());
$save_time = date("Y-m-d H:i:s");
foreach($_POST['unit_qty'] as $idx=>$unit_qty){
$wpdb->insert(
'inventory_preparation_list',
array(
'product_id' => $_POST['product_id'][$idx],
'sku_id' => $_POST['sku_id'][$idx],
'sku' => $_POST['sku'][$idx],
'name' => $_POST['desc'][$idx],
'order_qty' => $_POST['order_qty'][$idx],
'qty_per_unit' => $_POST['qty_per_unit'][$idx],
'confirmed_production_qty' => $_POST['unit_qty'][$idx],
'confirmed_production_qty_pic' => $_POST['qty'][$idx],
'delivery_date' => $_POST['delivery_date'],
'hash' => $hash
)
);
}
$arr_result = array("condition"=>"success", "message"=>"data is saved.");
echo json_encode($arr_result);
}
if($_POST['section']=="update_holiday"){
if($_POST['action']=='add') {
if($_POST['post_date']!=""){
if($wpdb->insert(
'holiday_list',
array(
'holiday' => $_POST['post_date']
)
)){
$arr_result = array("condition"=>"success", "message"=>"Holiday is added");
} else {
$arr_result = array("condition"=>"fail", "message"=>"Error in inserting new holiday");
}
} else {
$arr_result = array("condition"=>"fail", "message"=>"Enter a date");
}
} elseif($_POST['action']=='remove') {
if($wpdb->delete("holiday_list", array( 'id' => $_POST['id'] ) )){
$arr_result = array("condition"=>"success", "message"=>"Holiday is removed");
} else {
$arr_result = array("condition"=>"fail", "message"=>"Error in removing holiday");
}
} elseif($_POST['action']=='edit') {
if($_POST['post_date']!=""){
if($wpdb->update('holiday_list', array( 'holiday' => $_POST['post_date']),array('id'=>$_POST['id']))){
$arr_result = array("condition"=>"success", "message"=>"Holiday is edited");
} else {
$arr_result = array("condition"=>"fail", "message"=>"Error in editing holiday");
}
} else {
$arr_result = array("condition"=>"fail", "message"=>"Enter a date");
}
}
echo json_encode($arr_result);
}
if($_POST['section']=="get_domain_blacklist"){
$arr_result = array();
$arr_result['data'] = array();
$domain_blacklist = get_domain_blacklist();
foreach($domain_blacklist as $idx=>$domain){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$domain."</span><input type='text' id='".$idx."-domain' name='".$idx."-domain' value='".$domain."' callout='".$domain."' class='edit_domain'>",
"<button type='button' class='btn btn-sm btn-danger del_phrase' id='".$idx."-delete-domain'><i class='fa fa-trash' aria-hidden='true'></i></button>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="get_phrase_blacklist"){
$arr_result = array();
$arr_result['data'] = array();
$phrase_blacklist = get_phrase_blacklist();
foreach($phrase_blacklist as $idx=>$phrase){
array_push($arr_result['data'],
array(
$idx,
"<span style='display:none'>".$phrase."</span><input type='text' id='".$idx."-phrase' name='".$idx."-phrase' value='".$phrase."' callout='".$phrase."' class='edit_phrase'>",
"<button type='button' class='btn btn-sm btn-danger del_phrase' id='".$idx."-delete-phrase'><i class='fa fa-trash' aria-hidden='true'></i></button>"
)
);
}
$arr_result['recordsTotal'] = count($arr_result['data']);
$arr_result['recordsFiltered'] = count($arr_result['data']);
echo json_encode($arr_result);
}
if($_POST['section']=="edit_blacklist_setting"){
$arr_result = array();
if($_POST['id']!="" && $_POST['type']!="") {
if($_POST['type']=="domain"){
$table = "custom_keyword_blacklist";
$wpdb->update($table, array( "name" => $_POST['nvalue']),array('id'=>$_POST['id']));
} elseif($_POST['type']=="phrase") {
$table = "custom_keyword_blacklist";
$wpdb->update($table, array( "name" => $_POST['nvalue']),array('id'=>$_POST['id']));
}
$arr_result['id'] = $_POST['id']."-".$_POST['type'];
$arr_result['callout'] = $_POST['nvalue'];
$arr_result['condition']='success';
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
if($_POST['section']=="delete_blacklist"){
$arr_result = array();
if($_POST['id']!="") {
$table = "custom_keyword_blacklist";
$wpdb->delete($table, array('id'=>$_POST['id']));
//$arr_result['id'] = $_POST['id']."-".$_POST['type'];
//$arr_result['callout'] = $_POST['nvalue'];
$arr_result['condition']='success';
} else {
$arr_result['condition']='fail';
}
echo json_encode($arr_result);
}
?>