File: /var/www/html/breadsecret.com_bak20260330/wp-content/themes/zeen-child/functions.php.20230922a
<?php
if (!session_id()) {
session_start();
}
// update stock value for nemake table
function update_stock_remake($stock_date, $sku, $value)
{
global $wpdb;
$result = $wpdb->get_results("SELECT id FROM `sku_stock_remake` WHERE stock_date = '".$stock_date."' AND sku = '".$sku."' LIMIT 1");
if(count($result)>0){
// update
$data = array(
'remain' => $value
);
$wpdb->update('sku_stock_remake', $data, array('id'=>$result[0]->id));
} else {
// insert
$data = array(
'stock_date' => $stock_date,
'stock_dayofweek' => date('l', strtotime($stock_date)),
'sku' => $sku,
'remain' => $value
);
$wpdb->insert('sku_stock_remake', $data);
}
}
// global function for rounding up number
function round_up($value, $precision)
{
$pow = pow(10, $precision);
return (ceil($pow * $value) + ceil($pow * $value - ceil($pow * $value))) / $pow;
}
//get material type list
function get_material_type_list()
{
global $wpdb;
$material_type_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_material_type` ORDER BY id");
foreach ($result as $idx => $material_type) {
$material_type_list[$material_type->id] = $material_type->name;
}
return $material_type_list;
}
//get material brand list
function get_material_brand_list()
{
global $wpdb;
$material_brand_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_material_brand` ORDER BY id");
foreach ($result as $idx => $material_brand) {
$material_brand_list[$material_brand->id] = $material_brand->name;
}
return $material_brand_list;
}
//get material supplier list
function get_material_supplier_list()
{
global $wpdb;
$material_supplier_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_material_supplier` ORDER BY id");
foreach ($result as $idx => $material_supplier) {
$material_supplier_list[$material_supplier->id] = $material_supplier->name;
}
return $material_supplier_list;
}
//get material measure unit
function get_measure_unit_list()
{
global $wpdb;
$measure_unit_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_measure_unit` ORDER BY id");
foreach ($result as $idx => $measure_unit) {
$measure_unit_list[$measure_unit->id] = $measure_unit->name;
}
return $measure_unit_list;
}
//get material procedure list
function get_procedure_list()
{
global $wpdb;
$procedure_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_material_procedure` ORDER BY id");
foreach ($result as $idx => $procedure) {
$procedure_list[$procedure->id] = $procedure->name;
}
return $procedure_list;
}
//get material attribute list
function get_material_attribute_list()
{
global $wpdb;
$attribute_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_material_attribute` ORDER BY id");
foreach ($result as $idx => $attribute) {
$attribute_list[$attribute->id] = $attribute->name;
}
return $attribute_list;
}
//get sfproduct attribute list
function get_sfproduct_attribute_list()
{
global $wpdb;
$attribute_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_sfproduct_attribute` ORDER BY id");
foreach ($result as $idx => $attribute) {
$attribute_list[$attribute->id] = $attribute->name;
}
return $attribute_list;
}
//get sfproduct category list
function get_sfproduct_category_list()
{
global $wpdb;
$category_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_sfproduct_category` ORDER BY id");
foreach ($result as $idx => $category) {
$category_list[$category->id] = $category->name;
}
return $category_list;
}
//get preset misc cost total
function preset_total_misc_cost($type = "minutely_cost")
{
global $wpdb;
$result = $wpdb->get_results("
SELECT SUM(`" . $type . "`) as cost
FROM inventory_process_misc_cost
WHERE status = 1
");
if (count($result) > 0) {
return number_format($result[0]->cost, 4, '.', '');
} else {
return 0;
}
}
//get process type list
function get_process_type_list()
{
global $wpdb;
$process_type_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_process_type` ORDER BY id");
foreach ($result as $idx => $process_type) {
$process_type_list[$process_type->id] = $process_type->name;
}
return $process_type_list;
}
//get process baker type list
function get_process_baker_wage_type_list()
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `inventory_process_baker_type` ORDER BY id");
foreach ($result as $idx => $wage_type) {
$wage_type_list[$wage_type->id] = $wage_type->name;
}
return $wage_type_list;
}
//get process machine list
function get_process_machine_type_list()
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `inventory_process_machine` ORDER BY id");
foreach ($result as $idx => $machine_type) {
$machine_type_list[$machine_type->id] = $machine_type->name;
}
return $machine_type_list;
}
//get process constant list
function get_process_constant_list()
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `inventory_process_constant` ORDER BY id");
return $result;
}
//get process baker type list
function get_process_baker_type_list()
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `inventory_process_baker_type` ORDER BY id");
return $result;
}
//get process machine list
function get_process_machine_list()
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `inventory_process_machine` ORDER BY id");
return $result;
}
//get process misc cost list
function get_process_misc_cost_list()
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `inventory_process_misc_cost` ORDER BY id");
return $result;
}
// get process item info
function get_process_item_info($process_id)
{
global $wpdb;
if ($process_id != "") {
$result = $wpdb->get_results("
SELECT process.code as code, process.id as process_id, process.name as process_name, process.name as item_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 = '" . $process_id . "' LIMIT 1
");
if (count($result) > 0) {
return $result[0];
} else {
return null;
}
} else {
return null;
}
}
// get ingredient content from BOM
function get_ingredient_content_from_bom($sku_id)
{
global $wpdb;
$skuObj = $wpdb->get_results("SELECT * FROM stock_init WHERE id = '" . $sku_id . "' LIMIT 1 ");
$result = $wpdb->get_results("
SELECT mat.display_name, sum(qty) as grouped_qty, bom.production_qty FROM sku_bom bom LEFT JOIN sku_bom_detail detail ON detail.bom_id = bom.id LEFT JOIN inventory_material mat ON mat.id = detail.material_id WHERE bom.sku_id = '" . $sku_id . "' AND mat.show_in_label = 'Y' GROUP BY mat.display_name ORDER BY grouped_qty DESC
");
$arr_result = array();
$arr_result['sku_id'] = $sku_id;
$arr_result['sku'] = $skuObj[0]->sku;
$arr_result['description'] = $skuObj[0]->description;
$arr_result['production_qty'] = $result[0]->production_qty ?? 0;
$arr_result['content'] = array();
$arr_label = array();
$i = 1;
foreach ($result as $obj) {
array_push($arr_label, $obj->display_name);
$arr_content = array();
$arr_content['rank'] = $i;
$arr_content['name'] = $obj->display_name;
$arr_content['weight'] = number_format($obj->grouped_qty, 2, ".", ",");
array_push($arr_result['content'], $arr_content);
$i++;
}
$arr_result['label'] = ucfirst(implode(", ", $arr_label)) . ".";
return $arr_result;
}
// added by samiel 2022-08-09 //
// add empty row for sfproduct
function append_empty_row_for_sfproduct($i)
{
$empty_row = "<tr id='row-" . $i . "'>";
$empty_row .= "<td><input type='hidden' name='row[]' value='" . $i . "'><input type='hidden' name='show[]' id='show-" . $i . "' value='1'>";
$empty_row .= "<div class='custom-control custom-switch custom-switch-md'>";
$empty_row .= "<input type='checkbox' class='custom-control-input' id='customSwitches-" . $i . "' checked>";
$empty_row .= "<label class='custom-control-label' for='customSwitches-" . $i . "'></label>";
$empty_row .= "</div></td>";
$empty_row .= "<td><select name='component_type_id[]' id='component_type_id-" . $i . "' data-live-search='true' class='component selectpicker show-tick'><option></option>";
$empty_row .= get_component_option_list(3);
$empty_row .= "</select></td>";
$empty_row .= "<td id='reference-" . $i . "'><select name='reference_id[]' id='reference_id-" . $i . "' data-live-search='true' class='reference selectpicker show-tick'><option></option>" . get_material_option_list('ingredient') . "</select></td>";
$empty_row .= "<td><input type='number' id='qty-" . $i . "' name='qty[]' value='0' min='0' step='ANY' class='qty' style='width: 80px !important;' readonly></td>";
$empty_row .= "<td><div id='unit-" . $i . "'></div></td>";
$empty_row .= "<td><div id='ttl_cost-" . $i . "'></div></td>";
$empty_row .= "<td><textarea id='remark-" . $i . "' name='remark[]' class='remark' rows='3' readonly>" . $obj->remark . "</textarea></td>";
$empty_row .= "<td><i class='text-danger fas fa-times fa-2x btnRemove' aria-hidden='true' style='cursor:pointer' title='Remove this Process'></i></td>";
$empty_row .= "</tr>";
return $empty_row;
}
// added by samiel 2022-08-09 //
//get component list
function get_component_type_list()
{
global $wpdb;
$component_list = array();
$result = $wpdb->get_results("SELECT id, name FROM `inventory_component_type` ORDER BY id");
foreach ($result as $idx => $component) {
$component_list[$component->id] = $component->name;
}
return $component_list;
}
// added by samiel 2022-08-09 //
// component options for selection menu
function get_component_option_list($id = "", $filter = [1, 2, 3, 4, 5])
{
$strList = "";
foreach (get_component_type_list() as $idx => $component_type) {
if (in_array($idx, $filter)) {
$strList .= "<option value='" . $idx . "' data-tokens='" . $component_type . "' ";
if ($idx == $id) {
$strList .= "selected";
}
$strList .= ">";
$strList .= $component_type;
$strList .= "</option>";
}
}
return $strList;
}
// added by samiel 2022-08-09 //
// get process record in inventory_process table
function get_process_list()
{
global $wpdb;
return $result = $wpdb->get_results("
SELECT *, process.id as process_id, process.name as process_name, type.name as type_name, machine.name as machine_name
FROM inventory_process process
LEFT JOIN inventory_process_type type ON type.id = process.type_id
LEFT JOIN inventory_process_machine machine ON machine.id = process.machine_id WHERE process.status = 1
");
}
// added by samiel 2022-08-09 //
// process options for selection menu
function get_process_option_list($id = "")
{
$strList = "";
foreach (get_process_list() as $idx => $process) {
if ($process->machine_id != 0) {
$display_value = "(" . $process->code . ") " . $process->process_name . " -- 機器:" . $process->machine_name;
} else {
$display_value = "(" . $process->code . ") " . $process->process_name;
}
$strList .= "<option value='" . $process->process_id . "' data-tokens='" . $display_value . "' ";
if ($process->process_id == $id) {
$strList .= "selected";
}
$strList .= ">";
$strList .= $display_value;
$strList .= "</option>";
}
return $strList;
}
// added by samiel 2022-08-09 //
// get material record in inventory_material table
function get_material_list($category = "")
{
global $wpdb;
$sql = "SELECT *, 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, 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 unit ON unit.id = mat.unit_id
WHERE mat.status = 1 ";
if ($category != "") {
$sql .= "AND mat.category = '" . $category . "' ";
}
$sql .= "ORDER BY is_default DESC, mat.id ASC ";
return $result = $wpdb->get_results($sql);
}
// added by samiel 2022-08-09 //
// material options for selection menu
function get_material_option_list($category = "", $id = "")
{
$strList = "";
foreach (get_material_list($category) as $idx => $material) {
$default = $material->is_default == 'Y' ? '*' : '';
$display_value = "(" . $material->code . ") " . $material->material_name . $default . " -- 類型:" . $material->type_name . "/品牌:" . $material->brand_name . "/供應商:" . $material->supplier_name;
$strList .= "<option value='" . $material->material_id . "' data-tokens='" . $display_value . "' ";
if ($material->is_default == 'Y') {
$strList .= "style='background: cornflowerblue; color: white;' ";
}
if ($material->material_id == $id) {
$strList .= "selected";
}
$strList .= ">";
$strList .= $display_value;
$strList .= "</option>";
}
return $strList;
}
// added by samiel 2022-08-09 //
// get sfproduct record in inventory_sfproduct table
function get_sfproduct_list()
{
global $wpdb;
return $result = $wpdb->get_results("
SELECT sfproduct.*, sfproduct.id as sfproduct_id, unit.name as unit_name
FROM inventory_sfproduct sfproduct
LEFT JOIN inventory_measure_unit unit ON unit.id = sfproduct.unit_id WHERE sfproduct.status = 1 ORDER BY code ASC
");
}
// added by samiel 2022-08-09 //
// sfproduct options for selection menu
function get_sfproduct_option_list($id = "")
{
$strList = "";
foreach (get_sfproduct_list() as $idx => $sfproduct) {
$display_value = "(" . $sfproduct->code . ") " . $sfproduct->name;
$strList .= "<option value='" . $sfproduct->sfproduct_id . "' data-tokens='" . $display_value . "' ";
if ($sfproduct->sfproduct_id == $id) {
$strList .= "selected";
}
$strList .= ">";
$strList .= $display_value;
$strList .= "</option>";
}
return $strList;
}
// added by samiel 2022-08-09 //
// get product record in inventory_process table
function get_product_list()
{
global $wpdb;
return $result = $wpdb->get_results("
SELECT product.*, product.id as product_id, unit.name as unit_name
FROM inventory_product product
LEFT JOIN inventory_measure_unit unit ON unit.id = product.unit_id WHERE product.status = 1 ORDER BY sku ASC
");
}
// added by samiel 2022-08-09 //
// product options for selection menu
function get_product_option_list($id = "")
{
$strList = "";
foreach (get_product_list() as $idx => $product) {
$display_value = "(" . $product->sku . ") " . $product->name;
$strList .= "<option value='" . $product->product_id . "' data-tokens='" . $display_value . "' ";
if ($product->product_id == $id) {
$strList .= "selected";
}
$strList .= ">";
$strList .= $display_value;
$strList .= "</option>";
}
return $strList;
}
// added by samiel 2022-08-09 //
// get option list by type
function get_reference_option_list($type, $id = "")
{
if ($type == 5) { // process
return get_process_option_list($id);
} elseif ($type == 4) { // packing material
return get_material_option_list("packing", $id);
} elseif ($type == 3) { // ingredient
return get_material_option_list("ingredient", $id);
} elseif ($type == 2) { // semi-finished product
return get_sfproduct_option_list($id);
} elseif ($type == 1) { // product
return get_product_option_list($id);
} else {
return;
}
}
// added by samiel 2022-08-09 //
// get unit name
function get_unit_name($type, $id)
{
if ($type == 5) {
return "min.";
} elseif ($type == 4 || $type == 3) { // material
$material = get_material_item_info($id);
return $material->unit_name;
} elseif ($type == 2) { // semi-finished product
$sfproduct = get_sfproduct_item_info($id);
return $sfproduct->unit_name;
} elseif ($type == 1) { // product
$product = get_product_item_info($id);
return $product->unit_name;
} else {
return;
}
}
// added by samiel 2022-08-09 //
// get material item info
function get_material_item_info($material_id)
{
global $wpdb;
if ($material_id != "") {
$result = $wpdb->get_results("
SELECT mat.category as category, mat.code as code, mat.id as material_id, mat.name as material_name, mat.name as item_name, mat.display_name as display_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 = '" . $material_id . "' LIMIT 1
");
if (count($result) > 0) {
return $result[0];
} else {
return null;
}
} else {
return null;
}
}
// added by samiel 2022-08-09 //
// get sfproduct item info
function get_sfproduct_item_info($sfproduct_id)
{
global $wpdb;
if ($sfproduct_id != "") {
$result = $wpdb->get_results("
SELECT sfproduct.*, sfproduct.id as sfproduct_id, sfproduct.name as item_name, unit.name as unit_name
FROM inventory_sfproduct sfproduct
LEFT JOIN inventory_measure_unit unit ON unit.id = sfproduct.unit_id
WHERE sfproduct.id = '" . $sfproduct_id . "' LIMIT 1
");
if (count($result) > 0) {
return $result[0];
} else {
return null;
}
} else {
return null;
}
}
// added by samiel 2022-08-09 //
// get product item info
function get_product_item_info($product_id)
{
global $wpdb;
if ($product_id != "") {
$result = $wpdb->get_results("
SELECT product.*, product.id as product_id, product.name as item_name, unit.name as unit_name
FROM inventory_product product
LEFT JOIN inventory_measure_unit unit ON unit.id = product.unit_id
WHERE product.id = '" . $product_id . "' LIMIT 1
");
if (count($result) > 0) {
return $result[0];
} else {
return null;
}
} else {
return null;
}
}
// added by samiel 2022-08-10 //
// get cost of an item without packing material
function get_item_total_cost_without_packing_material($type, $id)
{
global $wpdb;
$total_cost = 0;
if ($type == 2) { // 半成品
//sql skip packing material
$result = $wpdb->get_results("
SELECT * FROM inventory_sfproduct_detail WHERE component_type_id != '4' AND sfproduct_id= '" . $id . "'
");
} else if ($type == 1) {
$result = $wpdb->get_results("
SELECT * FROM inventory_product_detail WHERE component_type_id != '4' AND product_id= '" . $id . "'
");
}
foreach ($result as $resultObj) {
if ($resultObj->component_type_id == 1 || $resultObj->component_type_id == 2) { // recursively get cost without packing material
$total_cost += $resultObj->ttl_cost;
} elseif ($resultObj->component_type_id == 3) { // ingredient
$total_cost += $resultObj->ttl_cost;
} elseif ($resultObj->component_type_id == 5) { // process
if (!in_array($resultObj->reference_id, [20, 21])) {
$total_cost += $resultObj->ttl_cost;
}
} else {;
}
}
return $total_cost;
}
// draw product/sdproduct recipe table (html)
function getRecipeTable($mode = '', $component_type_id, $reference_id, $qty, $class = 'outer', $level = 1)
{
global $wpdb;
$productIndentPX = 30 * ($level - 1);
$processIndentPX = 30 * ($level - 1);
$ingrdentIndentPX = 30 * $level;
switch ($component_type_id) {
case "1": // 成品
$obj = get_product_item_info($reference_id); // for getting current obj production qty;
if ($mode == 'ingredient') {
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id IN ('1','2','3') AND product_id= '" . $reference_id . "'");
} elseif ($mode == 'packing_material') {
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id IN ('1','2','4') AND product_id= '" . $reference_id . "'");
} elseif ($mode == 'process') {
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id IN ('1','2','5') AND product_id= '" . $reference_id . "'");
} else {
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE product_id= '" . $reference_id . "'");
}
break;
case "2": // 半成品
$obj = get_sfproduct_item_info($reference_id); // for getting current obj production qty;
if ($mode == 'ingredient') {
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE component_type_id IN ('1','2','3') AND sfproduct_id= '" . $reference_id . "'");
} elseif ($mode == 'packing_material') {
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE component_type_id IN ('1','2','4') AND sfproduct_id= '" . $reference_id . "'");
} elseif ($mode == 'process') {
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE component_type_id IN ('1','2','5') AND sfproduct_id= '" . $reference_id . "'");
} else {
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE sfproduct_id= '" . $reference_id . "'");
}
break;
default:
break;
}
$display_ratio = $qty / $obj->production_qty; // get ratio
$resultHTML = "";
if ($class == 'inner') {
$resultHTML .= "<table class='stripe hover innerTable' border='1' style='border-style: hidden;'>";
} else {
$resultHTML .= "<table id='dataTable' class='stripe hover outerTable' border='1' cellpadding='2' cellspacing='2'>";
}
if ($class == 'outer') {
$resultHTML .= "<thead>";
$resultHTML .= "<tr>";
$resultHTML .= "<th width='40%' style='min-width:150px'>Item</th><th width='10%' style='min-width:45px'>Qty</th><th width='10%' style='min-width:40px'>Unit</th><th width='40%' style='min-width:115px'>Remark</th>";
$resultHTML .= "</tr>";
$resultHTML .= "</thead>";
}
$resultHTML .= "<tbody>";
if (count($result) > 0) {
foreach ($result as $item) {
switch ($item->component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($item->reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($item->reference_id);
break;
case "3": // 食材
$itemObj = get_material_item_info($item->reference_id);
break;
case "4": // 包裝材料
$itemObj = get_material_item_info($item->reference_id);
break;
case "5": // 工序
$itemObj = get_process_item_info($item->reference_id);
break;
default:
break;
}
if (in_array($item->component_type_id, [3, 4, 5])) {
$resultHTML .= "<tr>";
if ($item->component_type_id == 3 || $item->component_type_id == 4) {
$resultHTML .= "<td style='text-indent: " . $ingrdentIndentPX . "px; width:40%; min-width:150px'>";
//$resultHTML .= "<li class='materialIndent'>".$level."-".$itemObj->item_name."</li>";
$resultHTML .= "<li class='materialIndent'>" . $itemObj->item_name . "</li>";
$resultHTML .= "</td>";
} else {
$resultHTML .= "<td style='text-indent: " . $processIndentPX . "px; width:40%; min-width:150px'>";
//$resultHTML .= "<li class='processIndent'>".$level."-".$itemObj->item_name."</li>";
$resultHTML .= "<li class='processIndent'>" . $itemObj->item_name . "</li>";
$resultHTML .= "</td>";
}
$resultHTML .= "<td style='width:10%; min-width:45px' class='right'>";
$resultHTML .= round_up($item->qty * $display_ratio, 2);
$resultHTML .= "</td>";
$resultHTML .= "<td style='width:10%; min-width:40px' class='center'>";
$resultHTML .= get_unit_name($item->component_type_id, $item->reference_id);
$resultHTML .= "</td>";
$resultHTML .= "<td style='width:40%; min-width:115px'>";
$resultHTML .= $item->remark;
$resultHTML .= "</td>";
$resultHTML .= "</tr>";
} else {
$nextLevel = $level + 1;
$resultHTML .= "<tr>";
$resultHTML .= "<td style='text-indent: " . $productIndentPX . "px; width:40%; min-width:150px'>";
//$resultHTML .= "<b style='font-size: 18px;'>".$level."-".$itemObj->item_name."</b>";
$resultHTML .= "<b style='font-size: 18px; font-weight: bold;'>" . $itemObj->item_name . "</b>";
$resultHTML .= "</td>";
$resultHTML .= "<td style='width:10%; min-width:45px' class='right'>";
$resultHTML .= round_up($item->qty * $display_ratio, 2);
$resultHTML .= "</td>";
$resultHTML .= "<td style='width:10%; min-width:40px' class='center'>";
$resultHTML .= get_unit_name($item->component_type_id, $item->reference_id);
$resultHTML .= "</td>";
$resultHTML .= "<td style='width:40%; min-width:115px'>";
$resultHTML .= $item->remark;
$resultHTML .= "</td>";
$resultHTML .= "</tr>";
$resultHTML .= "</tr>";
$resultHTML .= "<td colspan='4' style='background-color:#eee; padding: 0px !important'>";
$resultHTML .= getRecipeTable($mode, $item->component_type_id, $item->reference_id, $item->qty, "inner", $nextLevel);
$resultHTML .= "</td>";
$resultHTML .= "</tr>";
}
}
}
$resultHTML .= "</tbody>";
$resultHTML .= "</table>";
return $resultHTML;
}
// get all ingredient listed in product/sfproduct table (recursive)
function getIngredientLabelData($component_type_id, $reference_id, $qty, $ingredientList = [])
{
global $wpdb;
switch ($component_type_id) {
case "1": // 成品
$obj = get_product_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id IN ('1','2','3') AND product_id= '" . $reference_id . "'");
break;
case "2": // 半成品
$obj = get_sfproduct_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE component_type_id IN ('1','2','3') AND sfproduct_id= '" . $reference_id . "'");
break;
default:
break;
}
$display_ratio = $qty / $obj->production_qty; // get ratio
if (count($result) > 0) {
foreach ($result as $item) {
switch ($item->component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($item->reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($item->reference_id);
break;
case "3": // 食材
$itemObj = get_material_item_info($item->reference_id);
break;
case "4": // 包裝材料
$itemObj = get_material_item_info($item->reference_id);
break;
case "5": // 工序
$itemObj = get_process_item_info($item->reference_id);
break;
default:
break;
}
if ($item->component_type_id == "3") {
$item_content = array('name' => $itemObj->item_name, 'display_name' => $itemObj->display_name, 'qty' => round_up($item->qty * $display_ratio, 2), 'unit' => get_unit_name($item->component_type_id, $item->reference_id));
$ingredientList[] = $item_content;
} else {
$ingredientList[] = getIngredientLabelData($item->component_type_id, $item->reference_id, $item->qty, $ingredientList);
}
}
}
//return $ingredientList;
$ingredientArray = array();
foreach ($ingredientList as $firstLevel) {
if (is_array($firstLevel[0])) {
foreach ($firstLevel as $secondLevel) {
if (is_array($secondLevel[0])) {
foreach ($secondLevel as $thirdLevel) {
if (is_array($thirdLevel[0])) {
foreach ($thirdLevel as $forthLevel) {
if (is_array($forthLevel[0])) {;
} else {
$ingredientArray[] = array('name' => $forthLevel['name'], 'display_name' => $forthLevel['display_name'], 'qty' => $forthLevel['qty'], 'unit' => $forthLevel['unit']);
//$ingredientArray[$forthLevel['name']] += $forthLevel['qty'];
}
}
} else {
$ingredientArray[] = array('name' => $thirdLevel['name'], 'display_name' => $thirdLevel['display_name'], 'qty' => $thirdLevel['qty'], 'unit' => $thirdLevel['unit']);
//$ingredientArray[$thirdLevel['name']] += $thirdLevel['qty'];
}
}
} else {
$ingredientArray[] = array('name' => $secondLevel['name'], 'display_name' => $secondLevel['display_name'], 'qty' => $secondLevel['qty'], 'unit' => $secondLevel['unit']);
//$ingredientArray[$secondLevel['name']] += $secondLevel['qty'];
}
}
} else {
$ingredientArray[] = array('name' => $firstLevel['name'], 'display_name' => $firstLevel['display_name'], 'qty' => $firstLevel['qty'], 'unit' => $firstLevel['unit']);
//$ingredientArray[$firstLevel['name']] += $firstLevel['qty'];
}
}
return $ingredientArray;
}
// depreciated
// get raw ingredient data of a product/sfproduct
function getIngredientTableData($component_type_id, $reference_id, $qty, $ingredientList = [])
{
global $wpdb;
switch ($component_type_id) {
case "1": // 成品
$obj = get_product_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id IN ('1','2','3') AND product_id= '" . $reference_id . "'");
break;
case "2": // 半成品
$obj = get_sfproduct_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE component_type_id IN ('1','2','3') AND sfproduct_id= '" . $reference_id . "'");
break;
default:
break;
}
$display_ratio = $qty / $obj->production_qty; // get ratio
if (count($result) > 0) {
foreach ($result as $item) {
switch ($item->component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($item->reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($item->reference_id);
break;
case "3": // 食材
$itemObj = get_material_item_info($item->reference_id);
break;
default:
break;
}
$item_content = array('component_type_id' => $item->component_type_id, 'reference_id' => $item->reference_id, 'name' => $itemObj->item_name, 'display_name' => $itemObj->display_name, 'qty' => round($item->qty * $display_ratio), 'unit' => get_unit_name($item->component_type_id, $item->reference_id));
$ingredientList[] = $item_content;
}
}
return $ingredientList;
}
// depreciated
// get ingredient data from a product/sfproduct as well as its subitem (product/sfproduct) data
function getIngredientDataArray($component_type_id, $reference_id, $qty)
{
global $wpdb;
$arr_product = array();
$data = getIngredientTableData($component_type_id, $reference_id, $qty);
$extra = array();
switch ($component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($reference_id);
break;
case "3": // 食材
$itemObj = get_material_item_info($reference_id);
break;
default:
break;
}
$arr_product = ['component_type_id' => $component_type_id, 'product_name' => $itemObj->item_name, 'product_qty' => $qty, 'product_unit' => $itemObj->unit_name];
foreach ($data as $item) {
if (in_array($item['component_type_id'], [1, 2])) {
$extra[] = array("component_type_id" => $item['component_type_id'], "reference_id" => $item['reference_id'], "name" => $item['name'], "qty" => $item['qty'], "unit" => $item['unit']);
}
$arr_product['items'][] = ['component_type_id' => $item['component_type_id'], 'product_name' => $item['name'], 'product_qty' => $item['qty'], 'product_unit' => $item['unit']];
}
foreach ($extra as $subItem) {
$arr_product['extra'][] = getIngredientDataArray($subItem['component_type_id'], $subItem['reference_id'], $subItem['qty']);
}
return $arr_product;
}
// get sdproudct name for recipe grouping
function getSfproductGroupNameByproduct($reference_id)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id = '2' AND product_id= '" . $reference_id . "'");
foreach ($result as $lineObj) {
$sfproductID = $lineObj->reference_id;
$sfproductObj = get_sfproduct_item_info($sfproductID);
if ($sfproductObj->grouping == 1) {
return $sfproductObj->name;
}
}
return "";
}
// get raw ingredient data of a product/sfproduct
function getIngredientTableDataNew($component_type_id, $reference_id, $qty, $ingredientList = [])
{
global $wpdb;
switch ($component_type_id) {
case "1": // 成品
$obj = get_product_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id IN ('1','2','3') AND product_id= '" . $reference_id . "'");
break;
case "2": // 半成品
$obj = get_sfproduct_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE component_type_id IN ('1','2','3') AND sfproduct_id= '" . $reference_id . "'");
break;
default:
break;
}
$display_ratio = $qty / $obj->production_qty; // get ratio
if (count($result) > 0) {
foreach ($result as $item) {
switch ($item->component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($item->reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($item->reference_id);
break;
case "3": // 食材
$itemObj = get_material_item_info($item->reference_id);
break;
default:
break;
}
$item_content = array('component_type_id' => $item->component_type_id, 'reference_id' => $item->reference_id, 'name' => $itemObj->item_name, 'display_name' => $itemObj->display_name, 'qty' => $item->qty * $display_ratio, 'unit' => get_unit_name($item->component_type_id, $item->reference_id), 'show_qty' => $item->show_in_preparation_list);
$ingredientList[] = $item_content;
}
}
return $ingredientList;
}
// get ingredient data from a product/sfproduct as well as its subitem (product/sfproduct) data
function getIngredientDataArrayNew($component_type_id, $reference_id, $qty)
{
global $wpdb;
$arr_product = array();
$data = getIngredientTableDataNew($component_type_id, $reference_id, $qty);
$extra = array();
switch ($component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($reference_id);
$visible = 1;
$group = getSfproductGroupNameByproduct($reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($reference_id);
$visible = $itemObj->show_in_preparation_list;
$group = $itemObj->sfcategory_id;
break;
case "3": // 食材
$itemObj = get_material_item_info($reference_id);
$visible = 1;
$group = '';
break;
default:
break;
}
$arr_product = [
'component_type_id' => intval($component_type_id),
'product_name' => $itemObj->item_name,
'product_qty' => $qty,
'product_unit' => $itemObj->unit_name,
'visible' => intval($visible), 'group' => $group
];
foreach ($data as $item) {
if (in_array($item['component_type_id'], [1, 2])) {
$extra[] = array(
"component_type_id" => $item['component_type_id'],
"reference_id" => $item['reference_id'],
"name" => $item['name'],
"qty" => $item['qty'],
"unit" => $item['unit'],
"show_qty" => $item['show_qty']
);
}
$arr_product['items'][] = ['component_type_id' => $item['component_type_id'], 'product_name' => $item['name'], 'product_qty' => $item['qty'], 'product_unit' => $item['unit'], 'show_qty' => $item['show_qty']];
}
foreach ($extra as $subItem) {
$arr_product['extra'][] = getIngredientDataArrayNew($subItem['component_type_id'], $subItem['reference_id'], $subItem['qty']);
}
return $arr_product;
}
//TEST ONLY//
// get ingredient data from a product/sfproduct as well as its subitem (product/sfproduct) data
function getIngredientDataArrayTest($component_type_id, $reference_id, $qty, $parent = ['component_type_id' => 0, 'reference_id' => 0, 'qty' => 0])
{
global $wpdb;
$arr_product = array();
$data = getIngredientTableDataTest($component_type_id, $reference_id, $qty);
/*
echo "<pre>";
print_r($data);
echo "</pre>";
*/
$extra = array();
switch ($component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($reference_id);
$visible = 1;
$group = getSfproductGroupNameByproduct($reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($reference_id);
$visible = $itemObj->show_in_preparation_list;
$group = $itemObj->sfcategory_id;
break;
case "3": // 食材
$itemObj = get_material_item_info($reference_id);
$visible = 1;
$group = '';
break;
default:
break;
}
$arr_product = [
'parent' => $parent,
'component_type_id' => intval($component_type_id),
'product_name' => $itemObj->item_name,
'product_qty' => $qty,
'product_unit' => $itemObj->unit_name,
'visible' => intval($visible),
'group' => $group
];
foreach ($data as $item) {
if (in_array($item['component_type_id'], [1, 2])) {
$extra[] = array(
"component_type_id" => $item['component_type_id'],
"reference_id" => $item['reference_id'],
"name" => $item['name'],
"qty" => $item['qty'],
"unit" => $item['unit'],
"show_qty" => $item['show_qty'],
"parent" => $item['parent']
);
}
$arr_product['items'][] = ["parent" => $item['parent'], 'component_type_id' => $item['component_type_id'], 'product_name' => $item['name'], 'product_qty' => $item['qty'], 'product_unit' => $item['unit'], 'show_qty' => $item['show_qty']];
}
foreach ($extra as $subItem) {
$arr_product['extra'][] = getIngredientDataArrayTest($subItem['component_type_id'], $subItem['reference_id'], $subItem['qty'], $subItem['parent']);
}
return $arr_product;
}
// get raw ingredient data of a product/sfproduct
function getIngredientTableDataTest($component_type_id, $reference_id, $qty, $ingredientList = [])
{
global $wpdb;
switch ($component_type_id) {
case "1": // 成品
$obj = get_product_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE component_type_id IN ('1','2','3') AND product_id= '" . $reference_id . "'");
$skuObj = get_sku_init_info_by_id($obj->sku_id);
$bake_qty_per_round = $skuObj->bake_qty_per_round;
break;
case "2": // 半成品
$obj = get_sfproduct_item_info($reference_id); // for getting current obj production qty;
$result = $wpdb->get_results("SELECT * FROM inventory_sfproduct_detail WHERE component_type_id IN ('1','2','3') AND sfproduct_id= '" . $reference_id . "'");
$bake_qty_per_round = 0;
break;
default:
break;
}
$display_ratio = $qty / $obj->production_qty; // get ratio
if (count($result) > 0) {
foreach ($result as $item) {
switch ($item->component_type_id) {
case "1": // 成品
$itemObj = get_product_item_info($item->reference_id);
break;
case "2": // 半成品
$itemObj = get_sfproduct_item_info($item->reference_id);
break;
case "3": // 食材
$itemObj = get_material_item_info($item->reference_id);
break;
default:
break;
}
$item_content = array('parent' => array('component_type_id' => $component_type_id, 'reference_id' => $reference_id, 'name' => $obj->item_name, 'qty' => $qty, 'bake_qty_per_round' => $bake_qty_per_round), 'component_type_id' => $item->component_type_id, 'reference_id' => $item->reference_id, 'name' => $itemObj->item_name, 'display_name' => $itemObj->display_name, 'qty' => $item->qty * $display_ratio, 'unit' => get_unit_name($item->component_type_id, $item->reference_id), 'show_qty' => $item->show_in_preparation_list);
$ingredientList[] = $item_content;
}
}
return $ingredientList;
}
// draw Production Summary Table for Thermal Printing
function drawSummaryTable($itemData)
{
$resultHTML = "";
$resultHTML .= "<table border='1' style='border-collapse: collapse;' cellspacing='3' cellpadding='3' width='100%'>";
$resultHTML .= "<thead style='background-color:#000; color:#fff'>";
$resultHTML .= "<tr>";
$resultHTML .= "<th>產品</th>";
$resultHTML .= "<th>份數</th>";
$resultHTML .= "<th>件數</th>";
$resultHTML .= "</tr>";
$resultHTML .= "</thead>";
$resultHTML .= "<tbody>";
foreach ($itemData as $idx => $item) {
if ($item['qty'] > 0) {
$resultHTML .= "<tr>";
$resultHTML .= "<td>" . $item['name'] . "</td>";
$resultHTML .= "<td>" . $itemData[$idx]['unit_qty'] . "</td>";
$resultHTML .= "<td>" . $itemData[$idx]['qty'] . "</td>";
$resultHTML .= "</tr>";
}
}
$resultHTML .= "</tbody>";
$resultHTML .= "</table>";
return $resultHTML;
}
// draw recipe / sf product Table for Thermal Printing
function drawRecipeTable($itemData)
{
$resultHTML = "";
$resultHTML .= "<table border='1' style='border-collapse: collapse;' cellspacing='3' cellpadding='3' width='100%'>";
$resultHTML .= "<tbody>";
if (in_array($itemData['component_type_id'], [1, 2])) {
$resultHTML .= "<tr style='background-color:#eee'>";
} else {
$resultHTML .= "<tr>";
}
$resultHTML .= "<th colspan='3' class='tdLabel'><h3>" . $itemData['product_name'] . " (" . ceil($itemData['product_qty']) . " " . $itemData['product_unit'] . ")</h3></th>";
$resultHTML .= "</tr>";
foreach ($itemData['items'] as $itemItemsData) {
if (in_array($itemItemsData['component_type_id'], [1, 2])) {
$resultHTML .= "<tr style='background-color:#eee'>";
} else {
$resultHTML .= "<tr>";
}
$resultHTML .= "<td width='70%'>" . $itemItemsData['product_name'] . "</td>";
$resultHTML .= "<td width='15%' class='right'>" . ($itemItemsData['show_qty'] == 1 ? ceil($itemItemsData['product_qty']) : "") . "</td>";
$resultHTML .= "<td width='15%'>" . ($itemItemsData['show_qty'] == 1 ? $itemItemsData['product_unit'] : "") . "</td>";
$resultHTML .= "</tr>";
}
$resultHTML .= "</tbody>";
$resultHTML .= "</table>";
return $resultHTML;
}
// get ingredient label of a product/sfproduct based on weight
function getIngredientLabel($component_type_id, $reference_id, $qty)
{
$dataResult = getIngredientLabelData($component_type_id, $reference_id, $qty);
$arrResult = array();
foreach ($dataResult as $itemArr) {
$arrResult[$itemArr['display_name']] += $itemArr['qty'];
}
arsort($arrResult);
$resultStr = implode(", ", array_keys($arrResult));
return ucfirst($resultStr) . ".";
}
// get price/cost ratio of a product (sku)
function getProductPriceCostInfo($sku_id)
{
global $wpdb;
$skuInitResult = $wpdb->get_results("SELECT * FROM stock_init WHERE id = '" . $sku_id . "' LIMIT 1");
$skuInit = $skuInitResult[0];
if ($skuInit->sku == "BD-WNL-460") {
$sku = "BD-WNT-460";
} else {
$sku = $skuInit->sku;
}
$woo_product_id = wc_get_product_id_by_sku($sku);
$woo_product = wc_get_product($woo_product_id);
//$woo_price = get_post_meta($woo_product_id, "_price", true);
$productResult = $wpdb->get_results("SELECT * FROM inventory_product WHERE sku_id = '" . $sku_id . "' LIMIT 1");
$productObj = $productResult[0];
$price = $woo_product->get_price() / $skuInit->unit_qty;
//$price = $woo_price/$skuInit->unit_qty;
$cost = $productObj->unit_cost_with_wastage;
$ratio = round(($cost / $price) * 100, 2);
/*
if($ratio==0){
$ratio = "N/A";
}
*/
$unit = get_unit_name(1, $productObj->id);
return ["price" => $price, "cost" => $cost, "ratio" => $ratio, "unit" => $unit];
}
// get start day of a given year and week#
function weekstartday($year, $weekno)
{
$date = new DateTime();
$date->setISODate($year, $weekno);
return $date->format('Y-m-d');
}
// get the max available delivery date from current date
function get_custom_calendar_date_info($date)
{
$year = date("Y");
$hour = date("H");
$weekday = date("N", strtotime($date));
$weekdayname = date("l", strtotime($date));
$weekno = date("W", strtotime($date));
if ($weekday == 6) {
if ($hour < 20) {
//$max_date = date('Y-m-d', strtotime("+7 day", strtotime($date)));
$max_date = date('Y-m-d', strtotime("+8 day", strtotime($date)));
} else {
//$max_date = date('Y-m-d', strtotime("+14 day", strtotime($date)));
$max_date = date('Y-m-d', strtotime("+15 day", strtotime($date)));
}
} elseif ($weekday > 6) {
//$max_date = date('Y-m-d', strtotime("+12 day", strtotime(weekstartday($year, $weekno+1))));
$max_date = date('Y-m-d', strtotime("+13 day", strtotime(weekstartday($year, $weekno + 1))));
} else {
//$max_date = date('Y-m-d', strtotime("+12 day", strtotime(weekstartday($year, $weekno))));
$max_date = date('Y-m-d', strtotime("+13 day", strtotime(weekstartday($year, $weekno))));
}
$period = ((strtotime($max_date) - strtotime($date)) / 86400) + 1;
return ["date" => $date, "weekno" => $weekno, "weekday" => $weekday, "weekdayname" => $weekdayname, "maxdate" => $max_date, "period" => $period];
}
// get chinese weekday name
function get_chinese_weekday($datetime)
{
$weekday = date('w', strtotime($datetime));
$weeklist = array('日', '一', '二', '三', '四', '五', '六');
return '星期' . $weeklist[$weekday];
}
// get constant value
function get_constant_value($field_name)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM inventory_process_constant WHERE name = '" . $field_name . "' and status = 1 LIMIT 1 ");
if (count($result) == 1) {
return $result[0]->value;
} else {
return false;
}
}
// get custom value
function get_custom_value($key)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM custom_value WHERE field_name = '" . $key . "' and status = 1 LIMIT 1 ");
if (count($result) == 1) {
return $result[0]->field_value;
} else {
return false;
}
}
// function performed when order status changes from pending payment to processing
add_filter('woocommerce_order_status_pending_to_processing', 'pending_to_processing_action', 10, 2);
function pending_to_processing_action($order_id)
{
date_default_timezone_set("Asia/Hong_Kong");
if (!$order_id)
return;
global $wpdb;
// Getting an instance of the order object
$order = wc_get_order($order_id);
$delivery_date = $order->get_meta('delivery_date', true);
// send notification
$new_order_notification = $order->get_meta('new_order_notification', true);
if ($new_order_notification != 1) {
$display_delivery_date = date("d/m/Y", strtotime($delivery_date));
if ($delivery_date != date("Y-m-d")) {
$title = "NEW ORDER";
} else {
$title = "\u{2B50}TODAY";
}
$message = "#" . $order->get_order_number() . " " . $display_delivery_date;
$topic = "newOrder";
initPushNotification($title, $message, $topic, $order_id);
update_post_meta($order_id, 'new_order_notification', '1');
}
// adjust stock
adjust_stock_action($order_id);
}
// added on 2022-03-04 by Samiel
// send push notification via Firebase Cloud Messaging Service
function sendPushNotification($fields = array())
{
$API_ACCESS_KEY = 'AAAA6BQ0Sks:APA91bFUBOd0DWOBs8W48e25IvPZsiktqGZUt9C4GobsEisEnEaKVcpg9UxP5vHIsk7TlTWj2C4LJJLLVUWB4GX7NatumRtAmdd6P9ko1j2uJkIfkprou5hYCtKe-QwuXQjxVYNeUt7v';
$headers = array(
'Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
//echo $result;
}
function sendPushNotificatioApp($fields = array())
{
$API_ACCESS_KEY = 'AAAAcs8rees:APA91bGyoIXoKr7WQiOz7h9EtogW5XkAaZtpzxRpMW9P4FiHElLxH_Ert64C1rtB2BkpLHCfCXR1IKQkXmALTK_E4RRc-Q1uyKaspMIYJtR0r6FSpnFUlYYGHWoIimJ3lORlJOylPHfn';
$headers = array
(
'Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
//echo $result;
}
// added on 2022-03-04 by Samiel
// init push notification message content
function initPushNotification($title, $message, $topic, $order_id)
{
$fields = array(
'to' => '/topics/' . $topic,
'priority' => 'high',
'notification' => array(
'body' => $message,
'title' => $title,
'sound' => 'default',
'icon' => '',
'image' => ''
),
'data' => array(
'message' => $message,
'title' => $title,
'id' => $order_id,
'sound' => 'default',
'icon' => '',
'image' => ''
)
);
sendPushNotification($fields);
}
// init notification (topic)
function initPushNotificationAppTopic($title, $message, $topic, $type="", $id){
$fields = array
(
'to' => '/topics/'.$topic,
'priority' => 'high',
'notification' => array(
'body' => $message,
'title' => $title,
'sound' => 'default',
'icon' => '',
'image'=> ''
),
'data' => array(
'message' => $message,
'title' => $title,
'type' => $type,
'id' => $id,
'sound' => 'default',
'icon' => '',
'image'=> ''
),
'apns'=> array(
'headers'=> array('apns-priority'=>5),
'payload'=> array(
'aps'=> array(
'mutable-content'=> 1,
'content-available'=> 1
)
)
)
);
sendPushNotificatioApp($fields);
}
// init notification (device)
function initPushNotificationAppDevice($title, $message, $device_token, $type, $id, $notification_id=0){
$fields = array
(
'to' => $device_token,
'priority' => 'high',
'notification' => array(
'body' => $message,
'title' => $title,
'sound' => 'default',
'icon' => '',
'image'=> ''
),
'data' => array(
'notification_id' => $notification_id,
'message' => $message,
'title' => $title,
'type' => $type,
'id' => $id,
'sound' => 'default',
'icon' => '',
'image'=> ''
),
'apns'=> array(
'headers'=> array('apns-priority'=>5),
'payload'=> array(
'aps'=> array(
'mutable-content'=> 1,
'content-available'=> 1
)
)
)
);
sendPushNotificatioApp($fields);
}
// determine whether it is a wholesaler order (group buy) true = yes; false = no;
// added on 2022-03-07 by Samiel
function is_wholesaler_order($order_id)
{
$order = wc_get_order($order_id);
$wholesaler = false;
// Coupons used in the order LOOP (as they can be multiple)
foreach ($order->get_used_coupons() as $coupon_code) {
if (strpos($coupon_code, "wholesale") !== false) {
$wholesaler = true;
}
}
return $wholesaler;
}
// get report sorting sequence by sku
// added on 2022-03-14 by Samiel
function get_report_sequence_by_sku($sku)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `sku_report_sorting` WHERE sku = '" . $sku . "' LIMIT 1");
if (count($result) == 1) {
$sequence = $result[0]->sequence;
} else {
$sequence = 99;
}
return $sequence;
}
//check current language
function get_language()
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
return "chi";
} else {
return "eng";
}
}
//check sku sale schedule
function check_stock_init($sku, $stock_date)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `stock_init` WHERE sku = '" . $sku . "' LIMIT 1");
$status = 0; // 0 = discontinued; 1 = selling; 2 = coming soon
if (count($result) == 1) {
if ($result[0]->start_date == "0000-00-00" || $result[0]->start_date > $stock_date) {
$status = 2;
} elseif ($result[0]->start_date <= $stock_date) {
if ($result[0]->end_date == "0000-00-00" || $result[0]->end_date >= $stock_date) {
$status = 1;
}
}
}
return $status;
}
//check sku init info.
function get_sku_init_info($sku)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `stock_init` WHERE sku = '" . $sku . "' LIMIT 1");
if (count($result) == 1) {
return $result[0];
} else {
return false;
}
}
//check sku init info.
function get_sku_init_info_by_id($sku_id)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `stock_init` WHERE id = '" . $sku_id . "' LIMIT 1");
if (count($result) == 1) {
return $result[0];
} else {
return false;
}
}
//get earliest available date
function get_earliest_available_date($sku)
{
global $wpdb;
$unit_qty = get_master_sku_unit_qty($sku);
$stock_sku = get_master_sku($sku);
$date = date("Y-m-d");
if (date('H', time()) >= 16) {
$date = date('Y-m-d', strtotime("+1 day"));
}
$init_info = get_sku_init_info($sku);
$start_date = $init_info->start_date;
if ($date > $start_date) {
$start_date = $date;
}
$result = $wpdb->get_results("SELECT stock_date FROM `sku_stock` WHERE stock_date >= '" . $start_date . "' AND `" . $stock_sku . "` >= " . $unit_qty . " LIMIT 1");
if (count($result) == 1) {
return date('d/m', strtotime($result[0]->stock_date));
} else {
return false;
}
}
//get user_id from hash (for group buyer reservation form)
function get_user_id_from_hash($hash)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM `wp_usermeta` WHERE meta_key = 'wikipedia' AND meta_value = '" . $hash . "' LIMIT 1");
if (count($result) == 1) {
return $result[0]->user_id;
} else {
return false;
}
}
// get client IP
function getClientIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
//make first and last character of a word to star
function secret_word($text, $type = "text")
{
if ($type == "email") {
$word = explode("@", $text);
return substr($word[0], 0, strlen($word[0]) - 3) . "***@" . $word[1];
} else {
return substr($text, 0, strlen($text) - 3) . "***";
}
}
//get roundup production qty
function roundUpToAny($n, $x = 5)
{
return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
}
//get holiday list from table
function get_holiday_list()
{
global $wpdb;
$holiday_list = array();
$result = $wpdb->get_results("SELECT holiday FROM `holiday_list` ORDER BY holiday");
foreach ($result as $idx => $holiday) {
array_push($holiday_list, $holiday->holiday);
}
return $holiday_list;
}
//get customer payment method list from table
function get_customer_payment_method_list()
{
global $wpdb;
$payment_method_list = array();
$result = $wpdb->get_results("SELECT name FROM `custom_payment_method` ORDER BY sequence");
foreach ($result as $idx => $payment_method) {
array_push($payment_method_list, $payment_method->name);
}
return $payment_method_list;
}
//get customer payment tems list from table
function get_customer_payment_terms_list()
{
global $wpdb;
$payment_terms_list = array();
$result = $wpdb->get_results("SELECT name FROM `custom_payment_terms` ORDER BY sequence");
foreach ($result as $idx => $payment_terms) {
array_push($payment_terms_list, $payment_terms->name);
}
return $payment_terms_list;
}
//get shipping method name from code
function get_shipping_method_from_code($code)
{
global $wpdb;
$result = $wpdb->get_results("SELECT name FROM `custom_shipping_method` WHERE code = '" . trim($code) . "' LIMIT 1");
if (count($result) == 1) {
return $result[0]->name;
} else {
return "";
}
}
//get region name from code
function get_region_from_code($code)
{
global $wpdb;
$result = $wpdb->get_results("SELECT name FROM `custom_region` WHERE code = '" . trim($code) . "' LIMIT 1");
if (count($result) == 1) {
return $result[0]->name;
} else {
return "";
}
}
//write log to stock_log table
function write_log($stock_date, $action, $type, $order_id, $sku, $description, $qty_from, $qty_to, $user_id, $ip, $sql_statement)
{
global $wpdb;
//$order = wc_get_order($order_id);
$wpdb->insert('stock_log', array(
'stock_date' => $stock_date,
'action' => $action,
'type' => $type,
'order_id' => $order_id,
'sku' => $sku,
'description' => $description,
'qty_from' => $qty_from,
'qty_to' => $qty_to,
'user_id' => $user_id,
'ip' => $ip,
'sql_statement' => sanitize_text_field($sql_statement),
));
}
// add wording to order confirmation email base on shipping method
function translate_shipping_method($shipping_methods)
{
if ($shipping_methods == 'Pick-up') {
return '<p>To guarantee you have the freshest bread possible, please pick-up your order 15:00 -17:30 on your selected date.<br />
Pick-up location: Room Q, 6/F, Block 1, Kin Ho Industrial Building, 14-24 Au Pui Wan Street, Fo Tan.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Delivery') {
return '<p>Your order will be delivered to you on your selected date, 2pm to 7pm.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Delivery 2') {
return '<p>Your order will be delivered to you on your selected date, 4pm to 9pm.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Delivery 3') {
return '<p>Your order will be delivered to you on your selected date, 4pm to 9pm.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Kau To Shan, Fo Tan Mid-levels') {
return '<p>Your order will be delivered to you on your selected date, 2pm to 7pm.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Collect 1') {
return '<p>Your order will be delivered to Admiralty MTR customer service centre by Exit A (17:30).
on your selected date.<br/>
Contact:+852 5612 5381<br/>
</p> ';
} elseif ($shipping_methods == 'Collect 2') {
return '<p>Your order will be delivered to Kowloon Tong MTR at ticket gate by Exit C (18:00).
on your selected date.<br/>
Contact:+852 5612 5381<br/>
</p> ';
} elseif ($shipping_methods == 'Collect 3') {
return '<p>Your order will be delivered to Fo Tan MTR station, customer service centre near Exit D (17:30).
on your selected date.<br/>
Contact:+852 5612 5381<br/>
</p>';
} elseif ($shipping_methods == 'Collect 4') {
return '<p>Your order will be delivered to Royal Ascot Shipping Centre, near customer service centre (17:00).
on your selected date.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Collect 5') {
return '<p>Your order will be delivered to Fo Tan MTR station, customer service centre near Exit D (18:00-18:15).
on your selected date.<br/>
Contact:+852 5612 5381<br/>
</p>';
} elseif ($shipping_methods == 'Collect 6') {
return '<p>Your order will be delivered to Royal Ascot Shipping Centre, near customer service centre (17:30-17:45).
on your selected date.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Collect 11') {
return "<p>Your order will be delivered to Drop-off area outside Admiralty Centre, near McDonald's (Monday, Wednesday, Friday) 17:00-17:30.
on your selected date.<br />
Contact :+852 5612 5381
</p>";
} elseif ($shipping_methods == 'Collect 12') {
return '<p>Your order will be delivered to Kowloon Tong Suffolk roadside, near MTR Station Exit B (Tuesday, Thursday, Saturday) 17:00-17:30.
on your selected date.<br />
Contact :+852 5612 5381
</p>';
} elseif ($shipping_methods == 'Collect 13') {
return '<p>Your order will be delivered to Admiralty MTR customer service centre by Exit A (Monday, Wednesday, Friday) 17:30-17:45.
on your selected date.<br/>
Contact:+852 5612 5381<br/>
</p> ';
} elseif ($shipping_methods == 'Collect 14') {
return '<p>Your order will be delivered to Kowloon Tong MTR at ticket gate by Exit C (Tuesday, Thursday, Saturday) 18:00-18:15.
on your selected date.<br/>
Contact:+852 5612 5381<br/>
</p> ';
} elseif ($shipping_methods == 'Collect 15') {
return '<p>Pop-Up Store 1, K11 Natural, Shop 201, K11 Art Mall, 18 Hanoi Road, Tsim Sha Tsui. 17:00-20:00 on your selected date.<br/>
Contact:+852 5612 5381<br/>
</p> ';
} elseif ($shipping_methods == '送貨') {
return '<p>你的訂單將於你所選的日子(下午2時至7時)送到給你。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '送貨 2') {
return '<p>你的訂單將於你所選的日子(下午4時至9時)送到給你。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '送貨 3') {
return '<p>你的訂單將於你所選的日子(下午4時至9時)送到給你。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '九肚山、火炭半山區住宅') {
return '<p>你的訂單將於你所選的日子(下午2時至7時)送到給你。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 1') {
return '<p>你的訂單將於你所選的日子在金鐘MTR客務中心近A出口 (17:30)交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 2') {
return '<p>你的訂單將於你所選的日子在九龍塘港鐵站C出口閘機旁 (18:00)交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 3') {
return '<p>你的訂單將於你所選的日子在火炭港鐵站客戶服務中心,D出口旁 (17:30)交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 4') {
return '<p>你的訂單將於你所選的日子在駿景園商場客戶服務中心旁 (17:00)交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 5') {
return '<p>你的訂單將於你所選的日子在火炭港鐵站客戶服務中心,D出口旁 (18:00-18:15)交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 6') {
return '<p>你的訂單將於你所選的日子在駿景園商場客戶服務中心旁 (17:30-17:45)交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 11') {
return '<p>你的訂單將於你所選的日子在金鐘海富中心外上落客區,近麥當勞 (星期一、三、五) 17:00-17:30交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 12') {
return '<p>你的訂單將於你所選的日子在九龍塘沙福道路邊停車處、近港鐵站B出口 (星期二、四、六) 17:00-17:30交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 13') {
return '<p>你的訂單將於你所選的日子在金鐘MTR客務中心近A出口 (星期一、三、五) 17:30-17:45交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 14') {
return '<p>你的訂單將於你所選的日子在九龍塘港鐵站C出口閘機旁 (星期二、四、六) 18:00-18:15交收。<br />
聯絡:+852 5612 5381
</p> ';
} elseif ($shipping_methods == '交收 15') {
return '<p>尖沙咀河內道18號K11 Art Mall 二樓 201號店 K11 Natural Pop-Up Store 1號(24/10/2022 - 30/10/2022) 17:00-20:00交收。<br />
聯絡:+852 5612 5381
</p> ';
} else {
return '';
}
}
//get client ip for logging
function get_client_ip()
{
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if (getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if (getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if (getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if (getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if (getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
//get full product name with variation name
function get_name_from_variation_id($product_name, $variation_id)
{
global $wpdb;
$variation = new WC_Product_Variation($variation_id); // get variation object from variation id
$variationName = implode(" / ", $variation->get_variation_attributes()); // get variation name from ariation object
if ($variation_id != 0) {
$description = $product_name . " - " . $variationName;
} else {
$description = $product_name;
}
return $description;
}
//get the unit qty of a variation
function get_variation_unit_qty($variation_id)
{
global $wpdb;
$result = $wpdb->get_results("SELECT unit_qty FROM `variation_unit_qty` WHERE variation_id = '" . $variation_id . "' LIMIT 1");
if (isset($result[0]->unit_qty))
return $result[0]->unit_qty;
else
return "1";
}
//check if a sku contains a master sku (for stock use)
function has_master_sku($sku)
{
global $wpdb;
$result = $wpdb->get_results("SELECT master_sku FROM `sku_mapping` WHERE slave_sku = '" . $sku . "' LIMIT 1");
if (isset($result[0]->master_sku))
return true;
else
return false;
}
//get a master sku if present
function get_master_sku($sku)
{
global $wpdb;
$result = $wpdb->get_results("SELECT master_sku FROM `sku_mapping` WHERE slave_sku = '" . $sku . "' LIMIT 1");
if (isset($result[0]->master_sku))
return $result[0]->master_sku;
else
return $sku;
}
//get master sku unit qty (for stock use)
function get_master_sku_unit_qty($sku)
{
global $wpdb;
$result = $wpdb->get_results("SELECT unit_qty FROM `sku_mapping` WHERE slave_sku = '" . $sku . "' LIMIT 1");
if (isset($result[0]->unit_qty))
return $result[0]->unit_qty;
else
return "1";
}
//check if a sku contains slave sku (for stock use)
function has_slave_sku($sku)
{
global $wpdb;
$result = $wpdb->get_results("SELECT slave_sku FROM `sku_mapping` WHERE master_sku = '" . $sku . "' ");
if (count($result) > 0)
return true;
else
return false;
}
//get a master sku if present
function get_salve_sku($sku)
{
global $wpdb;
$result = $wpdb->get_results("SELECT slave_sku FROM `sku_mapping` WHERE master_sku = '" . $sku . "' ");
if (count($result) > 0)
return $result;
else
return false;
}
//get total sku qty received from order delivery date
function get_production_qty($sku, $stock_date)
{
global $wpdb;
//initialize wanted order status
$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed'));
//get all orders
$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '" . $stock_date . "'");
$count = 0;
//chech matched delivery date and sku#
foreach ($result as $order_obj) {
$order = wc_get_order($order_obj->ID);
$delivery_date = $order->get_meta('delivery_date', true);
if ($delivery_date == $stock_date) {
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$stock_sku = get_master_sku($product->get_sku());
$unit_qty = 1;
if (has_master_sku($product->get_sku())) {
$unit_qty = get_master_sku_unit_qty($product->get_sku()); //get master sku unit qty
} else {
//check variation for old product
$variation_id = $item->get_variation_id();
if ($variation_id != 0) {
$unit_qty = get_variation_unit_qty($variation_id); //get variation unit qty
} else {
$unit_qty = 1;
}
}
if ($stock_sku == $sku) {
$count += $item->get_quantity() * $unit_qty;
}
}
}
}
return $count;
}
//get total sku qty received from order delivery date
function get_calculated_production_qty($sku, $qty)
{
$skuObj = get_sku_init_info($sku);
$min = $skuObj->min_production_qty;
$multiple = $skuObj->production_multiple;
$extra = $skuObj->extra_production_qty;
if ($qty == 0) {
return intval("0");
} else {
return (roundUpToAny($qty, $multiple) + $extra) > $min ? (roundUpToAny($qty, $multiple) + $extra) : $min;
}
}
//woocommerce移除不需要的欄位
add_filter('woocommerce_billing_fields', 'remove_billing_address_1');
function remove_billing_address_1($fields)
{
unset($fields['billing_city']);
unset($fields['billing_postcode']);
//unset($fields['billing_address_1']);
unset($fields['billing_address_2']);
return $fields;
}
//woocommerce移除不需要的欄位
add_filter('woocommerce_shipping_fields', 'remove_shipping_address_1');
function remove_shipping_address_1($fields)
{
unset($fields['shipping_city']);
unset($fields['shipping_postcode']);
unset($fields['shipping_company']);
return $fields;
}
/**
* Add or modify States
*/
add_filter('woocommerce_states', 'custom_woocommerce_states');
function custom_woocommerce_states($states)
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
$states['HK'] = array(
'HK1' => '中區 ',
'HK23' => '清水灣',
'HK2' => '東區 ',
'HK3' => '離島區 ',
'HK4' => '九龍城區 ',
'HK5' => '葵興',
'HK6' => '觀塘區 ',
'HK7' => '北區 ',
'HK8' => '西貢',
'HK9' => '沙田區 ',
'HK10' => '深水埗區',
'HK11' => '南區 ',
'HK12' => '大埔 ',
'HK27' => '大埔 (大尾督)',
'HK26' => '大埔 (汀角)',
'HK28' => '大埔 (白石角)',
'HK24' => '將軍澳',
'HK19' => '青衣',
'HK13' => '荃灣 ',
'HK25' => '荃灣 (深井)',
'HK14' => '屯門區 ',
'HK15' => '灣仔區 ',
'HK20' => '西區',
'HK16' => '黃大仙區',
'HK22' => '油尖旺區',
'HK18' => '元朗區 ',
'HK31' => '自取/交收',
'HK32' => '送貨'
);
} else {
$states['HK'] = array(
'HK1' => 'Central ',
'HK23' => 'Clear Water Bay',
'HK2' => 'Eastern ',
'HK3' => 'Islands ',
'HK4' => 'Kowloon City ',
'HK5' => 'Kwai Hing ',
'HK6' => 'Kwun Tong ',
'HK7' => 'North ',
'HK8' => 'Sai Kung ',
'HK9' => 'Sha Tin ',
'HK10' => 'Sham Shui Po ',
'HK11' => 'Southern ',
'HK12' => 'Tai Po ',
'HK26' => 'Tai Po (Ting Kok)',
'HK27' => 'Tai Po (Tai Mei Tuk)',
'HK28' => 'Tai Po (Pak Shek Kok)',
'HK24' => 'Tseung Kwan O ',
'HK19' => 'Tsing Yi',
'HK13' => 'Tsuen Wan ',
'HK25' => 'Tsuen Wan (Sham Tseng)',
'HK14' => 'Tuen Mun ',
'HK15' => 'Wan Chai ',
'HK20' => 'Western',
'HK16' => 'Wong Tai Sin',
'HK22' => 'Yau Tsim Mong',
'HK18' => 'Yuen Long ',
'HK31' => 'PICKUP / COLLECT',
'HK32' => 'DELIVERY'
);
}
return $states;
}
//logout to home page
add_action('wp_logout', 'auto_redirect_after_logout');
function auto_redirect_after_logout()
{
wp_redirect(home_url());
exit();
}
//woocommerce hide shipping on cart page
function disable_shipping_calc_on_cart($show_shipping)
{
if (is_cart()) {
return false;
}
return $show_shipping;
}
add_filter('woocommerce_cart_ready_to_calc_shipping', 'disable_shipping_calc_on_cart', 99);
// Billing and Shipping fields on my account edit-addresses and checkout
add_filter('woocommerce_default_address_fields', 'custom_override_default_address_fields');
function custom_override_default_address_fields($fields)
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
$fields['address_1']['label'] = '地址';
$fields['address_2']['label'] = '地址 2';
} else {
$fields['address_1']['label'] = 'Address';
$fields['address_2']['label'] = 'Address 2';
}
return $fields;
}
//Check out page add files (shipping phone and email)
add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');
function custom_override_checkout_fields($fields)
{
$fields['shipping']['shipping_phone'] = array(
'label' => __('Phone', 'woocommerce'),
'placeholder' => _x('Phone', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
$fields['shipping']['shipping_email'] = array(
'label' => __('Email address', 'woocommerce'),
'placeholder' => _x('Email address', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
//Display field value on the order edit page
add_action('woocommerce_admin_order_data_after_shipping_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1);
function my_custom_checkout_field_display_admin_order_meta($order)
{
echo "<p class='form-field _shipping_email_field '><label for='_shipping_email'>Shipping Email</label><input type='text' class='short' style='' name='_shipping_email' id='_shipping_email' value='".get_post_meta( $order->get_id(), '_shipping_email', true )."' placeholder=''> </p>";
//echo '<p><strong>' . __('Shipping Phone') . ':</strong> ' . get_post_meta($order->get_id(), '_shipping_phone', true) . '</p>';
//echo '<p><strong>' . __('Shipping Email') . ':</strong> ' . get_post_meta($order->get_id(), '_shipping_email', true) . '</p>';
//echo '<p><strong>' . __('Delivery Date') . ':</strong> ' . get_post_meta($order->get_id(), 'delivery_date', true) . '</p>';
//echo '<p><strong>' . __('Payment ') . ':</strong> ' . get_post_meta($order->get_id(), 'Payment', true) . '</p>';
echo "<p class='form-field _delivery_date '><label for='_delivery_date'><strong>Delivery Date</strong></label>".get_post_meta($order->get_id(), 'delivery_date', true)."</p>";
echo "<p class='form-field _payment '><label for='_payment'><strong>Payment</strong></label>".get_post_meta($order->get_id(), 'Payment', true)."</p>";
}
//order email show shipping address
add_filter('woocommerce_order_needs_shipping_address', '__return_true');
//order email show order time
add_action('woocommerce_email_order_details', 'custom_processing_order_notification', 1, 4);
function custom_processing_order_notification($order, $sent_to_admin, $plain_text, $email)
{
// Only for processing email notifications to customer
if (!'customer_processing_order' == $email->id) return;
$date_modified = $order->get_date_created();
$date_paid = $order->get_date_paid();
$date = empty($date_paid) ? $date_modified : $date_paid;
echo sprintf('<p>Order #%s (placed on <time>%s</time>)</p>', $order->get_order_number(), $date->date("F j, Y, g:i:s A T"));
}
// additional shipping descripion for pickup in checkout page
add_filter('woocommerce_cart_shipping_method_full_label', 'custom_shipping_method_label', 10, 2);
function custom_shipping_method_label($label, $method)
{
//$rate_id = $method->id; // The Method rate ID (Method Id + ':' + Instance ID)
$add_eng = 'Room Q, 6/F, Block 1, Kin Ho Industrial Building, 14-24 Au Pui Wan Street, Fo Tan.';
$add_chi = '火炭坳背灣街14-24號金豪工業大廈一期6樓Q室。';
$pickup_time_eng = "<b style='color: red;'>Sat : 15:00 - 17:30</b></br> Mon - Fri : 15:00 - 17:30";
$pickup_time_chi = "<b style='color: red;'>星期六:15:00 - 17:30</b></br> 星期一至五:15:00 - 17:30";
//$pickupdate_chi = "";
//$pickupdate_eng = "";
//$msg_chi = "";
//$msg_eng = "";
//$holiday = true; // set this to true if today is holiday, false if today is working day.
// Continue only if it is "flat rate"
//$arr_holiday = get_holiday_list();
//if (in_array(date('Y-m-d'), $arr_holiday)) // check if today is in holiday list
// $holiday = true;
if ($method->id !== 'local_pickup:424') return $label; {
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
//check order is working day and before 4pm
/*
if (!$holiday && in_array(date('N'), array(1, 2, 3, 4, 5, 6)) && time() < strtotime('8 am')) {
$pickupdate_chi = '為保證您能享用新鮮的麵包,請您在即日' . date("d/m/Y") . ',15:00 - 17:30 自取<br />'; // <= Additional text
$pickupdate_eng = 'To guarantee you have the freshest bread possible, please pick-up your order today ' . date("d/m/Y") . ', 16:00 - 18:30.<br />';
} elseif (!$holiday && in_array(date('N'), array(6)) && time() < strtotime('8 am')) {
$pickupdate_chi = '為保證您能享用新鮮的麵包,請您在即日' . date("d/m/Y") . ',15:00 - 17:30 自取<br />'; // <= Additional text
$pickupdate_eng = 'To guarantee you have the freshest bread possible, please pick-up your order today ' . date("d/m/Y") . ', 16:00 - 18:00.<br />';
} else { // for order after 4pm or on sunday
if ($holiday) { //check if it is holiday
$msg_chi = '由於是日店休,';
$msg_eng = "It's holiday today, ";
}
$pickupdate_chi = $msg_chi . '請您在下一個工作天,15:00 - 17:30 自取<br />'; // <= Additional text
$pickupdate_eng = $msg_eng . 'Please pick-up your order on the next business day, 15:00 - 17:30.<br />';
}
*/
//check for website language
if (strpos($url, 'zh-hant') !== false) {
$address = $add_chi;
//$msg = $msg_chi;
//$pickupdate = $pickupdate_chi;
$time = $pickup_time_chi;
} else {
$address = $add_eng;
//$msg = $msg_eng;
//$pickupdate = $pickupdate_eng;
$time = $pickup_time_eng;
}
}
return $label . '<br /><small>' . $address . '<br />' . $time . '</small>';
}
//add some more fields to the order info section(Print Invoice & Delivery Notes for WooCommerce)
function custom_order_display_fields($fields, $order)
{
$new_fields = array();
if (get_post_meta($order->get_id(), 'delivery_date', true)) {
$new_fields['delivery_date'] = array(
'label' => 'Delivery / pickup date',
'value' => get_post_meta($order->get_id(), 'delivery_date', true)
);
}
return array_merge($fields, $new_fields);
}
add_filter('wcdn_order_info_fields', 'custom_order_display_fields', 10, 2);
//remove some more fields to the order info section(Print Invoice & Delivery Notes for WooCommerce)
function example_removed_payment_method($fields)
{
unset($fields['billing_email']);
unset($fields['billing_phone']);
return $fields;
}
add_filter('wcdn_order_info_fields', 'example_removed_payment_method');
// Add a custom field (in an order) to the emails
add_filter('woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3);
function custom_woocommerce_email_order_meta_fields($fields, $sent_to_admin, $order)
{
$fields['_shipping_phone'] = array(
'label' => __('Recipient Phone'),
'value' => get_post_meta($order->get_id(), '_shipping_phone', true),
);
$fields['_shipping_email'] = array(
'label' => __('Recipient Email'),
'value' => get_post_meta($order->get_id(), '_shipping_email', true),
);
$fields['delivery_date'] = array(
'label' => __('Delivery/Pick-up Date'),
'value' => get_post_meta($order->get_id(), 'delivery_date', true),
);
$shipping_methods = $order->get_shipping_method();
if ($shipping_methods == 'Pick-up') {
$display_text = "Fo Tan bakery house";
} elseif ($shipping_methods == 'Collect 1') {
$display_text = "Admiralty MTR customer service centre by Exit A (17:30)";
} elseif ($shipping_methods == 'Collect 2') {
$display_text = "Kowloon Tong MTR at ticket gate by Exit C (18:00)";
} elseif ($shipping_methods == 'Collect 3') {
$display_text = "Fo Tan MTR station, customer service centre near Exit D (17:30)";
} elseif ($shipping_methods == 'Collect 4') {
$display_text = "Royal Ascot shopping centre, near customer service centre (17:00)";
} elseif ($shipping_methods == 'Collect 5') {
$display_text = "Fo Tan MTR station, customer service centre near Exit D (18:00-18:15)";
} elseif ($shipping_methods == 'Collect 6') {
$display_text = "Royal Ascot shopping centre, near customer service centre (17:30-17:45)";
} elseif ($shipping_methods == 'Collect 11') {
$display_text = "Drop-off area outside Admiralty Centre, near McDonald's (Monday, Wednesday, Friday) 17:00-17:30";
} elseif ($shipping_methods == 'Collect 12') {
$display_text = "Kowloon Tong Suffolk roadside, near MTR Station Exit B (Tuesday, Thursday, Saturday) 17:00-17:30";
} elseif ($shipping_methods == 'Collect 13') {
$display_text = "Admiralty MTR customer service centre by Exit A (Monday, Wednesday, Friday) 17:30-17:45";
} elseif ($shipping_methods == 'Collect 14') {
$display_text = "Kowloon Tong MTR at ticket gate by Exit C (Tuesday, Thursday, Saturday) 18:00-18:15";
} elseif ($shipping_methods == 'Collect 15') {
$display_text = "Pop-Up Store 1, K11 Natural, Shop 201, K11 Art Mall, 18 Hanoi Road, Tsim Sha Tsui(24/10/2022 - 30/10/2022) 17:00-20:00";
} elseif ($shipping_methods == '自取') {
$display_text = "火炭烘焙室";
} elseif ($shipping_methods == '交收 1') {
$display_text = "金鐘MTR客務中心近A出口 (17:30)";
} elseif ($shipping_methods == '交收 2') {
$display_text = "九龍塘港鐵站C出口閘機旁 (18:00)";
} elseif ($shipping_methods == '交收 3') {
$display_text = "火炭港鐵站客戶服務中心,D出口旁 (17:30)";
} elseif ($shipping_methods == '交收 4') {
$display_text = "駿景園商場客戶服務中心旁 (17:00)";
} elseif ($shipping_methods == '交收 5') {
$display_text = "火炭港鐵站客戶服務中心,D出口旁 (18:00-18:15)";
} elseif ($shipping_methods == '交收 6') {
$display_text = "駿景園商場客戶服務中心旁 (17:30-17:45)";
} elseif ($shipping_methods == '交收 11') {
$display_text = "金鐘海富中心外上落客區,近麥當勞(星期一、三、五) 17:00-17:30";
} elseif ($shipping_methods == '交收 12') {
$display_text = "九龍塘沙福道路邊停車處、近港鐵站B出口(星期二、四、六) 17:00-17:30";
} elseif ($shipping_methods == '交收 13') {
$display_text = "金鐘MTR客務中心近A出口 (星期一、三、五) 17:30-17:45";
} elseif ($shipping_methods == '交收 14') {
$display_text = "九龍塘港鐵站C出口閘機旁 (星期二、四、六) 18:00-18:15";
} elseif ($shipping_methods == '交收 15') {
$display_text = "尖沙咀河內道18號K11 Art Mall 二樓 201號店 K11 Natural Pop-Up Store 1號(24/10/2022 - 30/10/2022) 17:00-20:00";
}
$fields['pickup_location'] = array(
'label' => __('Collect/Pick-up Location'),
'value' => $display_text,
);
return $fields;
}
// Acount remove downloads tab
add_filter('woocommerce_account_menu_items', 'custom_remove_downloads_my_account', 999);
function custom_remove_downloads_my_account($items)
{
unset($items['downloads']);
return $items;
}
//sold out in product page
add_action('woocommerce_single_product_summary', 'check_stock_in_product_page');
add_action('woocommerce_after_shop_loop_item_title', 'check_stock_in_product_page', 10);
function bbloomer_display_sold_out_loop_woocommerce()
{
global $product;
date_default_timezone_set("Asia/Hong_Kong");
$stock_sku = get_master_sku($product->get_sku());
if (isset($_SESSION['cart_date'])) {
$stock_date = $_SESSION['cart_date'];
} else {
$stock_date = date("Y-m-d");
}
//if (!$product->is_in_stock()) {
if (check_stock_init($stock_sku, $stock_date) == 0) {
if (get_language() == "chi") {
echo '<span class="soldout">敬請期待</span>';
} else {
echo '<span class="soldout">BE BACK SOON</span>';
}
} elseif (check_stock_init($stock_sku, $stock_date) == 2) {
if (get_language() == "chi") {
echo '<span class="soldout">即將推出</span>';
} else {
echo '<span class="soldout">COMING SOON</span>';
}
}
//}
}
//get stock remains from a given sku and delivery date
function get_sku_stock_by_date($sku, $date)
{
global $wpdb;
$result = $wpdb->get_results("SELECT `" . $sku . "` FROM sku_stock WHERE stock_date = '" . $date . "' LIMIT 1");
return $result[0]->$sku;
}
//get stock remains from a given sku and delivery date (remake)
function get_sku_stock_by_date_remake($sku, $date){
global $wpdb;
$result = $wpdb->get_results("SELECT `remain` FROM sku_stock_remake WHERE stock_date = '".$date."' AND sku = '".$sku."' LIMIT 1");
return $result[0]->$remain;
}
/* added checking for available shipping method vs time (By samiel on 2021-05-17) */
//checkout process checking....
add_action('woocommerce_checkout_process', 'customised_checkout_field_process');
function customised_checkout_field_process()
{
global $wpdb;
date_default_timezone_set("Asia/Hong_Kong");
if (!$_POST['delivery_date']) {
if (get_language() == "chi") {
wc_add_notice(__('選擇送貨/取貨日期'), 'error');
} else {
wc_add_notice(__('Select a Delivery/Pick-up Date'), 'error');
}
} elseif ($_POST['delivery_date'] == "x") {
if (get_language() == "chi") {
wc_add_notice(__('請與我們的客戶服務員聯絡(WhatsApp: +852 5612 5381)'), 'error');
} else {
wc_add_notice(__('Please contact our cs for help (WhatsApp: +852 5612 5381)'), 'error');
}
} elseif (!empty($_POST['shipping_method'][0])) {
$packages = WC()->shipping->get_packages();
foreach ($packages as $i => $package) {
if (isset($package['rates']) && isset($package['rates'][$_POST['shipping_method'][0]])) {
$rate = $package['rates'][$_POST['shipping_method'][0]];
$shipping_method_name = $rate->get_label();
}
}
$hour = date("H", time());
$min = date("i", time());
$today = date('Y-m-d', time());
if ($min >= 30) {
$hour = $hour + 0.5;
}
if ($_POST['delivery_date'] == $today) {
if ($hour >= 18) {
if (get_language() == "chi") {
wc_add_notice("不好意思!現在已過今日的截單時間,請選擇其他送貨/取貨日期", "error");
} else {
wc_add_notice("Today’s order has ended. Please select another day of delivery.", "error");
}
} else if ($hour >= 16) {
if (stristr($shipping_method_name, "Delivery") || stristr($shipping_method_name, "送貨")) {
if (get_language() == "chi") {
wc_add_notice("不好意思!今天的送貨服務已截單,您仍可選擇於今天17:30前到火炭烘焙室自取自取或其他送貨/取貨日期", "error");
} else {
wc_add_notice("Today’s delivery service has ended. You may choose to pick-up at our bakery house before 17:30 today or select another day of delivery.", "error");
}
}
if (stristr($shipping_method_name, "Collect") || stristr($shipping_method_name, "交收")) {
if (get_language() == "chi") {
wc_add_notice("不好意思!今天的交收服務已截單,您仍可選擇於今天18:30前到火炭烘焙室自取或其他送貨/取貨日期", "error");
} else {
wc_add_notice("Today’s collect service has ended. You may choose to pick-up at our bakery house before 17:30 today or select another day of delivery.", "error");
}
}
}
}
foreach (WC()->cart->get_cart() as $cart_item) {
$product = wc_get_product($cart_item['product_id']);
$sku = $product->get_sku(); //get sku#
$stock_sku = get_master_sku($sku); //get master sku if present
$unit_qty = 1;
if (has_master_sku($sku)) {
$unit_qty = get_master_sku_unit_qty($sku); //get master sku unit qty
$description = $product->get_name();
} else {
$variation_id = $cart_item['variation_id'];
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id); //get variation unit qty
} else {
$description = $product->get_name();
$unit_qty = 1;
}
}
$quantity = $cart_item['quantity'] * $unit_qty;
//check the stock in selected date
if (get_sku_stock_by_date($stock_sku, $_POST['delivery_date']) < $quantity) {
if (get_language() == "chi") {
wc_add_notice(__("不好意思! " . $product->get_name() . "在您選擇的日期剛剛被售出。您可以選擇另一個日期取貨/送貨"), 'error');
} else {
wc_add_notice(__("Oops! " . $product->get_name() . " has just been sold on your selected day. You may choose another day for delivery"), 'error');
}
}
}
} else {;
}
}
//update delivery date to order meta
add_action('woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta');
function custom_checkout_field_update_order_meta($order_id)
{
//global $wpdb;
if (!empty($_POST['delivery_date'])) {
update_post_meta($order_id, 'delivery_date', sanitize_text_field($_POST['delivery_date']));
}
}
//check successful payment then adjust stock
add_action('woocommerce_payment_complete', 'adjust_stock_action');
function adjust_stock_action($order_id)
{
if (!$order_id)
return;
global $wpdb;
// Getting an instance of the order object
$order = wc_get_order($order_id);
$delivery_date = $order->get_meta('delivery_date', true);
$adjust_stock = $order->get_meta('adjust_stock', true);
if (get_post_meta($order_id, 'stock_out', true))
return; // Exit if already processed
$arr_payment = array("AlipayHK", "WeChat Pay");
if (in_array($order->get_payment_method_title(), $arr_payment)) {
update_post_meta($order_id, "Payment", $order->get_payment_method_title());
}
if ($order->has_status('processing') || $order->has_status('completed')) {
if ($adjust_stock != "N") {
foreach ($order->get_items() as $item_id => $item) {
$prod = $item->get_product();
$sku = $prod->get_sku();
$variation_id = $item->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if (has_master_sku($sku)) {
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
} else {
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
} else {
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
$quantity = $item->get_quantity() * $unit_qty;
if (isset($delivery_date)) {
$qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
$qty_to = $qty_from - $quantity;
$sql_update = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to . "' WHERE stock_date = '" . $delivery_date . "' LIMIT 1";
if ($wpdb->query($sql_update)) {
write_log($delivery_date, "New Order", "Front End", $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
}
//reduce combine counter
$search = "SELECT * FROM `giftbox_combine_count` WHERE skus LIKE '%".$sku."%' LIMIT 1";
$combine_result = $wpdb->get_results($search);
if(count($combine_result) > 0){
$ori_counts = $combine_result[0]->counts;
$remain_counts = $ori_counts - $quantity;
$sql_update_counts = "UPDATE `giftbox_combine_count` SET counts = counts - ".$quantity." WHERE id = '".$combine_result[0]->id."' LIMIT 1";
$wpdb->query($sql_update_counts);
write_log($delivery_date, "Update Combine Counter", "Front End", $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update_counts);
// reduce stock of the same SKU in other defined date
$update_query = "UPDATE sku_stock SET `" . $stock_sku . "` = `" . $stock_sku . "` - ".$quantity." WHERE stock_date IN ('2023-01-19','2023-01-20','2023-01-21','2023-01-22','2023-01-23','2023-01-24','2023-01-25','2023-01-26','2023-01-27', '2023-01-28', '2023-01-29', '2023-01-30', '2023-01-31') AND stock_date != '".$delivery_date."' AND `" . $stock_sku . "` > 0 ";
$wpdb->query($update_query);
write_log($delivery_date, "Update Other Counter", "Front End", $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $update_query);
// reset sku stock to 0 for the same group if combine counter <= 0
if($remain_counts <= 0) {
$arr_skus = explode(",",$combine_result[0]->skus);
foreach($arr_skus as $reset_skus){
$reset_query = "UPDATE sku_stock SET `".trim($reset_skus)."` = '0' WHERE stock_date IN ('2023-01-19','2023-01-20','2023-01-21','2023-01-22','2023-01-23','2023-01-24','2023-01-25','2023-01-26','2023-01-27', '2023-01-28', '2023-01-29', '2023-01-30', '2023-01-31')";
$wpdb->query($reset_query);
write_log($delivery_date, "Reset Stock Count", "Front End", $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $reset_query);
}
}
}
}
}
if (isset($delivery_date)) {
wc_create_order_note($order_id, "Delivery Date: " . sanitize_text_field($delivery_date), false, true);
update_post_meta($order_id, 'stock_out', '1');
update_post_meta($order_id, 'adjust_stock', 'Y');
}
}
}
}
//thank you page to adjust stock and create order note for delivery date
add_action('woocommerce_thankyou', 'ceb_order_complete', 10, 1);
function ceb_order_complete($order_id)
{
date_default_timezone_set("Asia/Hong_Kong");
if (!$order_id)
return;
global $wpdb;
// Getting an instance of the order object
$order = wc_get_order($order_id);
$delivery_date = $order->get_meta('delivery_date', true);
adjust_stock_action($order_id);
if ($order->has_status('processing') || $order->has_status('completed')) {
$new_order_notification = $order->get_meta('new_order_notification', true);
if ($new_order_notification != 1) {
$display_delivery_date = date("d/m/Y", strtotime($delivery_date));
if ($delivery_date != date("Y-m-d")) {
$title = "NEW ORDER";
} else {
$title = "\u{2B50}TODAY";
}
$message = "#" . $order->get_order_number() . " " . $display_delivery_date;
$topic = "newOrder";
initPushNotification($title, $message, $topic, $order_id);
update_post_meta($order_id, 'new_order_notification', '1');
}
//display alert notification box
echo "<div class='alertCheckout'>";
if (get_language() == 'chi') {
echo "<p><b>訂單號碼: #" . $order->get_order_number() . "</b></p>";
} else {
echo "<p><b>Order Number: #" . $order->get_order_number() . "</b></p>";
}
$formatted_delivery_date = date('d/m/Y (l)', strtotime($delivery_date));
$shipping_methods = $order->get_shipping_method();
if ($shipping_methods == 'Pick-up') {
if (date('N', strtotime($delivery_date)) != 6) {
echo '<p>To guarantee you have the freshest bread possible, please pick-up your order 3pm-5:30pm on ' . $formatted_delivery_date . '<br />
Pick-up location: Room Q, 6/F, Block 1, Kin Ho Industrial Building, 14-24 Au Pui Wan Street, Fo Tan.</p>';
echo '<p>Contact :+852 5612 5381</p>';
} else {
echo '<p>To guarantee you have the freshest bread possible, please pick-up your order 3pm-5:30pm on ' . $formatted_delivery_date . '<br />
Pick-up location: Room Q, 6/F, Block 1, Kin Ho Industrial Building, 14-24 Au Pui Wan Street, Fo Tan.</p>';
echo '<p>Contact :+852 5612 5381</p>';
}
} elseif ($shipping_methods == 'Delivery') {
echo '<p>Your order will be delivered to you on ' . $formatted_delivery_date . ', 2pm to 7pm.<br />
Delivery location: ' . $order->get_formatted_billing_address() . '</p>';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Delivery 2') {
echo '<p>Your order will be delivered to you on ' . $formatted_delivery_date . ', 2pm to 7pm.<br />
Delivery location: ' . $order->get_formatted_billing_address() . '</p>';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Delivery 3') {
echo '<p>Your order will be delivered to you on ' . $formatted_delivery_date . ', 2pm to 7pm.<br />
Delivery location: ' . $order->get_formatted_billing_address() . '</p>';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Kau To Shan, Fo Tan Mid-levels') {
echo '<p>Your order will be delivered to you on ' . $formatted_delivery_date . ', 2pm to 7pm.<br />
Delivery location: ' . $order->get_formatted_billing_address() . '</p>';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 1') {
echo '<p>Your order will be delivered to Admiralty MTR customer service centre by Exit A (17:30) on ' . $formatted_delivery_date . '<br/>';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 2') {
echo '<p>Your order will be delivered to Kowloon Tong MTR at ticket gate by Exit C (18:00) on ' . $formatted_delivery_date . '<br/>';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 3') {
echo '<p>Your order will be delivered to Fo Tan MTR station, customer service centre near Exit D (17:30) on ' . $formatted_delivery_date . '<br/>';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 4') {
echo '<p>Your order will be delivered to Royal Ascot shopping centre, near customer service centre (17:00) on ' . $formatted_delivery_date . '.<br />';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 5') {
echo '<p>Your order will be delivered to Fo Tan MTR station, customer service centre near Exit D (18:00-18:15) on ' . $formatted_delivery_date . '.<br />';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 6') {
echo '<p>Your order will be delivered to Royal Ascot Shipping Centre, near customer service centre (17:30-17:45) on ' . $formatted_delivery_date . '.<br />';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 11') {
echo "<p>Your order will be delivered to Drop-off area outside Admiralty Centre, near McDonald's (Monday, Wednesday, Friday) 17:00-17:30
on " . $formatted_delivery_date . ".<br />";
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 12') {
echo '<p>Your order will be delivered to Kowloon Tong Suffolk roadside, near MTR Station Exit B (Tuesday, Thursday, Saturday) 17:00-17:30 on ' . $formatted_delivery_date . '.<br />';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 13') {
echo '<p>Your order will be delivered to Admiralty MTR customer service centre by Exit A (Monday, Wednesday, Friday) 17:30-17:45 on ' . $formatted_delivery_date . '.<br />';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 14') {
echo '<p>Your order will be delivered to Kowloon Tong MTR at ticket gate by Exit C (Tuesday, Thursday, Saturday) 18:00-18:15 on ' . $formatted_delivery_date . '.<br />';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == 'Collect 15') {
echo '<p>Pop-Up Store 1, K11 Natural, Shop 201, K11 Art Mall, 18 Hanoi Road, Tsim Sha Tsui on ' . $formatted_delivery_date . '.<br />';
echo '<p>Contact CS:+852 5612 5381</p>';
} elseif ($shipping_methods == '自取') {
if (date('N', strtotime($delivery_date)) != 6) {
echo '<p>保證您能享用新鮮的麵包,請您在已選的日子,下午3時至5時30分自取<br />
自取地點:火炭坳背灣街14-24號金豪工業大廈一期6樓Q室。</p>';
echo '<p>聯絡客服:+852 5612 5381</p>';
} else {
echo '<p>保證您能享用新鮮的麵包,請您在已選的日子,下午3時至5時30分自取<br />
自取地點:火炭坳背灣街14-24號金豪工業大廈一期6樓Q室。</p>';
echo '<p>聯絡客服:+852 5612 5381</p>';
}
} elseif ($shipping_methods == '送貨') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' (下午2時至7時)送到給你。</p>';
echo '<p>送貨地址: <br>' . $order->get_formatted_billing_address() . '</p>';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '送貨 2') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' (下午2時至7時)送到給你。<br />';
echo '<p>送貨地址: <br>' . $order->get_formatted_billing_address() . '</p>';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '送貨 3') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' (下午2時至7時)送到給你。<br />';
echo '<p>送貨地址: <br>' . $order->get_formatted_billing_address() . '</p>';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '九肚山、火炭半山區住宅') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' (下午2時至7時)送到給你。<br />';
echo '<p>送貨地址: <br>' . $order->get_formatted_billing_address() . '</p>';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 1') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在金鐘MTR客務中心近A出口 (17:30)交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 2') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在九龍塘港鐵站,C出口旁 (18:00)交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 3') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在火炭港鐵站客戶服務中心,D出口旁 (17:30)交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 4') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在駿景園商場客戶服務中心旁 (17:00)交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 5') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在火炭港鐵站客戶服務中心,D出口旁 (18:00-18:15)交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 6') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在駿景園商場客戶服務中心旁 (17:30-17:45)交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 11') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在金鐘海富中心外上落客區,近麥當勞 (星期一、三、五) 17:00-17:30交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 12') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在九龍塘沙福道路邊停車處、近港鐵站B出口 (星期二、四、六) 17:00-17:30交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 13') {
echo '<p>你的訂單將於' . $formatted_delivery_date . '在金鐘MTR客務中心近A出口 (星期一、三、五) 17:30-17:45交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 14') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 在九龍塘港鐵站C出口閘機旁 (星期二、四、六) 18:00-18:15交收。<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} elseif ($shipping_methods == '交收 15') {
echo '<p>你的訂單將於' . $formatted_delivery_date . ' 尖沙咀河內道18號K11 Art Mall 二樓 201號店 K11 Natural Pop-Up Store 1號交收。 17:00-20:00<br />';
echo '<p>聯絡客服:+852 5612 5381</p>';
} else {
echo "";
}
if (get_language() == 'chi') {
echo "<p>訂單確認已發送至您的電子郵件。</p>";
echo "<p>您的訂單已被確認並接受,不允許更改、取消或退款。</p>";
} else {
echo "<p>An order comfirmation has been sent to your email.</p>";
echo "<p>Your order has been confirmed and accepted, no changes, cancellation or refund is allowed.</p>";
}
echo "<span class='closebtnCheckout' onclick='this.parentElement.style.display=\"none\";'>OK</span>";
echo "</div>";
}
}
// get daily delivery quanity by a given sku and delivery date
function get_sku_daily_delivery_count($sku, $date)
{
global $wpdb;
$count = 0;
//search all order
$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed'));
$result = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'shop_order' AND post_status IN ('{$post_status}')");
foreach ($result as $order_obj) {
$order = wc_get_order($order_obj->ID);
//get order delivery date value
$delivery_date = $order->get_meta('delivery_date', true);
foreach ($order->get_items() as $item) {
$product = wc_get_product($item->get_product_id());
if ($delivery_date == $date && $product->get_sku() == $sku) {
$count += $item->get_quantity();
}
}
}
return $count;
}
// get next work date
function get_next_work_date($datetime, $format = 'Y-m-d')
{
//get holiday list
$arr_holiday = get_holiday_list();
//get tomorrow
$nextday = date('Y-m-d', strtotime($datetime) + 86400);
//get next weekday (1=mon, 2=tue.....7=sun)
$nextweekday = date('N', strtotime($nextday));
if (in_array($nextday, $arr_holiday)) { //if next day is holiday
return get_next_work_date(date($format, strtotime($datetime) + 86400));
} elseif ($nextweekday == 7) { // if next day is sunday
return get_next_work_date(date($format, strtotime($datetime) + 86400));
} else { // normal week day
return date($format, strtotime($nextday));
}
}
//shipping option change label
add_filter('woocommerce_cart_shipping_method_full_label', 'change_shipping_label', 10, 2);
function change_shipping_label($full_label, $method)
{
?><head>
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>
<?php
// $full_label = str_replace( "Pick-up", "Pick-up - Fo Tan bakery house", $full_label );
$full_label = str_replace("Pick-up", "Pick-up", $full_label);
//$full_label = str_replace( "Collect 1", "Collect 1 - Admiralty MTR at ticket gate by the customer service centre (17:30): $0", $full_label );
//$full_label = str_replace( "Collect 2", "Collect 2 - Kowloon Tong MTR at ticket gate by Exit C (18:00): $0", $full_label );
$full_label = str_replace("Collect 3", "Fo Tan MTR station, customer service centre near Exit D (17:30): $0", $full_label);
$full_label = str_replace("Collect 4", "Royal Ascot shopping centre, near customer service centre (17:00): $0", $full_label);
$full_label = str_replace("Collect 5", "Fo Tan MTR station, customer service centre near Exit D (18:00-18:15): $0", $full_label);
$full_label = str_replace("Collect 6", "Royal Ascot Shipping Centre, near customer service centre (17:30-17:45): $0", $full_label);
$full_label = str_replace("Collect 11", "Drop-off area outside Admiralty Centre, near McDonald's <b style='color:red;'>(Monday, Wednesday, Friday) 17:00-17:30</b>: $0", $full_label);
$full_label = str_replace("Collect 12", "Kowloon Tong Suffolk roadside, near MTR Station Exit B <b style='color:red;'>(Tuesday, Thursday, Saturday) 17:00-17:30</b>: $0", $full_label);
$full_label = str_replace("Collect 13", "Admiralty MTR customer service centre by Exit A <b style='color:red;'>(Monday, Wednesday, Friday) 17:30-17:45</b>: $0", $full_label);
$full_label = str_replace("Collect 14", "Kowloon Tong MTR at ticket gate by Exit C <b style='color:red;'>(Tuesday, Thursday, Saturday) 18:00-18:15</b>: $0", $full_label);
$full_label = str_replace("Collect 15", "Pop-Up Store 1, K11 Natural, Shop 201, K11 Art Mall, 18 Hanoi Road, Tsim Sha Tsui <b style='color:red;'>(24/10/2022 - 30/10/2022) 17:00-20:00</b>: $0", $full_label);
$full_label = str_replace("Delivery 2", "Delivery - Kau To Shan: $0", $full_label);
$full_label = str_replace("Delivery 3", "Delivery - Deerhill Bay: $0", $full_label);
$full_label = str_replace("Kau To Shan, Fo Tan Mid-levels", "Kau To Shan, Fo Tan Mid-levels: $0<br>
<small>Only applicable for Kau To Shan, Lok Lam Road, Lok Lin Path, Lok Fung Path, Lok Ha Square, Lok Shun Path, Lok Yuen Path, Hill Lodge, Shatin Lodge, The Grandville and Ficus Garden</small>
", $full_label);
// $full_label = str_replace( "自取", "自取 - 火炭烘焙室", $full_label );
$full_label = str_replace("自取", "自取", $full_label);
$full_label = str_replace("送貨 2", "送貨 - 九肚山: $0", $full_label);
$full_label = str_replace("送貨 3", "送貨 - 鹿茵山莊: $0", $full_label);
$full_label = str_replace("九肚山、火炭半山區住宅", "九肚山、火炭半山區住宅: $0<br>
<small>只限九肚山、樂林路、樂蓮徑、樂楓徑、樂霞坊、樂信徑、樂園徑、沙田曉蘆、沙田山莊、晉名峰及榕翠園</small>
", $full_label);
//$full_label = str_replace( "交收 1", "交收 1 - 金鐘MTR客務中心近A出口 (17:30): $0", $full_label );
//$full_label = str_replace( "交收 2", "交收 2 - 九龍塘港鐵站C出口閘機旁 (18:00): $0", $full_label );
$full_label = str_replace("交收 3", "火炭站客戶服務中心,D出口旁 (17:30): $0", $full_label);
$full_label = str_replace("交收 4", "駿景園商場客戶服務中心旁 (17:00): $0", $full_label);
$full_label = str_replace("交收 5", "火炭港鐵站客戶服務中心,D出口旁 (18:00-18:15): $0", $full_label);
$full_label = str_replace("交收 6", "駿景園商場客戶服務中心旁 (17:30-17:45): $0", $full_label);
$full_label = str_replace("交收 11", "金鐘海富中心外上落客區,近麥當勞 <b style='color:red;'>( 星期一、三、五) 17:00-17:30</b>: $0", $full_label);
$full_label = str_replace("交收 12", "九龍塘沙福道路邊停車處、近港鐵站B出口 <b style='color:red;'>(星期二、四、六) 17:00-17:30</b>: $0", $full_label);
$full_label = str_replace("交收 13", "金鐘MTR客務中心近A出口 <b style='color:red;'>( 星期一、三、五) 17:30-17:45</b>: $0", $full_label);
$full_label = str_replace("交收 14", "九龍塘港鐵站C出口閘機旁 <b style='color:red;'>(星期二、四、六) 18:00-18:15</b>: $0", $full_label);
$full_label = str_replace("交收 15", "尖沙咀河內道18號K11 Art Mall 二樓 201號店 K11 Natural Pop-Up Store 1號 <b style='color:red;'>(24/10/2022 - 30/10/2022) 17:00-20:00</b>: $0", $full_label);
if (strpos($full_label, "Collect 11") !== false) {
$full_label .= " <a href='https://www.breadsecret.com/wp-content/uploads/2022/03/Collect11.png' target='_blank'><i class='fa fa-exclamation-circle' aria-hidden='true' style='margin-left:5px;color: orange;'></i></a>";
}
if (strpos($full_label, "Collect 12") !== false) {
$full_label .= " <a href='https://www.breadsecret.com/wp-content/uploads/2022/03/Collect12.png' target='_blank'><i class='fa fa-exclamation-circle' aria-hidden='true' style='margin-left:5px;color: orange;'></i></a>";
}
if (strpos($full_label, "交收 11") !== false) {
$full_label .= " <a href='https://www.breadsecret.com/wp-content/uploads/2022/03/Collect11.png' target='_blank'><i class='fa fa-exclamation-circle' aria-hidden='true' style='margin-left:5px;color: orange;'></i></a>";
}
if (strpos($full_label, "交收 12") !== false) {
$full_label .= " <a href='https://www.breadsecret.com/wp-content/uploads/2022/03/Collect12.png' target='_blank'><i class='fa fa-exclamation-circle' aria-hidden='true' style='margin-left:5px;color: orange;'></i></a>";
}
return $full_label;
}
//shipping option description on email to user
add_action('woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4);
function my_completed_order_email_instructions($order, $sent_to_admin, $plain_text, $email)
{
// Only for processing and completed email notifications to customer
$holiday = false; //default not a holiday
$arr_holiday = get_holiday_list();
if (in_array(date('Y-m-d'), $arr_holiday)) // check if today is in holiday list
$holiday = true;
if (!('customer_processing_order' == $email->id || 'customer_completed_order' == $email->id)) return;
foreach ($order->get_items('shipping') as $shipping_item) {
$shipping_methods = $order->get_shipping_method();
echo translate_shipping_method($shipping_methods);
echo "<p>Your order has been confirmed and accepted, no changes, cancellation or refund is allowed.</p>";
}
}
if (isset($_POST['show']) && $_POST['show'] == 0) {
remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
}
add_filter('woocommerce_is_purchasable', 'woocommerce_hide_add_to_cart_button', 10, 2);
function woocommerce_hide_add_to_cart_button($is_purchasable = true, $product)
{
global $wpdb;
date_default_timezone_set("Asia/Hong_Kong");
if (isset($_SESSION['cart_date'])) {
$stock_date = $_SESSION['cart_date'];
} else {
$stock_date = date("Y-m-d");
}
$sku = $product->get_sku();
$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 = '" . $stock_date . "' LIMIT 1");
$array = (array) $result[0];
$limit = floor($array[$stock_sku] / $unit_qty);
if (isset($_POST['show']) && $_POST['show'] == 0) {
return false;
} elseif (check_stock_init($stock_sku, $stock_date) == 0 || check_stock_init($stock_sku, $stock_date) == 2) {
return false;
} elseif ($stock_date == date("Y-m-d") && date("H") >= 16) {
return false;
} elseif ($limit <= 0) {
return false;
} else {
return $is_purchasable;
}
}
add_action('woocommerce_single_product_summary', 'show_wholesaler_price', 10, 4);
function show_wholesaler_price()
{
global $product;
global $wpdb;
if (isset($_POST['show']) && $_POST['show'] == 0) {
$results = $wpdb->get_results("SELECT * FROM `sku_wholesaler` WHERE sku_id = '" . $_POST['sku_id'] . "' AND period_id = '" . $_POST['period_id'] . "' LIMIT 1");
if (count($results) > 0) {
echo "<br>$" . number_format($product->get_price() * $results[0]->price_factor, 2) . " " . get_post_meta($product->get_id(), "_woo_uom_input", true);
}
}
}
// show notice in product page if today's sotck is below 5 or out of stock
//add_action( 'woocommerce_before_add_to_cart_form', 'check_stock_in_product_page', 10, 4 );
function check_stock_in_product_page()
{
date_default_timezone_set("Asia/Hong_Kong");
global $product;
global $wpdb;
if (isset($_SESSION['cart_date'])) {
$stock_date = $_SESSION['cart_date'];
} else {
$stock_date = date("Y-m-d");
}
if ($stock_date == date("Y-m-d")) {
$today_chi = "今天";
$today_eng = "today";
} else {
$today_chi = "所選日子";
$today_eng = "on selected date";
}
if (isset($_POST['show']) && $_POST['show'] == 0) {;
} else {
$arr_holiday = get_holiday_list();
if (in_array($stock_date, $arr_holiday)) { // check if today is in holiday list
if (get_language() == 'chi') {
echo "<p class='b50442'><i>" . $today_chi . "店休。您仍可選擇其他日期取貨或送貨。</i></p>";
} else {
echo "<p class='b50442'><i>It's holiday " . $today_eng . ". You may still select another day to pick-up or deliver</i></p>";
}
} elseif (date('N', strtotime($stock_date)) == "7" && $stock_date != "2022-10-30") { // check if today is in holiday list
if (get_language() == 'chi') {
echo "<p class='b50442'><i>" . $today_chi . "是假期。您仍可選擇其他日期取貨或送貨。</i></p>";
} else {
echo "<p class='b50442'><i>It's holiday " . $today_eng . ". You may still select another day to pick-up or deliver</i></p>";
}
} else {
//echo "test";
$sku = $product->get_sku();
$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 = '" . $stock_date . "' LIMIT 1");
$init_info = get_sku_init_info($stock_sku);
$end_date = $init_info->end_date;
if (check_stock_init($stock_sku, $stock_date) == 1) { // within selling period
if (count($result) > 0) {
$array = (array) $result[0];
$limit = floor($array[$stock_sku] / $unit_qty);
if ($stock_date == date("Y-m-d") && date("H") >= 16) {
if (get_language() == 'chi') {
echo "<p class='b50442'><i>此產品於" . $today_chi . "已售罄。您仍可選擇其他日期取貨或送貨。</i></p>";
} else {
echo "<p class='b50442'><i>This item has been sold " . $today_eng . ". You may still select another day to pick-up or deliver</i></p>";
}
} elseif ($limit <= 0) {
if ($end_date == $stock_date) { // check if last date of selling
if (get_language() == 'chi') {
echo "<p class='b50442'><i>此產品已全部售罄。</i></p>";
} else {
echo "<p class='b50442'><i>This item has been sold.</i></p>";
}
} else {
if (get_language() == 'chi') {
echo "<p class='b50442'><i>此產品於" . $today_chi . "已售罄。您仍可選擇其他日期取貨或送貨。</i></p>";
} else {
echo "<p class='b50442'><i>This item has been sold " . $today_eng . ". You may still select another day to pick-up or deliver</i></p>";
}
}
} elseif ($limit <= 3) {
if (get_language() == 'chi') {
echo "<p class='b50442'><i>此產品於" . $today_chi . "只餘" . $limit . "份</i></p>";
} else {
echo "<p class='b50442'><i>Only " . $limit . " left " . $today_eng . "</i></p>";
}
}
}
}
}
}
}
//from::https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column
//For displaying in Woocommerce Order Page columns.
add_filter('manage_edit-shop_order_columns', 'set_custom_edit_shop_order_columns');
add_filter('manage_edit-shop_order_columns', 'set_custom_edit_shop_order_columns3');
add_filter('manage_edit-shop_order_columns', 'set_custom_edit_shop_order_columns4');
add_filter('manage_edit-shop_order_columns', 'set_custom_edit_shop_order_columns5');
function set_custom_edit_shop_order_columns($columns)
{
$columns['Payment'] = __('Payment', 'https://www.breadsecret.com/');
return $columns;
}
function set_custom_edit_shop_order_columns3($columns)
{
$columns['shipping_phone'] = __('shipping_phone', 'https://www.breadsecret.com/');
return $columns;
}
function set_custom_edit_shop_order_columns4($columns)
{
$columns['shipping_email'] = __('shipping_email', 'https://www.breadsecret.com/');
return $columns;
}
function set_custom_edit_shop_order_columns5($columns)
{
$columns['delivery_date'] = __('Delivery Date', 'https://www.breaDsecret.com/');
return $columns;
}
// Add the data to the custom columns for the order post type:
add_action('manage_shop_order_posts_custom_column', 'custom_shop_order_column', 10, 2);
add_action('manage_shop_order_posts_custom_column', 'custom_shop_order_column3', 10, 2);
add_action('manage_shop_order_posts_custom_column', 'custom_shop_order_column4', 10, 2);
add_action('manage_shop_order_posts_custom_column', 'custom_shop_order_column5', 10, 2);
add_action('manage_shop_order_posts_custom_column', 'custom_shop_order_column6', 10, 2);
function custom_shop_order_column($column, $post_id)
{
switch ($column) {
case 'Payment':
echo esc_html(get_post_meta($post_id, 'Payment', true));
break;
}
}
function custom_shop_order_column3($column, $post_id)
{
switch ($column) {
case 'shipping_phone':
echo esc_html(get_post_meta($post_id, 'shipping_phone', true));
break;
}
}
function custom_shop_order_column4($column, $post_id)
{
switch ($column) {
case 'shipping_email':
echo esc_html(get_post_meta($post_id, 'shipping_email', true));
break;
}
}
function custom_shop_order_column5($column, $post_id)
{
switch ($column) {
case 'payment_terms':
echo esc_html(get_post_meta($post_id, 'payment_terms', true));
break;
}
}
function custom_shop_order_column6($column, $post_id)
{
switch ($column) {
case 'delivery_date':
echo esc_html(get_post_meta($post_id, 'delivery_date', true));
break;
}
}
// For display and saving in order details page.
add_action('add_meta_boxes', 'add_shop_order_meta_box');
function add_shop_order_meta_box()
{
add_meta_box(
'Payment',
__('Payment', 'https://www.breadsecret.com/'),
'shop_order_display_callback',
'shop_order'
);
}
add_action('add_meta_boxes', 'add_shop_order_meta_box5');
function add_shop_order_meta_box5()
{
add_meta_box(
'payment_terms',
__('payment_terms', 'https://www.breadsecret.com/'),
'shop_order_display_callback5',
'shop_order'
);
}
// draw payment option in admin order page
function shop_order_display_callback($post)
{
$value = get_post_meta($post->ID, 'Payment', true);
$arr_payment = get_customer_payment_method_list();
echo '<select style="width:50%"name="Payment" id="Payment">';
echo '<option value=""></option>';
foreach ($arr_payment as $payment) {
echo '<option value="' . $payment . '" ';
if ($value == $payment) echo 'selected';
echo '>' . $payment . '</option>';
}
echo '</select>';
}
/*
add_action('add_meta_boxes', 'add_shop_order_meta_box3');
function add_shop_order_meta_box3()
{
add_meta_box(
'shipping_phone',
__('shipping_phone', 'https://www.breadsecret.com/'),
'shop_order_display_callback3',
'shop_order'
);
}
add_action('add_meta_boxes', 'add_shop_order_meta_box4');
function add_shop_order_meta_box4()
{
add_meta_box(
'shipping_email',
__('shipping_email', 'https://www.breadsecret.com/'),
'shop_order_display_callback4',
'shop_order'
);
}
*/
function shop_order_display_callback5($post)
{
$value = get_post_meta($post->ID, 'payment_terms', true);
$arr_payment = get_customer_payment_terms_list();
echo '<select style="width:50%"name="payment_terms" id="payment_terms">';
echo '<option value=""></option>';
foreach ($arr_payment as $payment_terms) {
echo '<option value="' . $payment_terms . '" ';
if ($value == $payment_terms) echo 'selected';
echo '>' . $payment_terms . '</option>';
}
echo '</select>';
}
function shop_order_display_callback3($post)
{
$value = get_post_meta($post->ID, '_shipping_phone', true);
echo '<input type="text" style="width:100%" id="shipping_phone" name="shipping_phone" value="' . esc_attr($value) . '">';
}
function shop_order_display_callback4($post)
{
$value = get_post_meta($post->ID, '_shipping_email', true);
echo '<input type="text" style="width:100%" id="shipping_email" name="shipping_email" value="' . esc_attr($value) . '">';
}
// For display and saving in order details page.
add_action('add_meta_boxes', 'add_shop_order_meta_box2');
function add_shop_order_meta_box2()
{
add_meta_box(
'delivery_date',
__('delivery_date', 'https://www.breadsecret.com/'),
'shop_order_display_callback2',
'shop_order'
);
}
// draw delivery date picker (not supported by MacOS safari)
function shop_order_display_callback2($post)
{
$value = get_post_meta($post->ID, 'delivery_date', true);
echo '<input type="date" id="delivery_date" name="delivery_date" value="' . esc_attr($value) . '">';
echo '<input type="hidden" id="o_delivery_date" name="o_delivery_date" value="' . esc_attr($value) . '">';
}
// For saving delivery and payment value in admin order page
add_action('save_post', 'save_shop_order_meta_box_data');
function save_shop_order_meta_box_data($post_id)
{
global $wpdb;
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (isset($_POST['post_type']) && 'shop_order' == $_POST['post_type']) {
if (!current_user_can('edit_shop_order', $post_id)) {
return;
}
}
// check if this is an admin order page
if (!is_admin()) {
return;
}
//handling shipping phone
if (isset($_POST['shipping_phone'])) {
update_post_meta($post_id, '_shipping_phone', sanitize_text_field($_POST['shipping_phone']));
}
//handling shipping email
if (isset($_POST['shipping_email'])) {
update_post_meta($post_id, '_shipping_email', sanitize_text_field($_POST['shipping_email']));
}
//handling shipping email
if (isset($_POST['_shipping_email'])) {
update_post_meta($post_id, '_shipping_email', sanitize_text_field($_POST['_shipping_email']));
}
//handling payment
$original_Payment = get_post_meta($post_id, 'Payment', true);
//adjust stock option
$adjust_stock = get_post_meta($post_id, 'adjust_stock', true);
if (!isset($_POST['Payment'])) {;
} elseif ($original_Payment == $_POST['Payment']) {;
} else {
update_post_meta($post_id, 'Payment', sanitize_text_field($_POST['Payment']));
if ($_POST['Payment'] != "") {
wc_create_order_note($post_id, "Payment: " . sanitize_text_field($_POST['Payment']), false, true);
}
}
//handling payment_terms
$original_payment_terms = get_post_meta($post_id, 'payment_terms', true);
if (!isset($_POST['payment_terms'])) {;
} elseif ($original_payment_terms == $_POST['payment_terms']) {;
} else {
update_post_meta($post_id, 'payment_terms', sanitize_text_field($_POST['payment_terms']));
if ($_POST['payment_terms'] != "") {
wc_create_order_note($post_id, "payment_terms: " . sanitize_text_field($_POST['payment_terms']), false, true);
}
}
//handling delivery date and stock
$type = "Back End";
$original_delivery_date = $_POST['o_delivery_date'];
if ($original_delivery_date != "") {
$action = "Edit Order";
} else {
$action = "New Order";
}
if (!isset($_POST['delivery_date'])) { //do nothing is no delivery date selected
;
} elseif ($original_delivery_date == $_POST['delivery_date']) { //delivery date has no change
;
} else {
update_post_meta($post_id, 'delivery_date', sanitize_text_field($_POST['delivery_date']));
if ($_POST['delivery_date'] != "") {
$order = wc_get_order($post_id);
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
$sku = $product->get_sku();
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if (has_master_sku($sku)) {
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
} else {
$variation_id = $item->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
} else {
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
$quantity = $item->get_quantity() * $unit_qty;
//if edit delivery date, add stock to original delivery date
if ($action == "Edit Order") {
if ($adjust_stock == "Y") {
$qty_from_o = get_sku_stock_by_date($stock_sku, $original_delivery_date);
$qty_to_o = $qty_from_o + $quantity;
$sql_update_o = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to_o . "' WHERE stock_date = '" . sanitize_text_field($original_delivery_date) . "' LIMIT 1";
if ($wpdb->query($sql_update_o)) {
write_log($original_delivery_date, $action, $type, $post_id, $stock_sku, $description, $qty_from_o, $qty_to_o, get_current_user_id(), get_client_ip(), $sql_update_o);
}
$qty_from = get_sku_stock_by_date($stock_sku, $_POST['delivery_date']);
$qty_to = $qty_from - $quantity;
$sql_update = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to . "' WHERE stock_date = '" . sanitize_text_field($_POST['delivery_date']) . "' LIMIT 1";
if ($wpdb->query($sql_update)) {
write_log($_POST['delivery_date'], $action, $type, $post_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
}
}
} else {
//deduct stock from the new delivery date
$qty_from = get_sku_stock_by_date($stock_sku, $_POST['delivery_date']);
$qty_to = $qty_from - $quantity;
$sql_update = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to . "' WHERE stock_date = '" . sanitize_text_field($_POST['delivery_date']) . "' LIMIT 1";
if ($wpdb->query($sql_update)) {
write_log($_POST['delivery_date'], $action, $type, $post_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
}
}
}
//create order note
wc_create_order_note($post_id, "Delivery Date: " . sanitize_text_field($_POST['delivery_date']), false, true);
}
}
}
//adjust stock when line item(product) is added to an on-hold order (at backend)
add_action('woocommerce_ajax_order_items_added', 'custom_add_item', 10, 2);
function custom_add_item($added_items, $order)
{
global $wpdb;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (isset($_POST['post_type']) && 'shop_order' == $_POST['post_type']) {
if (!current_user_can('edit_shop_order', $post_id)) {
return;
}
}
// check if this is an admin order page
if (!is_admin()) {
return;
}
$type = "Back End";
$action = "Add Line Item";
$order_id = $order->get_id();
$delivery_date = get_post_meta($order_id, 'delivery_date', true);
$adjust_stock = get_post_meta($order_id, 'adjust_stock', true);
foreach ($added_items as $added_item) {
if ('line_item' === $added_item->get_type()) {
/** @var \WC_Order_Item_Product $added_item */
$product = $added_item->get_product();
$sku = $product->get_sku();
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if (has_master_sku($sku)) {
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
} else {
$variation_id = $added_item->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
} else {
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
if ($adjust_stock == "Y") {
//if($adjust_stock!="N") {
$quantity = $added_item->get_quantity() * $unit_qty;
$qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
$qty_to = $qty_from - $quantity;
$sql_update = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to . "' WHERE stock_date = '" . sanitize_text_field($delivery_date) . "' LIMIT 1";
if ($wpdb->query($sql_update)) {
write_log($delivery_date, $action, $type, $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
}
}
}
}
}
//add stock when line item(product) is removed from an on-hold order (at backend)
add_action('woocommerce_before_delete_order_item', 'custom_remove_order_item', 10, 1);
function custom_remove_order_item($item_id)
{
global $wpdb;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (isset($_POST['post_type']) && 'shop_order' == $_POST['post_type']) {
if (!current_user_can('edit_shop_order', $post_id)) {
return;
}
}
// check if this is an admin order page
if (!is_admin()) {
return;
}
$type = "Back End";
$action = "Remove Line Item";
$item = new WC_Order_Item_Product($item_id);
$order_id = $item->get_order_id();
$delivery_date = get_post_meta($order_id, 'delivery_date', true);
$adjust_stock = get_post_meta($order_id, 'adjust_stock', true);
$product = $item->get_product();
$sku = $product->get_sku();
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if (has_master_sku($sku)) {
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
} else {
$variation_id = $item->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
} else {
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
if ($adjust_stock == "Y") {
//if($adjust_stock!="N") {
$quantity = $item->get_quantity() * $unit_qty;
$qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
$qty_to = $qty_from + $quantity;
$sql_update = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to . "' WHERE stock_date = '" . sanitize_text_field($delivery_date) . "' LIMIT 1";
if ($wpdb->query($sql_update)) {
write_log($delivery_date, $action, $type, $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
}
}
}
//adjust stock when line item(product) qty is edited from an on-hold order after pressing save button in item section(at backend)
add_action('woocommerce_before_save_order_items', 'custom_before_save_order_items', 10, 2);
function custom_before_save_order_items($order_id, $items)
{
global $wpdb;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (isset($_POST['post_type']) && 'shop_order' == $_POST['post_type']) {
if (!current_user_can('edit_shop_order', $order_id)) {
return;
}
}
// check if this is an admin order page
if (!is_admin()) {
return;
}
$order = wc_get_order($order_id);
$delivery_date = get_post_meta($order_id, 'delivery_date', true);
$adjust_stock = get_post_meta($order_id, 'adjust_stock', true);
//get original item info (item id and qty) ....before save
$arr_before = array();
foreach ($order->get_items() as $item_id => $item_before) {
if ('line_item' === $item_before->get_type()) {
$product = $item_before->get_product();
$sku = $product->get_sku();
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if (has_master_sku($sku)) {
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
} else {
$variation_id = $item_before->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
} else {
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
$arr_before_line = array("item_id" => $item_id, "qty" => $item_before->get_quantity(), "sku" => $stock_sku, "description" => $description, "unit_qty" => $unit_qty);
$arr_before[] = $arr_before_line;
}
}
//get being saved item info (item id and qty) ....after save
$arr_after = array();
foreach ($items['order_item_id'] as $idx => $line_item_id) {
$arr_after_line = array("item_id" => $line_item_id, "qty" => $items['order_item_qty'][$line_item_id]);
$arr_after[] = $arr_after_line;
}
if ($adjust_stock == "Y") {
//find out which item has changed qty
foreach ($arr_before as $index => $arr_info) {
if ($arr_info['item_id'] == $arr_after[$index]['item_id']) {
if ($arr_info['qty'] != $arr_after[$index]['qty']) {
//insert back the original qty to sku stock
$quantity_o = $arr_info['qty'] * $arr_info['unit_qty'];
$qty_from_o = get_sku_stock_by_date($arr_info['sku'], $delivery_date);
$qty_to_o = $qty_from_o + $quantity_o;
$sql_update_o = "UPDATE sku_stock SET `" . $arr_info['sku'] . "` = '" . $qty_to_o . "' WHERE stock_date = '" . sanitize_text_field($delivery_date) . "' LIMIT 1";
if ($wpdb->query($sql_update_o)) {
write_log($delivery_date, "Edit Line Item", "Back End", $order_id, $arr_info['sku'], $arr_info['description'], $qty_from_o, $qty_to_o, get_current_user_id(), get_client_ip(), $sql_update_o);
}
//deduct the new saved qty from sku stock
$quantity_n = $arr_after[$index]['qty'] * $arr_info['unit_qty'];
$qty_from_n = get_sku_stock_by_date($arr_info['sku'], $delivery_date);
$qty_to_n = $qty_to_o - $quantity_n;
$sql_update_n = "UPDATE sku_stock SET `" . $arr_info['sku'] . "` = '" . $qty_to_n . "' WHERE stock_date = '" . sanitize_text_field($delivery_date) . "' LIMIT 1";
if ($wpdb->query($sql_update_n)) {
write_log($delivery_date, "Edit Line Item", "Back End", $order_id, $arr_info['sku'], $arr_info['description'], $qty_from_n, $qty_to_n, get_current_user_id(), get_client_ip(), $sql_update_n);
}
}
}
}
}
}
// remove add to cart button for variable product if it is nor in selling period
add_action('woocommerce_single_product_summary', 'hide_add_to_cart_button_variable_product', 1, 0);
function hide_add_to_cart_button_variable_product()
{
global $product, $wpdb;
date_default_timezone_set("Asia/Hong_Kong");
$arr_holiday = get_holiday_list();
$min_date = date("Y-m-d");
$current_date = date('Y-m-d');
//$current_date = "2022-04-30";
if ($current_date >= "2022-04-30") {
$custom_calendar_date = get_custom_calendar_date_info($current_date);
$max_date = $custom_calendar_date['maxdate'];
} else {
$current_hour = date("H");
if ($current_hour >= 20) {
$max_date = date('Y-m-d', strtotime("+7 day"));
} else {
$max_date = date('Y-m-d', strtotime("+6 day"));
}
}
if (isset($_GET['date'])) {
if ($_GET['date'] < date('Y-m-d')) {
$stock_date = date('Y-m-d');
$_SESSION['cart_date'] = date('Y-m-d');
} elseif ($_GET['date'] > $max_date) {
$stock_date = date('Y-m-d');
$_SESSION['cart_date'] = date('Y-m-d');
} else {
$stock_date = $_GET['date'];
$_SESSION['cart_date'] = $_GET['date'];
}
} elseif (isset($_SESSION['cart_date'])) {
if ($_SESSION['cart_date'] < date('Y-m-d')) {
$stock_date = date('Y-m-d');
} else {
$stock_date = $_SESSION['cart_date'];
}
} else {
$stock_date = date("Y-m-d");
}
$sku = $product->get_sku();
$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 = '" . $stock_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, $stock_date) == 1) { // within selling period
$earliest_date = get_earliest_available_date($sku);
if (count($result) > 0) {
if (date("Y-m-d") == $stock_date && date("H") >= 16) {
if (get_language() == 'chi') {
$notice = "<p class='status-outofstock'>" . ($earliest_date == false ? '售罄' : '售罄。最早有貨日期: ' . $earliest_date) . "</p>";
} else {
$notice = "<p class='status-outofstock'>" . ($earliest_date == false ? 'Sold out' : 'Sold out. Next Available Date: ' . $earliest_date) . "</p>";
}
} elseif ($limit <= 0) {
if ($end_date == $stock_date) { // check if last date of selling
if (get_language() == 'chi') {
$notice = "<p class='status-outofstock'>" . ($earliest_date == false ? '售罄' : '售罄。最早有貨日期: ' . $earliest_date) . "</p>";
} else {
$notice = "<p class='status-outofstock'>" . ($earliest_date == false ? 'Sold out' : 'Sold out. Next Available Date: ' . $earliest_date) . "</p>";
}
} else {
if (get_language() == 'chi') {
$notice = "<p class='status-outofstock'>" . ($earliest_date == false ? '售罄' : '售罄。最早有貨日期: ' . $earliest_date) . "</p>";
} else {
$notice = "<p class='status-outofstock'>" . ($earliest_date == false ? 'Sold out' : 'Sold out. Next Available Date: ' . $earliest_date) . "</p>";
}
}
} elseif ($limit <= 3) {
if (get_language() == 'chi') {
$notice = "<p class='status-littlestock'>餘" . $limit . "份</p>";
} else {
$notice = "<p class='status-littlestock'>" . $limit . " Left</p>";
}
} else {
if (get_language() == 'chi') {
$notice = "<p class='status-instock'>有貨</p>";
} else {
$notice = "<p class='status-instock'>In Stock</p>";
}
}
}
} elseif (check_stock_init($stock_sku, $stock_date) == 0) {
if (get_language() == 'chi') {
$notice = "<p class='status-ended'>售賣期已完結</p>";
} else {
$notice = "<p class='status-ended'>Sales Ended</p>";
}
} elseif (check_stock_init($stock_sku, $stock_date) == 2) {
if (get_language() == 'chi') {
$notice = "<p class='status-coming'>即將推出</p>";
} else {
$notice = "<p class='status-coming'>Coming Soon</p>";
}
}
$display_date = date('d/m/Y', strtotime($stock_date));
?>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://www.breadsecret.com/custom/jquery-ui-1.12.1.custom/jquery-ui.css">
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">-->
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@500&family=Raleway:wght@100;500&display=swap" rel="stylesheet">
<style>
@media only screen and (max-width: 2000px) {
#calendarloader {
background: rgba(255, 255, 255, 0.9);
display: block;
height: 100%;
position: fixed;
z-index: 9999;
width: 100vw;
margin-left: -50vw;
left: 50%;
top: 14%;
}
#calendarcontent {
width: 600px;
position: relative;
top: 10%;
left: calc(50% - 300px);
padding: 20px;
}
#calendartext {
font-size: 18pt;
text-align: center;
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
font-weight: 500;
}
}
@media only screen and (max-width: 1440px) {
#calendarloader {
background: rgba(255, 255, 255, 0.9);
display: block;
height: 100%;
position: fixed;
z-index: 9999;
width: 100vw;
margin-left: -50vw;
left: 50%;
top: 12%;
}
#calendarcontent {
width: 600px;
position: relative;
top: 10%;
left: calc(50% - 300px);
padding: 20px;
}
#calendartext {
font-size: 18pt;
text-align: center;
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
font-weight: 500;
}
}
@media only screen and (max-width: 1200px) {
#calendarloader {
background: rgba(255, 255, 255, 0.9);
display: block;
height: 100%;
position: fixed;
z-index: 9999;
width: 100vw;
margin-left: -50vw;
left: 50%;
top: 15%;
}
#calendarcontent {
width: 600px;
position: relative;
top: 10%;
left: calc(50% - 300px);
padding: 20px;
}
#calendartext {
font-size: 18pt;
text-align: center;
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
font-weight: 500;
}
}
@media only screen and (max-width: 768px) {
#calendarloader {
background: rgba(255, 255, 255, 0.9);
display: block;
height: 100%;
position: fixed;
z-index: 9999;
width: 100vw;
margin-left: -50vw;
left: 50%;
top: 12%;
}
#calendarcontent {
width: 600px;
position: relative;
top: 10%;
left: calc(50% - 300px);
padding: 20px;
}
#calendartext {
font-size: 18pt;
text-align: center;
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
font-weight: 500;
}
}
@media only screen and (max-width: 480px) {
#calendarloader {
background: rgba(255, 255, 255, 0.9);
display: block;
height: 100%;
position: fixed;
z-index: 9999;
width: 100vw;
margin-left: -50vw;
left: 50%;
top: 12%;
}
#calendarcontent {
width: 600px;
position: relative;
top: 10%;
left: calc(50% - 300px);
padding: 20px;
}
#calendartext {
font-size: 12pt;
text-align: center;
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
font-weight: 500;
}
}
@media only screen and (max-width: 320px) {
#calendarloader {
background: rgba(255, 255, 255, 0.9);
display: block;
height: 100%;
position: fixed;
z-index: 9999;
width: 100vw;
margin-left: -50vw;
left: 50%;
top: 12%;
}
#calendarcontent {
width: 600px;
position: relative;
top: 10%;
left: calc(50% - 300px);
padding: 20px;
}
#calendartext {
font-size: 12pt;
text-align: center;
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
font-weight: 500;
}
}
#pageloader {
background: rgba(255, 255, 255, 0.9);
display: none;
height: 100%;
position: fixed;
z-index: 999999;
width: 100vw;
margin-left: -50vw;
left: 50%;
}
#pageloader img {
position: absolute;
left: 50%;
top: 30%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
z-index: 999999;
}
#pageloader2 {
background: rgba(255, 255, 255, 0.9);
display: none;
height: 100%;
position: fixed;
z-index: 9999;
width: 100vw;
margin-left: -50vw;
left: 50%;
top: 10%;
}
#pageloader2 img {
position: absolute;
left: 50%;
top: 40%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.status-outofstock {
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
padding: 5px 10px;
background-color: #FF5733;
color: #FFF;
}
.status-littlestock {
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
padding: 5px 10px;
background-color: #FFC300;
}
.status-instock {
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
padding: 5px 10px;
background-color: #DAF7A6;
}
.status-ended {
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
padding: 5px 10px;
background-color: #000000;
color: #ffffff;
}
.status-coming {
font-family: 'Raleway', 'Noto Sans TC', sans-serif;
padding: 5px 10px;
background-color: #DDB871;
color: #000;
}
.ui-datepicker {
width: 375px;
height: 425px !important;
z-index: 99 !important;
}
</style>
<div id="pageloader">
<img src="https://www.breadsecret.com/custom/image/loading_400x400px.png" alt="processing..." />
</div>
<div id='calendarloader' style="display:<?php echo isset($_SESSION['cart_date']) ? 'none' : 'block'; ?>">
<div id="calendarcontent">
<div id="pageloader2"><img src="https://www.breadsecret.com/custom/image/loading_400x400px.png" alt="processing..." /></div>
<div id="calendartext" class="body-f2"><?php echo get_language() == 'chi' ? '選擇自取/送貨日期' : 'Select pick-up/delivery date'; ?></div>
<div id="calendar" style="margin-top: 10px;
position: relative;
left: calc(50% - 188px);"> </div>
</div>
</div>
<?php
if (isset($_POST['show']) && $_POST['show'] == 0) {
remove_action('woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20);
} else {
if (get_language() == 'chi') {
echo "自取/送貨日期";
} else {
echo "Pick-up/Delivery Date";
}
echo "<input type='text' id='selected_stock_date' value='" . $display_date . "' style='font-size: 14px; margin-top:10px; margin-bottom:10px' readonly>";
echo "<input type='hidden' id='stock_date_value' value='" . $date . "' readonly>";
echo $notice;
echo "<br><br>";
}
if (check_stock_init($stock_sku, $stock_date) == 0 || check_stock_init($stock_sku, $stock_date) == 2) {
//remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation', 10 );
// Removing add to cart button and quantities only
remove_action('woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://www.breadsecret.com/custom/jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script src="https://www.breadsecret.com/custom/datepicker/js/datepicker-zh-TW.js"></script>
<script type="text/javascript">
var holidays = <?php echo json_encode($arr_holiday); ?>;
function noSundaysOrHolidays(date) {
var day = date.getDay();
var d = ("0" + date.getDate()).slice(-2);
var m = ("0" + (date.getMonth() + 1)).slice(-2);
var y = date.getFullYear();
var dateString = y + '-' + m + '-' + d;
if (dateString == "2022-10-30") {
return [true];
}
//console.log(dateString + "-" + day);
if (day != 0) {
for (i = 0; i < holidays.length; i++) {
if ($.inArray(y + '-' + m + '-' + d, holidays) != -1) {
return [false];
}
}
return [true];
} else {
return [day != 0, ''];
}
}
jQuery(function($) {
$.datepicker.setDefaults($.datepicker.regional["<?php echo get_language() == 'chi' ? 'zh-TW' : ''; ?>"]);
$('#selected_stock_date').datepicker({
beforeShow: function(input, inst) {
setTimeout(function() {
inst.dpDiv.css({
top: $("#selected_stock_date").offset().top + 50,
left: $("#selected_stock_date").offset().left - 20
});
}, 0);
},
beforeShowDay: noSundaysOrHolidays,
dateFormat: "yy-mm-dd",
autoclose: true,
minDate: new Date('<?php echo $min_date; ?>'),
maxDate: new Date('<?php echo $max_date; ?>'),
onSelect: function(dateText, inst) {
var date = $(this).val();
$("#stock_date_value").val(date);
$("#pageloader").show();
window.location.href = "?date=" + $("#stock_date_value").val() + "<?php echo get_language() == 'chi' ? '&lang=zh-hant' : ''; ?>&show=<?php echo $_POST['show']; ?>";
}
});
$("#calendar").datepicker({
beforeShowDay: noSundaysOrHolidays,
dateFormat: "yy-mm-dd",
autoclose: true,
minDate: new Date('<?php echo $min_date; ?>'),
maxDate: new Date('<?php echo $max_date; ?>'),
onSelect: function(dateText, inst) {
var date = $(this).val();
$("#stock_date_value").val(date);
$("#pageloader2").show();
window.location.href = "?date=" + $("#stock_date_value").val() + "<?php echo get_language() == 'chi' ? '&lang=zh-hant' : ''; ?>&show=<?php echo $_POST['show']; ?>";
}
});
});
</script>
<?php
}
//Hidden products showing in search results
add_action('pre_get_posts', 'hidden_search_query_fix');
function hidden_search_query_fix($query = false)
{
if (!is_admin() && isset($query->query['post_type']) && $query->query['post_type'] === 'product') {
$tax_query = $query->get('tax_query');
$tax_query = [
'relation' => 'OR',
[
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
],
[
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => '!=',
],
];
$query->set('tax_query', $tax_query);
}
}
//remove default shipping method
add_filter('pre_option_woocommerce_default_gateway' . '__return_false', 99);
add_filter('woocommerce_shipping_chosen_method', '__return_false', 99);
add_filter('woocommerce_get_catalog_ordering_args', 'bbloomer_first_sort_by_stock_amount', 9999);
function bbloomer_first_sort_by_stock_amount($args)
{
$args['orderby'] = 'meta_value';
$args['order'] = 'ASC';
$args['meta_key'] = '_stock_status';
return $args;
}
// cancel order from back end, resotre stock
add_action('woocommerce_order_status_cancelled', 'change_status_to_cancelled', 21, 1);
function change_status_to_cancelled($order_id)
{
global $wpdb;
$type = "Back End";
$action = "Cancel Order";
$delivery_date = get_post_meta($order_id, 'delivery_date', true);
$order = wc_get_order($order_id);
$adjust_stock = get_post_meta($order_id, 'adjust_stock', true);
$stock_out = get_post_meta($order_id, 'stock_out', true);
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
$sku = $product->get_sku();
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if (has_master_sku($sku)) {
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
} else {
$variation_id = $item->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
} else {
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
$quantity = $item->get_quantity() * $unit_qty;
$qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
$qty_to = $qty_from + $quantity;
if ($adjust_stock == "Y") {
if($stock_out == 1) {
$sql_update = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to . "' WHERE stock_date = '" . sanitize_text_field($delivery_date) . "' LIMIT 1";
if ($wpdb->query($sql_update)) {
write_log($delivery_date, $action, $type, $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
update_post_meta($order_id, 'stock_out','0');
}
}
}
}
}
// fail order from app, resotre stock
add_action( 'woocommerce_order_status_failed', 'change_status_to_failed');
function change_status_to_failed( $order_id ) {
global $wpdb;
$type = "App";
$action = "Fail Order";
$delivery_date = get_post_meta( $order_id, 'delivery_date', true );
$order = wc_get_order($order_id);
$adjust_stock = get_post_meta($order_id, 'adjust_stock', true);
$stock_out = get_post_meta($order_id, 'stock_out', true);
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product();
$sku = $product->get_sku();
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if(has_master_sku($sku)){
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
}else{
$variation_id = $item->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if($variation_id!=0){
$description = get_name_from_variation_id($product->get_name(),$variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
}else{
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
$quantity = $item->get_quantity()*$unit_qty;
$qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
$qty_to = $qty_from + $quantity;
if($adjust_stock=="Y") {
if($stock_out == 1) {
$sql_update = "UPDATE sku_stock SET `".$stock_sku."` = '".$qty_to."' WHERE stock_date = '".sanitize_text_field($delivery_date)."' LIMIT 1";
if($wpdb->query($sql_update)){
write_log($delivery_date, $action, $type, $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
update_post_meta($order_id, 'stock_out','0');
}
}
}
}
}
// adjust stock when order is restored from cancel to pending payment / processing
add_action('woocommerce_order_status_changed', 'restore_stock_from_cancelled_order', 99, 3);
function restore_stock_from_cancelled_order($order_id, $old_status, $new_status)
{
global $wpdb;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (isset($_POST['post_type']) && 'shop_order' == $_POST['post_type']) {
if (!current_user_can('edit_shop_order', $order_id)) {
return;
}
}
if (!is_admin()) {
return;
}
if ($old_status == "cancelled") {
if ($new_status == "pending" || $new_status == "processing") {
$type = "Back End";
$action = "Restore Order";
$delivery_date = get_post_meta($order_id, 'delivery_date', true);
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
$sku = $product->get_sku();
$stock_sku = get_master_sku($sku);
$unit_qty = 1;
if (has_master_sku($sku)) {
$description = $product->get_name();
$unit_qty = get_master_sku_unit_qty($sku);
} else {
$variation_id = $item->get_variation_id();
$product = wc_get_product(wc_get_product_id_by_sku($sku));
if ($variation_id != 0) {
$description = get_name_from_variation_id($product->get_name(), $variation_id);
$unit_qty = get_variation_unit_qty($variation_id);
} else {
$description = $product->get_name(); // make a unique key
$unit_qty = 1;
}
}
$quantity = $item->get_quantity() * $unit_qty;
$qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
$qty_to = $qty_from - $quantity;
$sql_update = "UPDATE sku_stock SET `" . $stock_sku . "` = '" . $qty_to . "' WHERE stock_date = '" . sanitize_text_field($delivery_date) . "' LIMIT 1";
if ($wpdb->query($sql_update)) {
write_log($delivery_date, $action, $type, $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update);
}
}
}
}
}
//20210927-https://stackoverflow.com/questions/46075866/og-image-is-not-working-in-whatsapp-share-in-wordpress
function doctype_opengraph($output)
{
return $output . '
xmlns:og="http://opengraphprotocol.org/schema/"
xmlns:fb="http://www.facebook.com/2008/fbml"';
}
add_filter('language_attributes', 'doctype_opengraph');
function fb_opengraph()
{
global $post;
if (is_single()) {
if (has_post_thumbnail($post->ID)) {
$img_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail');
} else {
$img_src = get_stylesheet_directory_uri() . '/img/opengraph_image.jpg';
}
if ($excerpt = $post->post_excerpt) {
$excerpt = strip_tags($post->post_excerpt);
$excerpt = str_replace("", "'", $excerpt);
} else {
$excerpt = get_bloginfo('description');
}
?>
<meta property="og:title" content="<?php echo the_title(); ?>" />
<meta property="og:description" content="<?php echo $excerpt; ?>" />
<meta property="og:type" content="article" />
<meta property="og:url" content="<?php echo the_permalink(); ?>" />
<meta property="og:site_name" content="<?php echo get_bloginfo(); ?>" />
<meta property="og:image" content="<?php echo $img_src[0]; ?>" />
<?php
} else {
return;
}
}
add_action('wp_head', 'fb_opengraph', 5);
//20220105 payment_terms
function example_custom_order_fields($fields, $order)
{
$new_fields = array();
if (get_post_meta($order->id, 'payment_terms', true)) {
$new_fields['payment_terms'] = array(
'label' => 'Payment Terms',
'value' => get_post_meta($order->id, 'payment_terms', true)
);
}
return array_merge($fields, $new_fields);
}
add_filter('wcdn_order_info_fields', 'example_custom_order_fields', 10, 2);
//20220119 2022 gift box production qty figure
function gift_box_figure_2022_backup()
{
global $wpdb;
$begin_date = "2022-01-24";
$end_date = "2022-01-29";
$arr_result = array(
"TS-PAL-250" => array("2022-01-24" => 0, "2022-01-25" => 0, "2022-01-26" => 0, "2022-01-27" => 0, "2022-01-28" => 0, "2022-01-29" => 0),
"TS-YYP-300" => array("2022-01-24" => 0, "2022-01-25" => 0, "2022-01-26" => 0, "2022-01-27" => 0, "2022-01-28" => 0, "2022-01-29" => 0),
"TS-APM-275" => array("2022-01-24" => 0, "2022-01-25" => 0, "2022-01-26" => 0, "2022-01-27" => 0, "2022-01-28" => 0, "2022-01-29" => 0),
"GB-CNP-325" => array("2022-01-24" => 0, "2022-01-25" => 0, "2022-01-26" => 0, "2022-01-27" => 0, "2022-01-28" => 0, "2022-01-29" => 0),
"GB-CCN-211" => array("2022-01-24" => 0, "2022-01-25" => 0, "2022-01-26" => 0, "2022-01-27" => 0, "2022-01-28" => 0, "2022-01-29" => 0),
"GB-CCC-163" => array("2022-01-24" => 0, "2022-01-25" => 0, "2022-01-26" => 0, "2022-01-27" => 0, "2022-01-28" => 0, "2022-01-29" => 0),
"GB-CCC-286" => array("2022-01-24" => 0, "2022-01-25" => 0, "2022-01-26" => 0, "2022-01-27" => 0, "2022-01-28" => 0, "2022-01-29" => 0)
);
$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed'));
//get all orders
$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value >= '" . $begin_date . "' AND order_detail.meta_value <= '" . $end_date . "' ");
foreach ($result as $order_obj) {
//get order object from order id
$order = wc_get_order($order_obj->ID);
$delivery_date = $order->get_meta('delivery_date', true);
foreach ($order->get_items() as $item) { //print each order line item
$prod = $item->get_product();
$sku = $prod->get_sku();
$qty = $item->get_quantity();
if (array_key_exists($sku, $arr_result)) {
$arr_result[$sku][$delivery_date] += $qty;
}
}
}
return $arr_result;
}
//20220119 2022 gift box production qty figure
function gift_box_figure_2022($arr_sku, $begin_date, $end_date)
{
global $wpdb;
$arr_date = array();
for ($i = strtotime($begin_date); $i <= strtotime($end_date); $i += 86400) {
$arr_date[date("Y-m-d", $i)] = 0;
}
$arr_result = array();
foreach ($arr_sku as $skus) {
$arr_result[$skus] = $arr_date;
}
$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed'));
//get all orders
$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value >= '" . $begin_date . "' AND order_detail.meta_value <= '" . $end_date . "' ");
foreach ($result as $order_obj) {
//get order object from order id
$order = wc_get_order($order_obj->ID);
$delivery_date = $order->get_meta('delivery_date', true);
foreach ($order->get_items() as $item) { //print each order line item
$prod = $item->get_product();
$sku = $prod->get_sku();
$qty = $item->get_quantity();
if (array_key_exists($sku, $arr_result)) {
$arr_result[$sku][$delivery_date] += $qty;
}
}
}
return $arr_result;
}
//20230106 2023 gift box production qty figure
function gift_box_figure_2023($arr_sku, $begin_date, $end_date)
{
global $wpdb;
$arr_date = array();
for ($i = strtotime($begin_date); $i <= strtotime($end_date); $i += 86400) {
$arr_date[date("Y-m-d", $i)] = array("group"=>0, "individual"=>0);
}
$arr_result = array();
foreach ($arr_sku as $skus) {
$arr_result[$skus] = $arr_date;
}
$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed'));
//get all orders
$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value >= '" . $begin_date . "' AND order_detail.meta_value <= '" . $end_date . "' ");
foreach ($result as $order_obj) {
//get order object from order id
$order = wc_get_order($order_obj->ID);
$order_type = is_wholesaler_order($order_obj->ID)?"group":"individual";
$delivery_date = $order->get_meta('delivery_date', true);
foreach ($order->get_items() as $item) { //print each order line item
$prod = $item->get_product();
$sku = $prod->get_sku();
$qty = $item->get_quantity();
if (array_key_exists($sku, $arr_result)) {
$arr_result[$sku][$delivery_date][$order_type] += $qty;
}
}
}
return $arr_result;
}
//20220127-KEI
/**
* Hide shipping rates when free shipping is available, but keep "Local pickup"
* Updated to support WooCommerce 2.6 Shipping Zones
*/
function hide_shipping_when_free_is_available($rates, $package)
{
//print_r($_SESSION);
$new_rates = array();
foreach ($rates as $rate_id => $rate) {
// Only modify rates if free_shipping is present.
if ('free_shipping' === $rate->method_id) {
$new_rates[$rate_id] = $rate;
break;
}
}
if (!empty($new_rates)) {
//Save local pickup if it's present.
foreach ($rates as $rate_id => $rate) {
if ('flat_rate' === $rate->method_id) {
$new_rates[$rate_id] = $rate;
break;
}
}
return $new_rates;
}
return $rates;
}
//add billing address 1
function add_billing_address_1($fields)
{
$fields['billing_address_1'] = array(
'label' => __('Field for Product ' . $product_id, 'woocommerce'),
'placeholder' => _x('Field for Product ' . $product_id, 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
//}
return $fields;
}
//set default state 'PICKUP / COLLECT'
function bbloomer_change_default_checkout_state()
{
return 'HK31'; // state code
}
//set default state 'HK32' => 'DELIVERY'
function bbloomer_change_default_checkout_stateB()
{
return 'HK32'; // state code
}
//set default state address 1
function bbloomer_change_default_checkout_address_1a()
{
return 'Pickup / Collect'; //
}
function bbloomer_set_checkout_field_input_value_default($fields)
{
$fields['billing']['billing_address_1']['default'] = 'Address';
return $fields;
}
function my_woocommerce_billing_fields($fields)
{
$fields['billing_address_1']['custom_attributes'] = array('readonly' => 'readonly');
return $fields;
}
function billing_company_checkout_field($fields)
{
$billing_company = WC()->customer->get_billing_company();
if (empty($billing_company)) { // Remove field
unset($fields['billing']['billing_state']);
} else { // Make readonly
$fields['billing']['billing_state']['custom_attributes']['readonly'] = 'readonly';
}
return $fields;
}
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'checkoutcollect') !== false) {
add_filter('default_checkout_billing_state', 'bbloomer_change_default_checkout_state');
add_action('wp_footer', 'custom_hide_country_field');
add_filter('check_billing_company_checkout_field', 'check_billing_company_checkout_field');
add_filter('woocommerce_cart_needs_shipping_address', '__return_false');
add_filter('default_checkout_billing_address_1', 'bbloomer_change_default_checkout_address_1a');
} elseif (strpos($url, 'checkoutdelivery') !== false) {
add_filter('default_checkout_billing_state', 'bbloomer_change_default_checkout_stateB');
add_filter('default_checkout_shipping_state', 'bbloomer_change_default_checkout_stateB');
//add_filter('woocommerce_cart_needs_shipping_address', '__return_true');
//add_filter( 'woocommerce_billing_fields', 'add_billing_address_1',80 );
}
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'checkoutdelivery') !== false) {
add_action('woocommerce_review_order_before_payment', 'ts_checkout_before_customer_details01b', 10);
}
//
function ts_checkout_before_customer_details01b()
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
echo '<h6>送貨詳情:</br></br>送貨時間:14:00 - 19:00。</br>
不送離島,機場、禁區、偏遠地區、車輛未能直達的地點(如大部份村屋)、沒有至少15分鐘免費泊車的屋苑、及沒有升降機直達的大廈等(如唐樓)。</br></br> 如您的送貨地址屬以上地區,落單前請聯絡我們。</br></h6>';
} else {
echo '<h6>Delivery details:</br></br>Delivery time: 14:00 - 19:00.</br></br>
No delivery to outlying islands, airport, restricted areas, remote areas, locations that cannot be reached directly by cars (such as most village houses), housing estates that do not have at least 15 minutes of free parking, and buildings that do not have direct elevator access (such as tenement houses).</br> </br>If it happens that your delivery address is within these area, please contact us before ordering.</br></h6>';
}
}
//add delivery date selection to checkout form
add_action('woocommerce_before_checkout_billing_form', 'custom_checkout_field');
function custom_checkout_field($checkout)
{
date_default_timezone_set("Asia/Hong_Kong");
$arr_holiday = get_holiday_list();
if (get_language() == "chi") {
$arr_option = array("" => "選擇");
} else {
$arr_option = array("" => "Select");
}
//if(get_current_user_id()==1){
$hour = date('H');
$current_date = date('Y-m-d');
//$current_date = "2022-05-03";
$now = strtotime($current_date);
if ($current_date >= "2022-04-30") {
$custom_calendar_date = get_custom_calendar_date_info($current_date);
if ($hour >= 16) { // after 18:00, today is not available for selection
$now += 86400;
$period = $custom_calendar_date['period'] - 1;
} else {
$period = $custom_calendar_date['period'];
}
//echo $period;
} else {
$period = 7;
if ($hour >= 20) {
$now += 86400;
} elseif ($hour >= 16) { // after 18:00, today is not available for selection
$now += 86400;
$period = 6;
}
}
$period_in_second = $period * 86400;
for ($i = $now; $i < $now + $period_in_second; $i = $i + 86400) {
//if(date('N',$i)==7){ // if sunday, skip list
if (date('N', $i) == 7 && date('Y-m-d', $i) != "2022-10-30") { // if sunday, skip list
continue;
}
if (in_array(date('Y-m-d', $i), $arr_holiday)) { // if hoiday, skip list
continue;
}
$avail = true;
$arr_sku_qty_sum = array();
foreach (WC()->cart->get_cart() as $cart_item) {
$product = wc_get_product($cart_item['product_id']);
$sku = $product->get_sku(); //get sku#
$stock_sku = get_master_sku($sku); //get master sku if present
$unit_qty = 1;
if (has_master_sku($sku)) {
$unit_qty = get_master_sku_unit_qty($sku); //get master sku unit qty
} else {
//check variation for old product
$variation_id = $cart_item['variation_id'];
if ($variation_id != 0) {
$unit_qty = get_variation_unit_qty($variation_id); //get variation unit qty
} else {
$unit_qty = 1;
}
}
$count = $cart_item['quantity'] * $unit_qty;
if (array_key_exists($stock_sku, $arr_sku_qty_sum)) { //product id already exist in summary array, then add ordered qty to its corresonding array value
$arr_sku_qty_sum[$stock_sku]['qty'] += $count;
} else {
$arr_sku_qty_sum[$stock_sku]['qty'] = $count; //insert new product id to summary array
}
//if($count>get_sku_stock_by_date($stock_sku,date('Y-m-d', $i))) // check stock qty
//$avail = false;
}
//print_r($arr_sku_qty_sum);
foreach ($arr_sku_qty_sum as $sku_name => $value) {
if ($value['qty'] > get_sku_stock_by_date($sku_name, date('Y-m-d', $i))) { // check stock qty
$avail = false;
}
}
if (!$avail) { // if no stock, skip list
continue;
}
if (get_language() == "chi") {
$display_date = date('d/m/Y', $i) . " (" . get_chinese_weekday(date('Y-m-d', $i)) . ")";
} else {
$display_date = date('d/m/Y (l)', $i);
}
//$arr_option[date('Y-m-d', $i)] = date('jS M Y (l)', $i);
$arr_option[date('Y-m-d', $i)] = $display_date;
}
if (count($arr_option) == 1) { //if no date available, contact cs
$arr_option = array("x" => "Please contact our cs for help (WhatsApp: +852 5612 5381)");
}
///edit add delivery date selection to checkout form
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'checkoutcollect') !== false) {
woocommerce_form_field(
'delivery_date',
array(
'type' => 'select',
'class' => array('wps-drop'),
'label' => get_language() == "chi" ? __('訂單取貨日期') : __('Order Pick-up / Collect Date'),
'label_class' => array('b50442'),
'required' => true,
'default' => $_SESSION['cart_date'],
'options' => $arr_option,
'custom_attributes' => array('readonly' => $readonly),
),
$checkout->get_value('delivery_date')
);
} elseif (strpos($url, 'checkoutdelivery') !== false) {
woocommerce_form_field(
'delivery_date',
array(
'type' => 'select',
'class' => array('wps-drop'),
'label' => get_language() == "chi" ? __('訂單送貨日期') : __('Order Delivery Date'),
'label_class' => array('b50442'),
'required' => true,
'default' => $_SESSION['cart_date'],
'options' => $arr_option,
'custom_attributes' => array('readonly' => $readonly),
),
$checkout->get_value('delivery_date')
);
}
?>
<script type="text/javascript">
jQuery(function($) {
$('#delivery_date').change(function(evt) {
var dataString = 'section=set_session_variable&field=cart_date&value=' + $(this).val();
$.ajax({
type: "POST",
url: "https://www.breadsecret.com/ajax_data.php",
data: dataString,
cache: false,
success: function(data) {
location.reload();
}
});
//}
});
});
</script>
<?php
}
// redirect shop page to store page
// added on 24/2/2022 by Samiel
function custom_shop_page_redirect()
{
if (is_shop()) {
wp_redirect(home_url('/store/'));
exit();
}
}
add_action('template_redirect', 'custom_shop_page_redirect');
// show check out notice
// added on 28/2/2022 by Samiel
function custom_checkout_notice()
{
if (get_language() == 'chi') {
echo "<p class='b50442'>*訂單一經確認並接納,不允許更改、取消或退款。</p>";
} else {
echo "<p class='b50442'>*No changes, cancellation or refund is allowed once order is confirmed and acccepted.</p>";
}
}
add_action('woocommerce_review_order_before_submit', 'custom_checkout_notice', 10, 0);
//change the wording of the password hint.
add_filter('password_hint', 'smarter_password_hint');
function smarter_password_hint($hint)
{
$hint = '<h3>Password must be at least 6 characters long, consists of letters and numbers.</h3>';
return $hint;
}
// added by samiel on 11/4/2022
// for displaying delivery date on cart page
add_action('woocommerce_before_cart_table', 'custom_display_delivery_date_in_cart');
function custom_display_delivery_date_in_cart()
{
//echo '<div class="woocommerce-info">';
if (get_language() == "chi") {
echo "<p class='b50442'><strong>送貨/取貨日期: " . date('d/m/Y', strtotime($_SESSION['cart_date'])) . " (" . get_chinese_weekday($_SESSION['cart_date']) . ")</p></strong>";
} else {
echo "<p class='b50442'><strong>Delivery/Pick-up Date: " . date('d/m/Y (l)', strtotime($_SESSION['cart_date'])) . "</p></strong>";
}
//echo '</div>';
}
//20220725 Kei My Account Page add column
add_filter('woocommerce_account_orders_columns', 'add_account_orders_column', 10, 1);
function add_account_orders_column($columns)
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
$columns['custom-column'] = __('送貨日期', 'woocommerce');
} else {
$columns['custom-column'] = __('Delivery Date', 'woocommerce');
}
return $columns;
}
//My Account Page add data in column
add_action('woocommerce_my_account_my_orders_column_custom-column', 'add_account_orders_column_rows');
function add_account_orders_column_rows($order)
{
// Example with a custom field
if ($value = $order->get_meta('delivery_date')) {
// echo esc_html( $value );
echo date("d/m/Y", strtotime("$value"));
}
}
//My Account Page add column
add_filter('woocommerce_account_orders_columns', 'add_account_orders_column1', 10, 1);
function add_account_orders_column1($columns)
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
$columns['order-date'] = __('落單日期', 'woocommerce');
} else {
$columns['order-date'] = __('Order Date', 'woocommerce');
}
return $columns;
}
//My Account Page column sort by
add_filter('woocommerce_account_orders_columns', 'add_custom_account_orders_column', 10, 1);
function add_custom_account_orders_column($columns)
{
$ordered_columns = array();
// Inserting a new column in a specific location
$ordered_columns['order-number'] = $columns['order-number'];
$ordered_columns['order-date'] = $columns['order-date'];
$ordered_columns['custom-column'] = $columns['custom-column'];
$ordered_columns['order-status'] = $columns['order-status'];
$ordered_columns['order-total'] = $columns['order-total'];
$ordered_columns['order-actions'] = $columns['order-actions'];
return $ordered_columns;
}
//Add Fields Inside “Order Details” Table
add_action('woocommerce_order_details_after_order_table_items', 'misha_order_details');
function misha_order_details($order)
{
// $delivery_date = get_post_meta( $order->get_id(), 'delivery_date', true );
// if( $shippingdate ) :
if ($value = $order->get_meta('delivery_date')) {
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
?>
<tr>
<th scope="row">送貨日期:</th>
<td><?php echo date('d/m/Y', strtotime($value)) ?></td>
</tr>
<?php
} else {
?>
<tr>
<th scope="row">Delivery Date:</th>
<td><?php echo date('d/m/Y', strtotime($value)) ?></td>
</tr>
<?php
}
}
}
// remove warning "WebSocket connection to 'wss://public-api.wordpress.com/pinghub/wpcom/me/newest-note-data' failed:"
add_action('admin_init', 'rm34_jetpack_deactivate_modules');
function rm34_jetpack_deactivate_modules()
{
if (class_exists('Jetpack') && Jetpack::is_module_active('notes')) {
Jetpack::deactivate_module('notes');
}
}
//Cart page Button
remove_action('woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20);
add_action('woocommerce_proceed_to_checkout', 'change_url_to_checkout', 20);
function change_url_to_checkout()
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
//default show delivery 1
$show = true;
//get cart date
$date = $_SESSION['cart_date'];
//define start and end date
$startDate = "2022-10-24";
$endDate = "2022-10-30";
//define k11 product
$arr_k11_product = array("BD-NNS-330", "BD-FPB-155");
if ($date == $endDate) {
$show = false;
} elseif ($date >= $startDate && $date < $endDate) { // 2022-10-24 - 2022-10-29
foreach (WC()->cart->get_cart() as $cart_item) {
$product = wc_get_product($cart_item['product_id']);
$sku = $product->get_sku(); //get cart item sku#
if (in_array($sku, $arr_k11_product)) {
$show = false; // if match k11 product, don't show
}
}
}
if (strpos($url, 'zh-hant') !== false) {
echo ' <div class="pickup1"></div>
<hr>
<h6 style="font-family: \' Raleway\';margin-bottom: 0px;">
自取 / 交收</h6>
<ul>
<li style="font-family: \' Raleway\';margin-top: 10px; font-size: 12px;">火炭烘培室, 金鐘、 火炭、九龍塘港鐵站, 駿景園商場。 <a href="https://www.breadsecret.com/%E9%80%81%E8%B2%A8/?lang=zh-hant" target="_blank"><b><u>點擊查看時間和詳情。</b></u></a></li>
<li style="font-family: \' Raleway\';margin-top: 10px; font-size: 12px; color:#b50442">請準時。送貨員會在交收時間後離開前往下一個送貨點。因食物安全理由,未取的訂單不會被退回給bread secret,因此訂單將被視為放棄,恕不能再被安排送貨及不獲退款。</li>
</ul>
<a href="https://www.breadsecret.com/checkoutcollect/?lang=zh-hant"><button id="pickupa" style=" margin-top: 0px;" >自取 / 交收</button></a>
<hr>
</div>';
if ($show) {
echo ' <div class="delivery1"></div>
<hr>
<h6 style="font-family: \' Raleway\';margin-bottom: 0px;">
送貨</h6>
<ul>
<li style="font-family: \' Raleway\';margin-top: 10px; font-size: 12px;">不送離島、機場、禁區、偏遠地區、車輛未能直達的地點、沒有至少15分鐘免費泊車的屋苑及沒有升降機直達的大廈等。<a href="https://www.breadsecret.com/%E9%80%81%E8%B2%A8/?lang=zh-hant" target="_blank"><b><u>點擊查看時間和詳情。</b></u></a></li>
</ul>
<a href="https://www.breadsecret.com/checkoutdelivery/?lang=zh-hant"><button id="deliverya" style=" margin-top: 0px;" >送貨</button></a>
<hr>
</div>';
}
} else {
echo '<div class="pickup1"></div>
<hr>
<h6 style="font-family: \' Raleway\';margin-bottom: 0px;">
Pick Up / Collect
</h6>
<ul>
<li style="font-family: \' Raleway\';margin-top: 10px; font-size: 12px;">Fo Tan Bakery, Admiralty, Fo Tan, or Kowloon Tong MTR station, Royal Ascot shopping centre. <a href="https://www.breadsecret.com/delivery-2/" target="_blank"><b><u>Click here for time and detail.</u></b></a></li>
<li style="font-family: \' Raleway\';margin-top: 10px; font-size: 12px; color:#b50442">Please be punctual. Delivery man will leave for the next delivery after the meeting time. For food safety reason, uncollected orders will NOT be returned to bread secret and thus be considered to be abandoned, no further delivery arrangement and refund will be accepted.</li>
</ul>
<a href="https://www.breadsecret.com/checkoutcollect"><button id="pickupa" style=" margin-top: 0px;" >Pick Up / Collect</button></a>
<hr>
</div>';
if ($show) {
echo ' <div class="delivery1"></div>
<hr>
<h6 style="font-family: \' Raleway\';margin-bottom: 0px;">
Delivery
</h6>
<ul>
<li style="font-family: \' Raleway\';margin-top: 10px; font-size: 12px;">No delivery to outlying islands, airport, restricted areas, remote areas, locations that cannot be reached directly by cars or do not have at least 15 minutes of free parking, and buildings that do not have direct elevator access. <a href="https://www.breadsecret.com/delivery-2/" target="_blank"><b><u>Click here for time and detail.</b></u></a></li>
</ul>
<a href="https://www.breadsecret.com/checkoutdelivery"><button id="deliverya" style=" margin-top: 0px;" >Delivery</button></a>
<hr>
</div>';
}
}
}
//shipping name rename
add_filter('woocommerce_shipping_package_name', 'custom_shipping_package_name01a');
function custom_shipping_package_name01a($name)
{
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url, 'zh-hant') !== false) {
return '運費';
} else {
return 'Shipping Fee';
}
}
//Contact Form 7 Use Really Simple CAPTCHA
add_filter('wpcf7_use_really_simple_captcha', '__return_true');
// Check if address field contains house number otherwise provide error message
//20880829-kei-lee check address1 when shipping method is flat_rate
add_action('woocommerce_checkout_process', 'custom_checkout_field_check');
function custom_checkout_field_check($method)
{
// Check if set, if its not set add an error.
$billing_address_1 = $_POST['billing_address_1'];
echo $chosen_shipping_method_id = WC()->session->get('chosen_shipping_methods')[0];
echo $chosen_shipping_method = explode(':', $chosen_shipping_method_id)[0];
if (strpos($billing_address_1, 'Pickup ') !== false && $chosen_shipping_method == 'flat_rate') {
// if ( $_POST['billing_address_1'] && strpbrk($_POST['billing_address_1'], '1234567890') !== FALSE )
wc_add_notice(__('Please fill in a valid address for delivery'), 'error');
}
}
function getSavedValueFromIPL($date, $product_id)
{
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM inventory_preparation_list WHERE product_id = '" . $product_id . "' AND delivery_date = '" . $date . "' LIMIT 1 ");
if (count($result) > 0) {
return $result[0]->confirmed_production_qty;
} else {
return 0;
}
}
//hide shipping method
add_filter('woocommerce_package_rates', 'hide_shipping_method_based_on_time', 10, 2);
function hide_shipping_method_based_on_time($rates, $package)
{
$array_unset = array(
'local_pickup:424',
'local_pickup:425',
'local_pickup:426',
'local_pickup:427',
'local_pickup:428'
);
$date = $_SESSION['cart_date'];
$startDate = "2022-10-24";
$endDate = "2022-10-30";
$arr_k11_product = array("BD-NNS-330", "BD-FPB-155");
$show1 = true;
if ($date == $endDate) {
$show1 = false;
} elseif ($date >= $startDate && $date < $endDate) { // 2022-10-24 - 2022-10-29
foreach (WC()->cart->get_cart() as $cart_item) {
$product = wc_get_product($cart_item['product_id']);
$sku = $product->get_sku(); //get cart item sku#
if (in_array($sku, $arr_k11_product)) {
$show1 = false; // if match k11 product, don't show
}
}
}
if ($show1) {
return $rates;
} else {
foreach ($array_unset as $shipping_rate_id) {
// When this shipping method is available and after 11 AM
if (array_key_exists($shipping_rate_id, $rates)) {
unset($rates[$shipping_rate_id]); // remove it
}
}
return $rates;
}
}
function getProductCostComponent($skuID, $qty) {
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM stock_init WHERE id = '".$skuID."' Order By start_date DESC, sku ASC ");
$row = $result[0];
$productResult = $wpdb->get_results("SELECT * FROM inventory_product WHERE sku_id = '".$row->id."' LIMIT 1"); // check if recipe (cost) is set
// hardcode for this sku (its sku is renamed previously)
if($row->sku=="BD-WNL-460"){
$row->sku = "BD-WNT-460";
}
$woo_product_id = wc_get_product_id_by_sku($row->sku); // get woocommerce product id
$woo_product = wc_get_product($woo_product_id); // get woocommerce product object
//$calculation_qty = $row->unit_qty; // qty in one unit
if(count($productResult)>0) {
$customProductID = $productResult[0]->id; // recipe (finished-product) id
$production_qty = $productResult[0]->production_qty; // production qty from recipe
$qty_factor = $qty / $production_qty;
// init cost type
$ingredient_cost = 0;
$packaging_cost = 0;
$indirect_cost = 0;
$total = 0;
if($productResult[0]->total_cost==0){ // 如果recipe有野未set好, default所有野做0
$ingredient_cost = 0;
$packaging_cost = 0;
$indirect_cost = 0;
} else {
$productCostLine = $wpdb->get_results("SELECT * FROM inventory_product_detail WHERE product_id = '".$customProductID."' ");
foreach($productCostLine as $item) {
if($item->component_type_id==1){
//$ingredient_cost += $item->ttl_cost;
}elseif($item->component_type_id==2) { // semi-finished product
//loop all item in sfproduct and get data array
/*
$itemCostData = getRecursiveItemCost($item->reference_id, $item->qty);
$ingredient_cost += $itemCostData['ingredient_cost'];
$packaging_cost += $itemCostData['packaging_cost'];
$indirect_cost += $itemCostData['indirect_cost'];
*/
/*
echo "<pre style='background-color:#ccc'>";
print_r($itemCostData);
echo "</pre>";
*/
//$data['ingredient_cost'] += $item->material_cost*$qty_factor;
$ingredient_cost += $item->ttl_cost*$qty_factor;
//$data['indirect_cost'] += $item->wage_cost*$qty_factor;
//$data['indirect_cost'] += $item->misc_cost*$qty_factor;
//$data['indirect_cost'] += $item->machine_cost*$qty_factor;
} elseif($item->component_type_id==3) { // ingredient
$ingredient_cost += $item->material_cost;
$indirect_cost += $item->wage_cost;
$indirect_cost += $item->misc_cost;
$indirect_cost += $item->machine_cost;
} elseif($item->component_type_id==4) { // packaging
$packaging_cost += $item->material_cost;
$indirect_cost += $item->wage_cost;
$indirect_cost += $item->misc_cost;
$indirect_cost += $item->machine_cost;
} elseif($item->component_type_id==5) { // process
$ingredient_cost += $item->material_cost;
$indirect_cost += $item->wage_cost;
$indirect_cost += $item->misc_cost;
$indirect_cost += $item->machine_cost;
}
}
/*
$ingredient_cost_with_wastage = $ingredient_cost * (1 + $iWastage);
$packaging_cost_with_wastage = $packaging_cost * (1 + $pWastage);
$indirect_cost_with_wastage = $indirect_cost * (1 + $tWastage);
$unit_ingredient_cost_with_wastage = $ingredient_cost_with_wastage / $production_qty * $calculation_qty;
$unit_packaging_cost_with_wastage = $packaging_cost_with_wastage / $production_qty * $calculation_qty;
$unit_indirect_cost_with_wastage = $indirect_cost_with_wastage / $production_qty * $calculation_qty;
$unit_direct_cost_with_wastage = $unit_ingredient_cost_with_wastage + $unit_packaging_cost_with_wastage;
$unit_total_cost = $unit_ingredient_cost_with_wastage + $unit_packaging_cost_with_wastage + $unit_indirect_cost_with_wastage;
*/
}
} else { // 如果未set recipe, default所有野做0
$ingredient_cost = 0;
$packaging_cost = 0;
$indirect_cost = 0;
}
$total_cost = $ingredient_cost + $packaging_cost + $indirect_cost;
return array('ingredient_cost'=>$ingredient_cost, 'packaging_cost'=>$packaging_cost, 'indirect_cost'=>$indirect_cost, 'total_cost'=>$total_cost);
}
function prevent_email_domain( $user_login, $user_email, $errors ) {
global $wpdb;
$ip = get_client_ip();
$result = $wpdb->get_results("SELECT * FROM `custom_keyword_blacklist`");
foreach ( $result as $idx=>$keywordObj) {
//$errors->add( 'bad_email_domain', '<strong>錯誤</strong>: '.$keywordObj->name);
if($keywordObj->type=="U"){
if ( stripos( $user_login, $keywordObj->name ) !== false ) {
$lang = get_bloginfo('language');
if($lang=="zh-TW") {
$errors->add( 'bad_email_domain', '<strong>錯誤</strong>: 此字段已被阻止註冊用戶帳戶');
} else {
$errors->add( 'bad_email_domain', '<strong>ERROR</strong>: This word phrase is blocked from registering user account');
}
$wpdb->insert('custom_blocked_registration', array(
'regName' => $user_login,
'regEmail' => $user_email,
'ipAddress' => $ip,
'blockReason' => 'blocked by word phrase '.$keywordObj->name
));
}
}
if($keywordObj->type=="D"){
if ( strpos( $user_email, $keywordObj->name ) !== false ) {
$lang = get_bloginfo('language');
if($lang=="zh-TW") {
$errors->add( 'bad_email_domain', '<strong>錯誤</strong>: 此網域已被阻止註冊用戶帳戶');
} else {
$errors->add( 'bad_email_domain', '<strong>ERROR</strong>: This domain is blocked from registering user account');
}
$wpdb->insert('custom_blocked_registration', array(
'regName' => $user_login,
'regEmail' => $user_email,
'ipAddress' => $ip,
'blockReason' => 'blocked by email domain '.$keywordObj->name
));
}
}
}
//$errors->add( 'bad_email_domain', '<strong>ERROR</strong>: This email domain is not allowed.'.$user_login.$user_email);
}
add_action( 'register_post', 'prevent_email_domain', 10, 3 );
//get domain blacklist
function get_domain_blacklist(){
global $wpdb;
$domain_blacklist = array();
$result = $wpdb->get_results("SELECT id, name FROM `custom_keyword_blacklist` WHERE type = 'D' ORDER BY id");
foreach ($result as $idx => $domain) {
$domain_blacklist[$domain->id] = $domain->name;
}
return $domain_blacklist;
}
//get wordphrase blacklist
function get_phrase_blacklist(){
global $wpdb;
$phrase_blacklist = array();
$result = $wpdb->get_results("SELECT id, name FROM `custom_keyword_blacklist` WHERE type = 'U' ORDER BY id");
foreach ($result as $idx => $phrase) {
$phrase_blacklist[$phrase->id] = $phrase->name;
}
return $phrase_blacklist;
}
//get order status index for app
function get_order_status_index($order_id) {
global $wpdb;
date_default_timezone_set("Asia/Hong_Kong");
// Getting an instance of the order object
$order = wc_get_order($order_id);
$delivery_date = $order->get_meta('delivery_date', true);
$pack_status = $order->get_meta('packed', true);
$system_status = $order->get_status();
if($system_status=="cancelled") {
return -2;
} elseif($system_status=="failed"){
return -1;
} elseif($system_status=="pending"){
return 0;
} elseif($system_status=="processing"){
if($pack_status==1){
return 3; // shipping / delivering
} else {
if(date("Y-m-d") >= $delivery_date ){
return 2; // preparing
} else {
return 1; // order received
}
}
} elseif($system_status=="completed"){
return 4;
} else {
return -3;
}
}