}
$received = date('Y-m-d H:i:s');
$tx_time = date('Y-m-d H:i:s', $request['txtime']);
$payone_txid = $request['txid'];
$txaction = isset($request['txaction']) ? $request['txaction'] : 'UNKNOWN';
$log_id = $class_plog->add("R", $received, $txaction, $request);
$rule1 = $request['portalid'] == PAYONE_PORTAL_ID || $request['portalid'] == PAYONE_PORTAL_ID_NO_EMAIL || $request['portalid'] == PAYONE_PORTAL_ID_JULIEGRACE;
$rule2 = $request['key'] == md5(PAYONE_PORTAL_KEY);
$response = "";
$status = "";
if ($rule1 && $rule2) {
    if (strtoupper($request['mode']) != 'LIVE') {
        $response = "TSOK";
    } else {
        $class_payone = new payone();
        $payi = new payone_invoice('payone_txid', $payone_txid);
        $response = "TSOK";
        $set_order_as_paid = false;
        switch ($txaction) {
            case 'appointed':
                $payi->confirmAppointed();
                break;
            case 'capture':
                $payi->confirmCaptured();
                if ($request['balance'] <= 0) {
                    if ($request['balance'] == 0) {
                        if ($payi->detail['invoice_complete_status'] == 'F') {
                            //set as refund processed for refund
                            $status = 'D';
                        } elseif ($payi->detail['invoice_complete_status'] == 'A') {
                            //if user not paid yet then returned all products, set as invoice cancelled
     }
 }
 if (count($items) > 0) {
     $order = $class_jo->retrieveDetail($order_id);
     $display_counter = date('d. M', strtotime($order['order_date'])) . ' - No. ' . sprintf("%003s", $order['daily_count']);
     $shipping_name = $order['customer_shipping_firstname'] . ' ' . $order['customer_shipping_lastname'];
     $shipping_address = $order['customer_shipping_address'];
     $cod_value = 0;
     switch ($order['jng_sp_id']) {
         case '1':
             //NM.DE
             $reference = $order['shipment_id'];
             break;
         case '2':
             //OT.DE
             $invoice = new payone_invoice();
             $invoice->createFromOrderSP($order, $items);
             if ($order['shipment_id'] != $invoice->detail['invoice_no']) {
                 $sda_jo = array('shipment_id' => $invoice->detail['invoice_no']);
                 tep_db_perform('jng_sp_orders', $sda_jo, 'update', "jng_sp_orders_id={$order['jng_sp_orders_id']}");
                 $order['shipment_id'] = $invoice->detail['invoice_no'];
             }
             $reference = $order['shipment_id'];
             $cod_value = $order['payment_method'] == 'CASH_ON_DELIVERY' ? number_format($invoice->detail['invoice_amount'], 2, ',', '') : 0;
             break;
     }
     if ($order['customer_shipping_address2'] != '') {
         $shipping_address .= ' ' . $order['customer_shipping_address2'];
     }
     $cols = array();
     $cols[] = $package['jng_sp_packages_id'];
if (isset($_POST['me_action'])) {
    if ($_POST['me_action'] == 'LOADUNSUBMITTEDORDERS') {
        $orders = $class_payone->newSPorders($jng_sp_id);
        $result = $class_payone->drawListTable($orders);
    } elseif ($_POST['me_action'] == 'AUTHORIZATION') {
        $process_method = 'authorization';
        $order_id = tep_db_prepare_input($_POST['orders_id']);
        $order = $class_jo->retrieveDetail($order_id);
        $items = $class_jo->retrieveItems($order_id);
        $cust = $class_jcust->retrieveDetail(null, $order['jng_sp_id'], $order['customer_billing_id']);
        foreach ($items as $key => $i) {
            if ($class_jo->statusIsCancelled($i['status'])) {
                unset($items[$key]);
            }
        }
        $payi = new payone_invoice();
        $payi->createFromOrderSP($order, $items);
        if (count($order) == 0 || count($items) == 0 || $payi->detail['invoice_complete_status'] != '0') {
            $result = "{$order_id},1";
        } else {
            //--PREPARE PARAMETERS
            $request = array();
            //--STANDARD PARAMETERS
            $request['mid'] = PAYONE_MERCHANT_ID;
            $request['portalid'] = PAYONE_PORTAL_ID;
            $request['key'] = md5(PAYONE_PORTAL_KEY);
            $request['mode'] = PAYONE_MODE;
            $request['request'] = $process_method;
            $request['encoding'] = 'UTF-8';
            //--ORDER INFO
            $request['aid'] = PAYONE_SUBACCOUNT_ID_OTTODE;
Example #4
0
         if (file_exists(SP_NECKERMANN_INVOICE_PATH . $pcl_filename)) {
             $oi_content .= '<h3>Download Invoice: <a href="print/print-file.php?type=pclnmde&amp;fn=' . $pcl_filename . '" target="_blank" title="Click to download PCL file">' . $pcl_filename . '</a></h3>';
         } else {
             $pcl_filename .= $class_jo->nmdeOrdersPCLignoreSuffix;
             if (file_exists(SP_NECKERMANN_INVOICE_PATH . $pcl_filename)) {
                 $oi_content .= '<h3 class="red">Orders canceled partially, updated invoice will be sent directly by NM.DE</h3>';
                 $oi_content .= '<h3 class="notice">Download Original Invoice: <a href="print/print-file.php?type=pclnmde&amp;fn=' . $pcl_filename . '" target="_blank" title="Click to download PCL file">' . $pcl_filename . '</a></h3>';
             } else {
                 $oi_content .= '<h3 class="red">Invoice not yet received</h3>';
             }
         }
     } else {
         $oi_content .= '<h3 class="red">Order from before we started using PCL for NM.DE</h3>';
     }
 } elseif ($order['jng_sp_id'] == '2') {
     $invoice = new payone_invoice();
     $invoice->retrieveDetail('S', $order_id);
     if (count($invoice->detail) == 0) {
         $oi_content = '<h2>Payone Invoice<h2>';
         $oi_content .= '<h3 class="red">No Payone Invoice created for this order yet</h3>';
     } else {
         $invoice->getReceipts();
         $invoice->getReminders();
         $amount_refund = $invoice->detail['invoice_amount_overpayment'] + $invoice->detail['invoice_amount_overpayment_canceled'];
         $amount_fines = $invoice->detail['invoice_amount_fines'] - $invoice->detail['invoice_amount_fines_canceled'];
         if ($worst_status <= 8) {
             $content .= '<p style="color:gray;">Download Invoice button will be available after products are sent to customer</p>';
         } elseif (statusIsCancelled($worst_status)) {
             $content .= '<p style="color:gray;">No Invoice for canceled order</p>';
         } else {
             $content .= '<span><a href="print/delivery-document.php?id=' . $order_id . '" target="_blank"></a><input type="button" id="dlinvoice" value="Download Invoice" title="Click here to Download Invoice"/></span><br /><br />';
Example #5
0
    $orders_array = explode(',', $orders);
} else {
    exit;
}
$order_counter = 0;
foreach ($orders_array as $order_id) {
    $pdf->AddPage();
    $order = $class_o->retrieveDetail($order_id, true);
    $items = $class_o->retrieveProducts($order_id, true);
    foreach ($items as $key => $item) {
        if ($class_o->productStatusIsCancelled($item['status'])) {
            unset($items[$key]);
        }
    }
    $print_delivery_note = false;
    $class_pi = new payone_invoice();
    //        echo "<pre>";var_dump($items);die();
    if (strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_BANK_TRANSFER)) {
        //Vorkasse
        $class_pi->createFromOrderJNG($order, $items, '+1 month');
    } elseif (strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_DIRECT_DEBIT)) {
        //Bankeinzug
        $class_pi->createFromOrderJNG($order, $items, '+0 days');
    } elseif (strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_INVOICE)) {
        //Rechnung
        $class_pi->createFromOrderJNG($order, $items);
    } else {
        //Paypal invoice
        $class_pi->createFromOrderJNG($order, $items, '+0 days', '2');
    }
    $invoice_id = tep_db_insert_id();
<?php

global $db;
require_once '../confy.php';
require_once '../functions.php';
require_once '../functions-2.php';
tep_db_connect();
use_class('payone_invoice');
$res = tep_db_query("SELECT invoice_id FROM payone_invoice");
while ($row = tep_db_fetch_array($res)) {
    $payi = new payone_invoice("invoice_id", $row['invoice_id']);
    $query = "UPDATE payone_invoice SET payone_saldo = " . $payi->getBalance() . " WHERE invoice_id = " . $row['invoice_id'];
    echo $query . " ";
    var_dump(tep_db_query($query));
    echo "<br/>";
}
use_class('payone_logger');
$class_paylog = new payone_logger();
if (isset($_POST['me_action']) && $_POST['me_action'] != '') {
    if ($_POST['me_action'] == 'CANCELQUEUEDREFUND') {
        use_class('payone');
        $class_payone = new payone();
        $pkey_id = tep_db_prepare_input($_POST['pkeyid']);
        $status = str_replace('C', '', tep_db_prepare_input($_POST['type']));
        $class_payone->updateReturnStatus($pkey_id, $status);
        echo utf8_encode($pkey_id);
        exit;
    } elseif ($_POST['me_action'] == 'UPDATEINVOICE') {
        use_class('payone_invoice');
        $invoice_id = tep_db_prepare_input($_POST['invid']);
        $payi = new payone_invoice('invoice_id', $invoice_id);
        $field = tep_db_prepare_input($_POST['fld']);
        $value = tep_db_prepare_input($_POST['val']);
        if ($field == 'invoice_complete_status') {
            $value = trim(strtoupper($value));
        }
        $payi->updateField($field, $value);
        echo utf8_encode($field);
        exit;
    }
}
//DETAIL VIEW
if (isset($_GET['id']) && $_GET['id'] != '') {
    $id = tep_db_prepare_input($_GET['id']);
    $content = $class_paylog->retrieveDetail($id);
    $title = 'Payone Log Detail ' . $id;
Example #8
0
 /**
  * Get Payment Summary
  * @param String $invoice_complete_status
  * @param String $filter
  * @return Array (payment_method => saldo)
  */
 public static function getPaymentSummaryData($invoice_complete_status, $filter = '', $order_by = 'invoice_date ASC')
 {
     use_class('payone_invoice');
     $q = "SELECT " . "pi.invoice_date, pi.invoice_due_date, pi.payone_txid" . ", pi.invoice_order_type, pi.invoice_order_id" . "," . payone_invoice::calcBalance(null, true) . " AS amount_saldo" . ", IF(pi.invoice_order_type = 'S', jo.payment_method, o.payment_method ) AS payment_method" . ", IF(pi.invoice_order_type = 'S', jo.order_id, o.orders_no ) AS order_no" . ", IF(pi.invoice_order_type = 'S', CONCAT(jo.customer_billing_firstname, ' ', jo.customer_billing_lastname), o.customers_name ) AS customers_name";
     $q .= " FROM payone_invoice pi";
     $q .= " LEFT JOIN jng_sp_orders jo " . "ON jo.jng_sp_orders_id = pi.invoice_order_id AND pi.invoice_order_type = 'S'";
     $q .= " LEFT JOIN orders o " . "ON o.orders_id = pi.invoice_order_id AND pi.invoice_order_type = 'J'";
     $q .= " WHERE pi.invoice_complete_status = '{$invoice_complete_status}'";
     if ($filter != '') {
         $q .= " AND {$filter}";
     }
     $q .= " ORDER BY {$order_by}";
     $r = tep_db_query($q);
     $result = array();
     while ($row = tep_db_fetch_array($r)) {
         $result[] = $row;
     }
     return $result;
 }
var_dump($test);
echo "\n";
var_dump($test2);
exit;
global $db;
require_once '../confy.php';
require_once '../functions.php';
require_once '../functions-2.php';
require_once DIR_WS_FUNCTIONS . 'html_output.php';
tep_db_connect();
use_class('jng_sp');
use_class('jng_sp_orders');
use_class('payone_invoice');
$class_sp = new jng_sp();
$class_jo = new jng_sp_orders();
$class_pi = new payone_invoice();
$items_id_returned = array('28801', '28806');
foreach ($items_id_returned as $items_id) {
    $o_oi = $class_jo->retrieveItemDetail($items_id);
    $o_ri_arr = $class_jo->retrieveReturnItem($items_id);
    $o_ri = $o_ri_arr[0];
    $class_pi->retrieveDetail("S", $o_oi['jng_sp_orders_id']);
    //ONLY QUEING JUST FOR TRANSACTION THAT HAVE payone_txid (FIRST GET FROM SUBMITTING INVOICE)
    if ($class_pi->detail['payone_txid'] != '') {
        $data_por = array();
        $data_por['return_id'] = $o_ri['return_id'];
        $data_por['invoice_id'] = $o_oi['jng_sp_orders_id'];
        $data_por['jng_sp_orders_items_id'] = $items_id;
        $data_por['id'] = $o_oi['article_number'];
        $data_por['pr'] = intval($o_oi['price'] * 100);
        $data_por['no'] = $o_ri['return_quantity'];
 private function queryOrdersItemsDetailSP($orders_items_id)
 {
     $return_status = in_array($this->filters_status, array('16', '17', '18'));
     $query = "SELECT CONCAT(jo.customer_billing_firstname,' ',jo.customer_billing_lastname) AS customer_name" . ", jo.cod_costs, jo.order_id, jo.order_date, jo.service_code, jo.customers_order_count" . ", jo.payment_method, jo.payment_status, joi.*, do.depot_orders_id" . ", do.status AS depot_orders_status, do.prod_status AS depot_orders_prod_status" . ", MAX(joih.status_date) AS status_date, MAX(psh.status_date) AS status_date_prod" . ", jcust.jng_sp_customers_id, jscs.list_type, sp.jng_sp_id, sp.package_prefix" . ", p.products_image, p.products_brand_id, p.material_expenses AS current_mat_exp" . ", ptc.categories_id, pi.invoice_complete_status" . ", " . payone_invoice::calcBalance('', true) . " AS invoice_current_balance" . ", pi.invoice_amount_paid, pi.is_captured, MAX(ope.last_sent_date) AS last_sent_date" . ", MAX(ope.sent_count) AS sent_count, pl.sold_monthly_1" . ", IFNULL(joi.leadtime_start_date, jo.order_date) AS date_for_sorting";
     if ($return_status) {
         $query .= ", MIN(joir.return_time) AS return_time, SUM(joir.return_quantity) AS return_quantity";
     }
     $query .= " FROM jng_sp_orders jo";
     $query .= " LEFT JOIN jng_sp sp ON sp.jng_sp_id = jo.jng_sp_id";
     $query .= " LEFT JOIN jng_sp_customers jcust " . " ON jcust.jng_sp_id = jo.jng_sp_id AND jcust.customer_id = jo.customer_billing_id";
     $query .= " LEFT JOIN jng_sp_customers_special jscs " . " ON jscs.jng_sp_customers_id = jcust.jng_sp_customers_id";
     $query .= " LEFT JOIN jng_sp_orders_items joi ON joi.jng_sp_orders_id = jo.jng_sp_orders_id";
     $query .= " LEFT JOIN depot_orders do " . " ON do.trans_type = 'SP' AND do.trans_id = joi.jng_sp_orders_items_id";
     $query .= " LEFT JOIN jng_sp_orders_items_status_history joih " . " ON joih.jng_sp_orders_items_id = joi.jng_sp_orders_items_id AND joih.status = joi.status";
     $query .= " LEFT JOIN production_status_history psh " . " ON psh.type = 'SP' AND psh.orders_items_id = joi.jng_sp_orders_items_id " . " AND psh.status = joi.prod_status";
     $query .= " LEFT JOIN products_log pl ON pl.products_id = joi.products_id";
     $query .= " LEFT JOIN products p ON p.products_id = joi.products_id";
     $query .= " LEFT JOIN products_to_categories ptc ON ptc.products_id = joi.products_id";
     $query .= " LEFT JOIN orders_products_email ope " . " ON ope.orders_products_id = joi.jng_sp_orders_items_id AND ope.type = 'S'";
     //retrieve MAX(ope.sent_count)
     $query .= " LEFT JOIN payone_invoice pi " . " ON pi.invoice_order_type = 'S' AND pi.invoice_order_id = jo.jng_sp_orders_id";
     if ($return_status) {
         $query .= " LEFT JOIN jng_sp_orders_items_return joir " . " ON joir.jng_sp_orders_items_id = joi.jng_sp_orders_items_id";
     }
     $query .= " WHERE joi.status = '{$this->filters_status}' AND joi.jng_sp_orders_items_id = '{$orders_items_id}'";
     if ($this->filters_order_type > 0) {
         $query .= " AND jo.jng_sp_id = {$this->filters_order_type} ";
     }
     $query .= $this->eanListFilterQuery('joi', $this->filters_list_ean, 'AND', '');
     $query .= $this->leadtimeFilterQuery($this->filters_status, 'joi.leadtime_start_date', 'jo.order_date', $this->filters_leadtime_date_start, $this->filters_leadtime_date_end, 'AND', '');
     $query .= $this->ordersNoFilterQuery('jo.order_id', $this->filters_list_orders_no, 'AND', '');
     if ($this->filters_brand_id > 0) {
         $query .= " AND p.products_brand_id = '{$this->filters_brand_id}' ";
     }
     if ($this->filters_cat_id > 0) {
         $query .= " AND ptc.categories_id = '{$this->filters_cat_id}' ";
     }
     if ($this->filters_sub_status != '') {
         if ($this->filters_status == '1') {
             //This will handle for tab Unpaid Prepayment, so far nothing todo
         } else {
             $query .= " AND joi.prod_status LIKE '{$this->filters_sub_status}%'";
         }
     }
     $query .= " AND " . Order::getOldOrderFunctionSP()->filterQueryForShippingWindow();
     $query .= " GROUP BY joi.jng_sp_orders_items_id";
     return $query;
 }
                //$result .= "<br />";
            }
            $class_plog->add('S', $process_time, $process_method, $request, $response);
        }
    }
} else {
    $logger->write("NO INVOICES READY TO BE SENT TO PAYONE");
}
//TODO: Send notification direclty per order after sending to payone
$logger->write("SENDING MAIL PREPAYMENT INFO");
if (count($success) > 0) {
    foreach ($success as $sp => $dts) {
        foreach ($dts as $dt) {
            $order_type = $sp == 'sp' ? Order::ORDER_TYPE_SALES_PARTNER : Order::ORDER_TYPE_JULIE_GRACE;
            list($invoice_id, $order_id) = explode('|', $dt);
            $inv = new payone_invoice('invoice_id', $invoice_id);
            $unpaid_amount = $inv->getBalance();
            $order = new Order($order_type, $order_id);
            if ($order->sendPrepaymentInformation($unpaid_amount)) {
                $mail_send_status = 'sent';
            } else {
                $mail_send_status = 'sent failed';
            }
            $logger->write($l_order_type . 'O' . $order_id . " {$mail_send_status}");
        }
    }
} else {
    $logger->write("no orders ready");
}
$msg = "TOTAL INVOICES JG CREATED: " . $pi_create_counter['jg'];
echo "{$msg} \n";
Example #12
0
 function recalcVouchersAndShippingCost($orders_id, $recalculate_payone_invoice = true)
 {
     $order = $this->retrieveDetail($orders_id);
     //LOAD CONFIG KEY
     $gv_config_query = tep_db_query("SELECT configuration_key, configuration_value FROM configuration WHERE configuration_key IN ('MODULE_ORDER_TOTAL_GV_SORT_ORDER', 'MODULE_ORDER_TOTAL_GV_INC_SHIPPING', 'MODULE_ORDER_TOTAL_COUPON_SORT_ORDER', 'MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING', 'MODULE_ORDER_TOTAL_SHIPPING_FREE_SHIPPING_OVER', 'MODULE_SHIPPING_MZMT_GEOZONE_1_TABLE_1')");
     $gv_config = array();
     while ($row = tep_db_fetch_array($gv_config_query)) {
         $gv_config[$row['configuration_key']] = $row['configuration_value'];
     }
     $owa = $this->getOrderWeightAndAmount($orders_id);
     $order_weight = $owa['order_weight'];
     $order_amount = $owa['order_amount'];
     //RECALC SHIPPING COST
     $ot_shipping_update = false;
     if ($order_weight > 0) {
         $ot_shipping_update = true;
         if ($order_amount > $gv_config['MODULE_ORDER_TOTAL_SHIPPING_FREE_SHIPPING_OVER']) {
             $shipping_amount = 0;
         } else {
             list($key, $shipping_amount) = explode(':', $gv_config['MODULE_SHIPPING_MZMT_GEOZONE_1_TABLE_1']);
         }
     } elseif ($order_weight == 0) {
         $shipping_amount = 0;
         $ot_shipping_update = true;
     }
     if ($ot_shipping_update) {
         $sql_data_array = array();
         $sql_data_array['text'] = displayCurrency('EUR', $shipping_amount);
         $sql_data_array['value'] = $shipping_amount;
         tep_db_perform('orders_total', $sql_data_array, 'update', "orders_id={$orders_id} AND class='ot_shipping'");
     }
     //GET OT(orders_total) DATA
     $ot = $this->retrieveTotals($orders_id);
     $total_amount = $ot['ot_subtotal']['value'];
     $total_amount += $shipping_amount;
     //var_dump($total_amount);die();
     $is_free_shipping = false;
     //GET USED COUPONS
     $dbq = tep_db_query("SELECT * FROM coupon_redeem_track WHERE order_id = {$orders_id}");
     while ($r = tep_db_fetch_array($dbq)) {
         $coupon_id = $r['coupon_id'];
         $gv_query = tep_db_query("SELECT * FROM coupons WHERE coupon_id = '{$coupon_id}' ORDER BY coupon_expire_date DESC LIMIT 1");
         if (tep_db_num_rows($gv_query) > 0) {
             $coupon = tep_db_fetch_array($gv_query);
             $gv_amount = $coupon['coupon_amount'];
             $ot_shipping_update = false;
             if ($coupon['free_shipping'] == '1') {
                 $is_free_shipping = true;
                 if (isset($ot['ot_shipping']) && isset($ot['ot_shipping']['value']) && $ot['ot_shipping']['value'] != '0') {
                     $ot_shipping_update = true;
                     $ot['ot_total']['value'] = $ot['ot_total']['value'] - $ot['ot_shipping']['value'];
                     $ot['ot_shipping']['value'] = 0;
                     $ot['ot_shipping']['text'] = number_format(0, 2, ',', '.') . ' ' . $order['currency'];
                 }
             }
             if ($coupon['coupon_type'] == 'C') {
                 $coupon_name = 'Gutschein';
                 $coupon_class = 'ot_coupon';
                 $coupon_sort = $gv_config['MODULE_ORDER_TOTAL_COUPON_SORT_ORDER'];
                 $subtotal_amt = $ot['ot_subtotal']['value'];
                 $shipping_amt = $ot['ot_shipping']['value'];
                 if ($gv_config['MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING'] == 'true') {
                     $price_to_discount = $subtotal_amt + $shipping_amt;
                 } else {
                     $price_to_discount = $subtotal_amt;
                 }
                 if (isset($ot['ot_bp']) && isset($ot['ot_bp']['value'])) {
                     $price_to_discount -= $ot['ot_bp']['value'];
                 }
                 if ($gv_amount > 0 && $gv_amount <= 1) {
                     $gv_amount = $gv_amount * $price_to_discount;
                 }
                 if ($gv_config['MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING'] == 'true') {
                     $new_total = $total_amount - $gv_amount;
                     if ($new_total < 0) {
                         $new_total = 0;
                     }
                 } else {
                     $exclude_shipping = $total_amount - $shipping_amt;
                     $new_total = $exclude_shipping - $gv_amount;
                     if ($new_total < 0) {
                         $new_total = 0;
                     }
                     $new_total += $shipping_amt;
                 }
             } else {
                 $coupon_name = 'Gutscheine';
                 $coupon_class = 'ot_gv';
                 $coupon_sort = $gv_config['MODULE_ORDER_TOTAL_GV_SORT_ORDER'];
                 $total = $ot['ot_total'];
                 if ($gv_config['MODULE_ORDER_TOTAL_GV_INC_SHIPPING'] == 'true') {
                     $new_total = $total['value'] - $gv_amount;
                     if ($new_total < 0) {
                         $new_total = 0;
                     }
                 } else {
                     $shipping = $ot['ot_shipping'];
                     $exclude_shipping = $total['value'] - $shipping['value'];
                     $new_total = $exclude_shipping - $gv_amount;
                     if ($new_total < 0) {
                         $new_total = 0;
                     }
                     $new_total += $shipping['value'];
                 }
             }
             $sql_data_array = array();
             $sql_data_array['orders_id'] = $orders_id;
             $sql_data_array['title'] = $coupon_name . ':';
             $sql_data_array['text'] = '<b>' . number_format($gv_amount, 2, ',', '.') . ' ' . $order['currency'] . '</b>';
             $sql_data_array['value'] = $gv_amount;
             $sql_data_array['class'] = $coupon_class;
             $sql_data_array['sort_order'] = $coupon_sort;
             tep_db_perform('orders_total', $sql_data_array, 'update', "orders_id={$orders_id} AND class='{$coupon_class}'");
             if ($ot_shipping_update) {
                 $sql_data_array = array();
                 $sql_data_array['text'] = $ot['ot_shipping']['text'];
                 $sql_data_array['value'] = $ot['ot_shipping']['value'];
                 tep_db_perform('orders_total', $sql_data_array, 'update', "orders_id={$orders_id} AND class='ot_shipping'");
             }
         }
         $sql_data_array = array();
         $sql_data_array['text'] = '<b>' . number_format($new_total, 2, ',', '.') . ' ' . $order['currency'] . '</b>';
         $sql_data_array['value'] = $new_total;
         tep_db_perform('orders_total', $sql_data_array, 'update', "orders_id={$orders_id} AND class='ot_total'");
     }
     if ($recalculate_payone_invoice) {
         use_class('payone_invoice');
         $payi = new payone_invoice('invoice_order_id', $orders_id, "invoice_order_type = 'J'");
         $payi->recalculate();
     }
     return $new_total;
 }
 $return_pkey_id = array();
 $joid_arr = array();
 $rid_arr = array();
 $id_arr = array();
 $pr_arr = array();
 $no_arr = array();
 $de_arr = array();
 $va_arr = array();
 $amount_return_arr = array();
 $amount_return_total = 0;
 $request = array();
 foreach ($data as $data_return) {
     $joi_id = $data_return['jng_sp_orders_items_id'];
     $amount_return = round($data_return['amount']);
     $invoice_id = $data_return['invoice_id'];
     $class_pi = new payone_invoice("invoice_id", $invoice_id);
     $portal_id = $class_pi->detail['portal_id'];
     $is_sp = $class_pi->detail['invoice_order_type'] == 'S' ? true : false;
     if (count($class_pi->detail) > 0) {
         $nextsequencenumber = intval($class_pi->detail['sequencenumber']) + 1;
         $amount = round($class_pi->detail['invoice_amount'] * 100);
         $amount_paid = round($class_pi->detail['invoice_amount_paid'] * 100);
         $amount_cancel = round($class_pi->detail['invoice_amount_cancel'] * 100);
         $amount_overpayment = round($class_pi->detail['invoice_amount_overpayment'] * 100);
     }
     $return_hist['type'] = $process_method;
     $return_pkey_id[] = $data_return['pkey_id'];
     $return_hist['return_id'] = $data_return['return_id'];
     $return_hist['invoice_id'] = $invoice_id;
     $return_hist['invoice_no'] = $data_return['invoice_no'];
     $return_hist['jng_sp_orders_items_id'] = $data_return['jng_sp_orders_items_id'];
    if ($cek['duration'] > 7) {
        $status = '1';
        $class_payi->updateCompleteStatus($status);
        $arr_success[] = $invoice_id;
    }
}
echo "Total 'expired' with status 'P' (Paid) : {$counter} \n";
if (count($arr_success) > 0) {
    echo count($arr_success) . " invoice(s) successfully update to '1 = Payone Complete' invoice_id's (" . implode(",", $arr_success) . ") \n";
}
$q = "SELECT invoice_id FROM payone_invoice WHERE invoice_complete_status = 'D' ORDER BY invoice_id";
$dbq = tep_db_query($q);
$counter = 0;
$arr_success = array();
$arr_failed = array();
while ($r = tep_db_fetch_array($dbq)) {
    $counter++;
    $invoice_id = $r['invoice_id'];
    $class_payi = new payone_invoice('invoice_id', $r['invoice_id']);
    $cek = $class_payone->getUpdateStatusDate($invoice_id, 'D');
    //CLEAN AFTER 2 WEEKS
    if ($cek['duration'] > 14) {
        $status = '1';
        $class_payi->updateCompleteStatus($status);
        $arr_success[] = $invoice_id;
    }
}
echo "Total 'expired' with status 'D' (Refund Processed) : {$counter} \n";
if (count($arr_success) > 0) {
    echo count($arr_success) . " invoice(s) successfully update to '1 = Payone Complete' invoice_id's (" . implode(",", $arr_success) . ") \n";
}
        $result['btnid'] = $btnid;
        ajaxReturn($result);
        exit;
    } elseif ($_POST['me_action'] == 'CHECKCURRENTBALANCE') {
        $current_balance = 0;
        $info_balance = '';
        $id = $_POST['id'];
        $dbq = tep_db_query("SELECT * FROM payone_invoice WHERE payone_txid = '{$id}' OR invoice_id = '{$id}'");
        if (tep_db_num_rows($dbq) > 0) {
            $info_balance = '<div align="center"><table border="0" cellpadding="0" cellspacing="0" style="background-color:#fff;width:300px;">';
            $info_balance .= '<th>Invoice ID</th><th>Payone txid</th><th>Current Balance</th>';
            while ($r = tep_db_fetch_array($dbq)) {
                $cur_balance = 0;
                $invoice_id = $r['invoice_id'];
                $txid = $r['payone_txid'];
                $payi = new payone_invoice('invoice_id', $invoice_id);
                $cur_balance = $payi->getBalance();
                $info_balance .= '<tr><td align="center">' . $invoice_id . '</td><td align="center">' . $txid . '</td><td align="center">' . $cur_balance . ' EUR</td></tr>';
            }
            $info_balance .= '</table></div>';
        }
        $result = array();
        $result['info-balance'] = $info_balance;
        ajaxReturn($result);
        exit;
    }
}
$sort = isset($_GET['sort']) && $_GET['sort'] != '' ? tep_db_prepare_input($_GET['sort']) : 'asc';
if (isset($_POST['paging_page_clicked'])) {
    if (isset($_SESSION['vars']['paging_page_clicked'])) {
        $paging_page_clicked = $_SESSION['vars']['paging_page_clicked'];
Example #16
0
/////////////////////////////////////////
// SET BACK UNANSWERED FEEDBACK AS NEW //
/////////////////////////////////////////
$q = tep_db_query("UPDATE minierp_users_has_notifications SET status=0 WHERE need_feedback=1 AND status=1");
$logger->write("Task 4ab - End");
$logger->write("Task 5 (RECALCULATE PAYONE INVOICE) - Start");
///////////////////////////////////////////////////
// CLEAR PAYONE INVOICE FOR FULL CANCELED ORDERS //
///////////////////////////////////////////////////
use_class('payone_invoice');
$date_tolerance = date('Y-m-d', strtotime('-3 days'));
//$q = tep_db_query("SELECT invoice_id FROM `payone_invoice` WHERE  invoice_date<'$date_tolerance' AND (invoice_complete_status='0' OR (is_captured IN (0, 2) AND invoice_complete_status NOT IN (2, 3)))");
//Recalculate only for invoice which is new (not yet sent to payone)
$q = tep_db_query("SELECT invoice_id FROM `payone_invoice` WHERE invoice_date < '{$date_tolerance}' AND invoice_complete_status = '0'");
while ($row = tep_db_fetch_array($q)) {
    $invoice = new payone_invoice('invoice_id', $row['invoice_id']);
    $invoice->recalculate();
}
$logger->write("Task 5 - End");
$logger->write("Task 6 (DOOM TO KILL CHECKER) - Start");
if (SERVER_IS_LOCAL) {
    $logger->write("Skipped! Not to be run in  Manobo Local");
} else {
    use_class('styles');
    use_class('products_minierp');
    use_class('products_articles');
    $class_s = new styles();
    $class_pm = new products_minierp();
    $class_pa = new products_articles();
    $style_id = 680;
    //COLLECTION: DOOMED TO BE KILLED
 $content .= '<input type="button" id="dl-inv-dn" value="Download Invoice" title="' . $sop_mouse_over['invoice_download'] . '" />';
 $content .= '</div>';
 $content .= '</div>';
 //$content .= $discount_info;
 //Payment - RIGHT COLUMN
 $content .= '<div id="payment-rightcol" style="margin-left:500px;width:450px;">';
 //Payone Details
 $content .= '<div class="box ui-corner-all">';
 $content .= '<h3 class="red" style="margin:0;">Payone Details</h3>';
 $content .= '<div style="padding-top:5px;">';
 $is_handled_by_payone = $order_object->isPaymentHandledByPayone();
 use_class('payone');
 use_class('payone_invoice');
 $class_payone = new payone();
 $invoice_order_type = substr($source, 0, 1);
 $invoice = new payone_invoice('invoice_order_type', $invoice_order_type, 'invoice_order_id=' . $order_id);
 if (isset($invoice->detail['invoice_id']) && $invoice->detail['invoice_id'] != '') {
     $month = date('n');
     $yearnow = date('Y');
     $yearbefore = $yearnow - 1;
     $pmilink = 'https://pmi.pay1.de/merchants/txmanager.popup.php?navi=&ebene=1&operation=1&b_id=&u_id=&sort_col=&sort_order=&e_operation=0&userid=';
     $pmilink .= '&plusminus%5B1%5D=%5Bweitere_Filterbedingung%5D&list_pos=0&search_kat%5B1%5D=buchungsid';
     $pmilink .= '&field%5B1%5D=' . $invoice->detail['payone_txid'];
     $pmilink .= '&startday=1&startmonth=' . $month . '&startyear=' . $yearbefore;
     $pmilink .= '&endday=' . date('j') . '&endmonth=' . $month . '&endyear=' . $yearnow;
     $pmilink .= '&selectedRadioMode=live';
     //$txid = ($invoice->detail['payone_txid']=='') ? '<span class="red">Not connected yet</span>' : '<a href="'.$pmilink.'" class="view_webpage" title="'.$sop_mouse_over['payone_link'].'">'.$invoice->detail['payone_txid'].'</a>';
     $txid = $invoice->detail['payone_txid'] == '' ? '<span class="red">Not connected yet</span>' : payoneWebLink($invoice->detail['payone_txid'], $sop_mouse_over['payone_link']);
     $content .= '<div><table border="0" cellpadding="0" cellspacing="0">';
     $content .= '<tr><td style="width:120px;">Payone TXID</td><td>:</td><td style="width:122px;">' . $txid . '</td></tr>';
     $content .= '<tr><td>Manobo Invoice ID</td><td>:</td><td>' . $invoice->detail['invoice_id'] . '</td></tr>';
    while ($row = tep_db_fetch_array($res)) {
        $sets_of_invoice[] = $row;
    }
}
//echo "<pre>";var_dump($sets_of_invoice);
$counter = array();
$counter_preauth_captured = 0;
$counter_capture_no_txid = 0;
if (count($sets_of_invoice) > 0) {
    $success = array();
    $failed = array();
    foreach ($sets_of_invoice as $invoice) {
        $is_sp = false;
        $counter_preauth_captured++;
        $arr_joid = explode(",", $invoice['invoice_order_items_id']);
        $inv = new payone_invoice('invoice_id', $invoice['invoice_id']);
        $invoice_id = $inv->detail['invoice_id'];
        $txid = $inv->detail['payone_txid'];
        $order_id = $inv->detail['invoice_order_id'];
        $nextsequencenumber = intval($inv->detail['sequencenumber']) + 1;
        $invoice_amount = round($inv->detail['invoice_amount'] * 100);
        $amount_disc = 0;
        if ($invoice['invoice_order_type'] == 'S') {
            $is_sp = true;
            $sp_jg = 'sp';
        } else {
            $sp_jg = 'jg';
        }
        $counter[$sp_jg]++;
        if ($is_sp) {
            $order = $class_jo->retrieveDetail($order_id);
    $orders_array = explode(',', $orders);
} else {
    exit;
}
$order_counter = 0;
foreach ($orders_array as $order_id) {
    $pdf->AddPage();
    $order = $class_o->retrieveDetail($order_id, true);
    $items = $class_o->retrieveProducts($order_id, true);
    foreach ($items as $key => $item) {
        if ($class_o->productStatusIsCancelled($item['status'])) {
            unset($items[$key]);
        }
    }
    $print_delivery_note = false;
    $invoice = new payone_invoice();
    //echo "<pre>";var_dump($items);die();
    if (strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_BANK_TRANSFER)) {
        //Vorkasse
        $invoice->createFromOrderJNG($order, $items, '+1 month');
    } elseif (strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_DIRECT_DEBIT)) {
        //Bankeinzug
        $invoice->createFromOrderJNG($order, $items, '+0 days');
    } elseif (strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_INVOICE)) {
        //Rechnung
        $invoice->createFromOrderJNG($order, $items);
    } else {
        //Paypal invoice
        $invoice->createFromOrderJNG($order, $items, '+0 days', '2');
    }
    $invoice_id = tep_db_insert_id();
use_class('payone/financegateConnect');
use_class('jng_sp');
use_class('jng_sp_orders');
use_class('orders');
use_class('jng_sp_customers');
use_class('payone');
use_class('payone_invoice');
use_class('payone_logger');
use_class('minierp_customers');
$class_sp = new jng_sp();
$class_jo = new jng_sp_orders();
$class_o = new orders();
$class_jcust = new jng_sp_customers();
$class_cust = new minierp_customers();
$class_payone = new payone();
$payi = new payone_invoice();
$pi_gift_create = array();
$cut_off_orders_id = 20363;
$pi_gift_counter = 0;
$process_method = 'authorization';
$sets_of_invoice = $class_payone->retrieveList("invoice_complete_status = 'R' AND invoice_id = 139163");
//$sets_of_invoice =  $class_payone->retrieveList("invoice_id = 48");
//echo "<pre>";var_dump($sets_of_invoice);die();
$counter = 0;
if (count($sets_of_invoice) > 0) {
    $success = array();
    $failed = array();
    foreach ($sets_of_invoice as $invoice) {
        $counter++;
        $order_id = $invoice['invoice_order_id'];
        $arr_joid = explode(",", $invoice['invoice_order_items_id']);
Example #21
0
     $sql_data_array['value'] = $gv_amount;
     $sql_data_array['class'] = $coupon_class;
     $sql_data_array['sort_order'] = $coupon_sort;
     tep_db_perform('orders_total', $sql_data_array);
     if ($ot_shipping_update) {
         $sql_data_array = array();
         $sql_data_array['text'] = $ot['ot_shipping']['text'];
         $sql_data_array['value'] = $ot['ot_shipping']['value'];
         tep_db_perform('orders_total', $sql_data_array, 'update', "orders_id={$order_id} AND class='ot_shipping'");
     }
     $sql_data_array = array();
     $sql_data_array['text'] = '<b>' . number_format($new_total, 2, ',', '.') . ' ' . $order['currency'] . '</b>';
     $sql_data_array['value'] = $new_total;
     tep_db_perform('orders_total', $sql_data_array, 'update', "orders_id={$order_id} AND class='ot_total'");
     use_class('payone_invoice');
     $payi = new payone_invoice('invoice_order_id', $order_id, "invoice_order_type = 'J'");
     $payi->recalculate();
     //SEND NOTIFICATION: "NEW ORDER CONFIRMATION" (order update)
     $to_name = $order['customers_name'];
     $to_email_address = $order['customers_email_address'];
     $order_products_query = tep_db_query("SELECT * FROM orders_products WHERE orders_id={$order_id}");
     $oplist = array();
     while ($row = tep_db_fetch_array($order_products_query)) {
         $oplist[] = $row;
     }
     include DIR_WS_EMAILS . $languages[2]['path'] . '/orders-updated.php';
     $from_email_name = FROM_EMAIL_NAME;
     $from_email_address = FROM_EMAIL_ADDRESS;
     $sent = tep_mail($to_name, $to_email_address, $email_subject, $email_text, $from_email_name, $from_email_address);
 } else {
     $messagebox->add('ERROR found when redeeming code <strong>"' . $gv_no . '"</strong>, please recheck the voucher code.');
    }
    //TODO: new method using new email template
    //or maybe it is not needed after using new email template
    //(already inform open amount)
}
//QUERY ORDERS
$query = "SELECT '" . Order::ORDER_TYPE_JULIE_GRACE . "' AS order_type" . ", o.customers_name, o.customers_email_address" . ", o.orders_id, o.orders_no, o.currency, o.date_purchased AS order_date" . ", op.status, ope.status AS last_status" . ", MAX(ope.last_sent_date) AS last_sent_date" . ", MAX(ope.sent_count) AS sent_count" . " FROM orders o" . " INNER JOIN orders_products op ON op.orders_id = o.orders_id" . " LEFT JOIN orders_products_email ope" . " ON ope.orders_products_id = op.orders_products_id AND ope.type = 'J'" . " WHERE o.payment_method LIKE '" . PAYMENT_METHOD_BANK_TRANSFER . "'" . " AND o.paid_status = 0 AND op.status = 1" . " GROUP BY o.orders_id" . " UNION ALL" . " SELECT '" . Order::ORDER_TYPE_SALES_PARTNER . "' AS order_type" . ", CONCAT(" . " jo.customer_billing_firstname, ' ', jo.customer_billing_lastname" . " ) AS customers_name" . ", jo.customer_billing_email AS customers_email_address" . ", jo.jng_sp_orders_id AS orders_id, jo.order_id AS orders_no" . ", 'EUR' AS currency, jo.order_date" . ", joi.status, ope.status AS last_status" . ", MAX(ope.last_sent_date) AS last_sent_date" . ", MAX(ope.sent_count) AS sent_count" . " FROM jng_sp_orders jo" . " INNER JOIN jng_sp_orders_items joi" . " ON joi.jng_sp_orders_id = jo.jng_sp_orders_id" . " LEFT JOIN orders_products_email ope" . " ON ope.orders_products_id = joi.jng_sp_orders_items_id" . " AND ope.type = 'S'" . " WHERE jo.jng_sp_id IN (" . implode(',', $sp_need_reminder) . ")" . " AND jo.payment_method LIKE '" . PAYMENT_METHOD_PREPAYMENT . "'" . " AND IFNULL(jo.payment_status,0) = 0 AND joi.status = 1" . " GROUP BY jo.jng_sp_orders_id";
$logger->write('Query orders');
$dbq = tep_db_query($query);
while ($o = tep_db_fetch_array($dbq)) {
    $orders_id = $o['orders_id'];
    $logger_oid = $o['order_type'] . 'O' . $orders_id;
    $order_date_timestamp = strtotime($o['order_date']);
    $last_sent_date_timestamp = strtotime($o['last_sent_date']);
    $invoice_order_type = substr($o['order_type'], 0, 1);
    $invoice = new payone_invoice('invoice_order_type', $invoice_order_type, "invoice_order_id='{$orders_id}'");
    $open_amount = $invoice->getBalance();
    $reminder_not_yet_sent = is_null($o['sent_count']);
    $need_resend = $last_sent_date_timestamp < strtotime('-' . PAYMENT_METHOD_BANK_TRANSFER_OVERDUE);
    $order = new Order($o['order_type'], $orders_id);
    $items_id = $order->getIDItems();
    //CHECK INVOICE STATUS
    if ($invoice->detail['invoice_complete_status'] == 'U') {
        //HANDLE UNDERPAID PREPAYMENT ORDERS
        //TODO: use new email template
        if ($reminder_not_yet_sent || $need_resend) {
            sendUnderpaidReminder($o, $open_amount, $languages[2]['path']);
            $logger->write('sent underpaid reminder ' . $logger_oid);
        }
    } elseif ($invoice->detail['invoice_complete_status'] == 'A') {
        //HANDLE UNPAID PREPAYMENT ORDERS
<?php

global $db;
require_once '../confy.php';
require_once '../functions.php';
require_once '../functions-2.php';
tep_db_connect();
use_class("payone_invoice");
$ids = tep_db_prepare_input($_GET['id']);
//invoice_id
$ids_array = explode(',', $ids);
foreach ($ids_array as $invoice_id) {
    $pi = new payone_invoice("invoice_id", $invoice_id);
    $pi->recalculate();
    echo "Invoice {$invoice_id} - txid " . $pi->detail['payone_txid'] . " recalculated \n";
}
tep_db_close();
Example #24
0
function conditionPrepaymentIsPaid($detail, $is_sp = true, $return_sql = false)
{
    /* -----------------------------------------------------------------------------------------
       * !!!!!! PLEASE UPDATE ON BOTH CONDITION IF THERES ANY CHANGES ON LOGIC !!!!!!
       * rule1 : all preauth-uncaptured that balance indicates overpaid, paid, and small amount
       * rule2 : all auth-submitted, preauth-captured that status is overpaid, paid, or complete
       * rule3 : all auth-submitted, preauth-captured that payment_status is paid
       ------------------------------------------------------------------------------------------- */
    //TODO : CHANGED BY USING payment_status = 1 (FOR NOW STILL USE 3 rules, PLEASE MAKE SURE FIRST FOR ALL ALLOWED SMALL PAYMENT ALSO APPLIED FOR CHANGE payment_status TO 1
    if ($return_sql) {
        use_class('payone_invoice');
        $cond = "(";
        $cond .= $is_sp ? "UPPER(jo.payment_method) = '" . strtoupper(PAYMENT_METHOD_PREPAYMENT) . "'" : "UPPER(o.payment_method) = '" . strtoupper(PAYMENT_METHOD_BANK_TRANSFER) . "'";
        $cond .= " AND (";
        //rule1
        $cond .= " ( pi.is_captured IN ('0','2') AND pi.invoice_amount_paid > 0 AND (" . payone_invoice::calcBalance('', true) . "*100 <= " . PAYONE_MAX_RETURNED_OPEN_PAYMENT . ") )";
        $cond .= " OR";
        //rule2
        $cond .= " ( (pi.is_captured IS NULL OR pi.is_captured NOT IN ('0','2')) AND pi.invoice_complete_status IN ('P','O','1') )";
        $cond .= " OR";
        //rule3
        $cond .= $is_sp ? " ( jo.payment_status = 1 )" : " ( o.paid_status = '1' )";
        $cond .= "))";
    } else {
        if ($is_sp) {
            $is_vorkasse = strtoupper($detail['payment_method']) == strtoupper(PAYMENT_METHOD_PREPAYMENT);
            $oid = $detail['jng_sp_orders_id'];
            $otype = 'S';
        } else {
            $is_vorkasse = strtoupper($detail['payment_method']) == strtoupper(PAYMENT_METHOD_BANK_TRANSFER);
            $oid = $detail['orders_id'];
            $detail['payment_status'] = $detail['paid_status'];
            $otype = 'J';
        }
        if (!$is_vorkasse) {
            return;
        }
        if (isset($detail['invoice_current_balance'])) {
            //PLEASE CONSIDER ADD "invoice_current_balance" AS SELECTION FIELD ON QUERY TO POSSIBLE USED THIS
            $current_balance = $detail['invoice_current_balance'];
        } else {
            use_class('payone_invoice');
            $inv = new payone_invoice("invoice_order_id", "{$oid}", "invoice_order_type='{$otype}'");
            $current_balance = $inv->getBalance();
        }
        $is_captured = $detail['is_captured'];
        /* disabled $rule1, we also set as Paid / payment_status = 1 for vorkasse with small payment <= PAYONE_MAX_RETURNED_OPEN_PAYMENT
            * so it would be handled by rule3
           $rule1 = (in_array($is_captured, array('0', '2')) && $detail['invoice_amount_paid']>0 && $current_balance<=PAYONE_MAX_RETURNED_OPEN_PAYMENT);
            */
        $rule2 = (!in_array($is_captured, array('0', '2')) || is_null($is_captured) || $is_captured == '') && in_array($detail['invoice_complete_status'], array('P', 'O', '1'));
        $rule3 = $detail['payment_status'] == 1;
        //$cond = $is_vorkasse && ($rule1 || $rule2 || $rule3);
        $cond = $is_vorkasse && ($rule2 || $rule3);
        //var_dump("$is_vorkasse | $rule1 | $rule2 | $cond");die();
    }
    return $cond;
}
Example #25
0
 function updateItemStatus($items_id, $new_status, $updater = '', $cancelby = 'J', $add_to_prod_target = true)
 {
     use_class('production_target');
     $pt = new production_target();
     list($new_status, $sub_status) = explode('-', $new_status);
     $item = $this->retrieveItemDetail($items_id);
     $itemMode = modeName($item['mode']);
     $timestamp = date('Y-m-d H:i:s');
     $is_reviving = statusIsCancelled($item['status']) && !statusIsCancelled($new_status);
     $reviving_need_next_update = false;
     //Revive Item should move to in HH directly if other items are already in HH
     if ($is_reviving) {
         $item_others = $this->retrieveItems($item['jng_sp_orders_id']);
         $others_in_hh = false;
         //If there's other items are already in HH set new status directly to HH
         foreach ($item_others as $io) {
             if ($io['status'] == '8') {
                 $new_status = '8';
                 $others_in_hh = true;
                 break;
             }
         }
         //If there's no items are already in HH (Full MTO)
         if (!$others_in_hh) {
             use_class('depot_orders');
             $class_do = new depot_orders();
             $item_do = $class_do->retrieveDetailTransmigran('SP', $items_id);
             if (!is_null($item_do)) {
                 if ($item_do['status'] < 6) {
                     /*  Order status is before in Package, do below steps:
                            1) Set real status same with last status of DP
                            2) Consider also set sub production status "only" when main status is in production
                            3) Cancel "directly" DP order, means we not use doCancelOrder
                         */
                     $new_status = $item_do['status'];
                     $sub_status = $new_status == '4' ? $item_do['prod_status'] : '';
                     $class_do->updateStatus($item_do['depot_orders_id'], '12', 'auto-set');
                     $reviving_need_next_update = true;
                     $revived_stock_status = $item_do['stock_status'];
                     $revived_mode = 'MTO';
                 } else {
                     /* Order status is >= "in Package"
                           1) Set real status to New
                        */
                     $new_status = '1';
                 }
             }
         }
     }
     //Only "Sent" and "Complete" status can be updated to "Returned"
     if ($new_status == '14' && !($item['status'] == '9' || $item['status'] == '11')) {
         return false;
     }
     //KPI Logging
     if ($add_to_prod_target) {
         if ($new_status == '5') {
             $pt->addDataToField($timestamp, 'finish', $item['order_quantity']);
         }
         if ($new_status == '6') {
             $pt->addDataToField($timestamp, 'package', $item['order_quantity']);
         }
         if ($new_status == '7') {
             $pt->addDataToField($timestamp, 'sent', $item['order_quantity']);
         }
         if ($new_status == '16') {
             $pt->addDataToField($timestamp, 'log_return_to_bali', $item['order_quantity']);
         }
         if ($new_status == '19') {
             $pt->addDataToField($timestamp, 'log_return_missing', $item['order_quantity']);
         }
         if ($new_status == '20') {
             $pt->addDataToField($timestamp, 'log_return_to_bin_in', $item['order_quantity']);
         }
         if ($new_status == '9') {
             use_class('jng_sp');
             $class_jsp = new jng_sp();
             //Get Sales Partner B2B
             $sp_b2b = array_keys($class_jsp->retrieveList("sp_type = 1"));
             $item_orders = $this->retrieveDetail($item['jng_sp_orders_id']);
             if (in_array($item_orders['jng_sp_id'], $sp_b2b)) {
                 $pt->addDataToField($timestamp, 'log_products_sent_b2b', $item['order_quantity']);
             } else {
                 $pt->addDataToField($timestamp, 'log_products_sent_b2c', $item['order_quantity']);
             }
             if ($itemMode == 'DSO') {
                 $pt->addDataToField($timestamp, 'log_products_sent_full_dso', $item['order_quantity']);
             } elseif ($itemMode == 'MTO') {
                 $pt->addDataToField($timestamp, 'log_products_sent_full_mto', $item['order_quantity']);
             } elseif ($itemMode == 'WMO' || $itemMode == 'MMO') {
                 $pt->addDataToField($timestamp, 'log_products_sent_mo', $item['order_quantity']);
             }
         }
     }
     $sub_status = trim(strtoupper($sub_status));
     if ($updater != 'new-import') {
         $setcancelation = $item['status'] == '10' && $new_status != '12' ? ", cancel_status=NULL" : '';
         if ($new_status == '10') {
             $setcancelation = ", cancel_status='{$cancelby}'";
         }
         $set_prod_status = $new_status == '4' && $sub_status != '' ? ", prod_status = '" . $sub_status . "'" : '';
         //PS: please don't set empty prod_status when it updated to status > 4,
         //since this will used for check whether order could transferred to DP or not
         //when real order taken over by HH when it from production
         tep_db_query("UPDATE jng_sp_orders_items SET status='{$new_status}' {$setcancelation} {$set_prod_status} WHERE jng_sp_orders_items_id={$items_id}");
     }
     $save_main_status_history = true;
     if (in_array($item['status'], array('3', '4', '5')) && $new_status == '4' && ($sub_status != '' && trim(strtoupper($item['prod_status'])) != $sub_status) || $is_reviving && $new_status == '4') {
         $psh = array();
         $psh['orders_items_id'] = $items_id;
         $psh['type'] = 'SP';
         $psh['status'] = $sub_status;
         $psh['status_quantity'] = $item['order_quantity'];
         $psh['status_date'] = $timestamp;
         $psh['update_by'] = $updater;
         saveProductionStatusHistory($psh);
         if ($item['status'] == '4') {
             $save_main_status_history = false;
         }
     }
     if ($save_main_status_history) {
         $sda = array();
         $sda['jng_sp_orders_items_id'] = $items_id;
         $sda['status'] = $new_status;
         $sda['status_quantity'] = $item['order_quantity'];
         $sda['status_date'] = $timestamp;
         $sda['update_by'] = $updater;
         tep_db_perform('jng_sp_orders_items_status_history', $sda);
     }
     if ($is_reviving) {
         //Revive Items from Cancel Request Status
         $this->recalculateOrderItemCount(null, $items_id);
         if ($new_status == '8') {
             $this->printCountReset($items_id);
             $this->updateOrderItemMode($items_id, 'MMO');
             use_class('depot_orders');
             $class_do = new depot_orders();
             $item_do = $class_do->transferFromRealOrder(SEGMENT_ID_HAMBURG, 'SP', $items_id);
             $do_close_status = explode(',', depot_orders::FILTER_STATUS_CLOSE);
             if (in_array($item_do['status'], $do_close_status)) {
                 $class_do->updateStatus($item_do['depot_orders_id'], '1');
                 $class_do->printCountReset($item_do['depot_orders_id']);
             }
         }
         if ($reviving_need_next_update) {
             $this->updateItemStockStatus($items_id, $revived_stock_status);
             if ($revived_mode != '') {
                 $this->updateOrderItemMode($items_id, $revived_mode);
             }
         }
         //Set need repackaging flag if needed
         $class_pm = new products_minierp();
         $p_data = $class_pm->retrieveDetail($item['products_id'], 'p');
         if ($p_data['p']['need_repackaging'] == 1) {
             $this->setNeedRepackaging($item['jng_sp_orders_id']);
         }
     }
     //Check other available products of this order which need repackage "nr" on cancel
     if ($new_status == '10') {
         $class_pm = new products_minierp();
         $need_repackaging = false;
         $nr_q = "SELECT products_id FROM jng_sp_orders_items WHERE jng_sp_orders_id = {$item['jng_sp_orders_id']} AND status NOT IN (10, 12)" . " AND jng_sp_orders_items_id != {$items_id}";
         $nr_dbq = tep_db_query($nr_q);
         while ($nr_r = tep_db_fetch_array($nr_dbq)) {
             $p_data = $class_pm->retrieveDetail($nr_r['products_id'], 'p');
             if ($p_data['p']['need_repackaging'] == 1) {
                 $need_repackaging = true;
                 break;
             }
         }
         if (!$need_repackaging) {
             $this->resetNeedRepackaging($item['jng_sp_orders_id']);
         }
     }
     //Update Stock Status and Elements Stock if necessary
     if ($new_status == '2' && $item['stock_status'] != 'S' && $item['stock_status'] != 'W') {
         //Set stock status to need sourcing if item is move to sourcing tab
         $this->updateItemStockStatus($items_id, false);
         $this->prodStatusReset($items_id);
         $this->eanPrintedReset($items_id);
         //$this->printCountReset($items_id);    //now we don't need to reset print_count for reprint pi when move to ready again.
         //TODO: Ceck if above statement is still true with new batch pi printing
     } elseif ($new_status == '3' && $item['stock_status'] == 'S' || $new_status == '4' && $item['stock_status'] == 'W') {
         //Reduce elements stock when products are forced to move to ready/production before approved by elements stock check
         $eu = $this->countElementsUsage($item['products_id'], $item['products_articles_id']);
         if (count($eu) > 0) {
             $jng_warehouses_id = '1';
             use_class('elements_stock');
             $class_es = new elements_stock();
             foreach ($eu as $elements_id => $euqty) {
                 $reduce_amount = $item['order_quantity'] * $euqty;
                 $class_es->reduceStockByPieces($jng_warehouses_id, $elements_id, $reduce_amount, 'RED SP-' . $items_id);
             }
         }
         $this->updateItemStockStatus($items_id, 'R');
     } elseif ($new_status == '1') {
         //IF THERES ORDERS NEEDS RESET BACK TO NEW
         $this->printCountReset($items_id);
         $this->printConfirmReset($items_id);
         $this->prodStatusReset($items_id);
         $this->eanPrintedReset($items_id);
         $this->updateItemStockStatus($items_id, 0);
         $this->updateOrderItemMode($items_id, 'UNSET');
     }
     //Production Target Flag Counter
     if ($item['status'] == '1' && ($new_status == '2' || $new_status == '3')) {
         //TODO: Move TARGET IN TO WHEN PI IS CONFIRMED BY SCANNING IT FOR EAN LABEL
         $this->productionTargetIn($timestamp, $item);
     } elseif ($new_status == '6') {
         $this->productionTargetOut($timestamp, $item);
     } elseif ($new_status == '10') {
         $this->productionTargetInReset($item);
     }
     //Auto Print PI rules
     if ($new_status == '3' || $new_status == '12') {
         /* e.g. :
                    5 items ordered > 4 to ready, 1 to sourcing ( PI not printed yet )
                    so this block is for handling PI not printed when "1 sourcing" is cancelled, while print_count flag is still "0"
             * !!!ABOVE SAMPLE PROCESS ISN'T RELIABLE AGAIN, SINCE WE NOW CHANGE PRINT PI DIRECTLY WHEN IT MOVES TO READY TAB VIA CRON cron/print-pi.php!!!
            */
         $jng_sp_orders_id = $item['jng_sp_orders_id'];
         $q_pi_status = tep_db_query("SELECT COUNT(1)=order_item_total AS pi_ready_to_print FROM jng_sp_orders_items WHERE jng_sp_orders_id = {$jng_sp_orders_id} AND status = 3 AND print_count = 0 GROUP BY jng_sp_orders_id");
         $pi_status = tep_db_fetch_array($q_pi_status);
         if ($pi_status['pi_ready_to_print'] == 1) {
             //PI PRINTED FOR THE FIRST TIME
             /* HANDLED BY BATCH PRINTING CRON cron/print-pi.php
                use_class('production_instruction_pdf');
                $class_pi = new production_instruction_pdf();
                $class_pi->addOrder('SP', $jng_sp_orders_id);
                $class_pi->createPDF(false, 'F', true);
                 */
         } else {
             if ($item['print_count'] > 0 && $item['print_confirmed'] > 0) {
                 //SECOND OR MORE PI PRINTED, could happen when there product by stock_status is "OK" but in real stock is "0" so this will set back to "NS". And when ready this will reprinted by using this block
                 //reset print_count and print_confirmed to include this order again on next print-pi scheduler
                 $this->printConfirmReset($item['jng_sp_orders_items_id']);
                 $this->printCountReset($item['jng_sp_orders_items_id']);
                 /*
                                     use_class('production_instruction_pdf');
                                     $class_pi = new production_instruction_pdf();
                                     $class_pi->addItem('SP', $item['jng_sp_orders_items_id']);
                                     $class_pi->createPDF(false, 'F', false);    //not add to daily statistic, we consider this as not "NEW"
                 */
             }
         }
     }
     $q = tep_db_query("SELECT jo.jng_sp_orders_id, UPPER(jo.payment_method) AS payment_method FROM jng_sp_orders_items joi LEFT JOIN jng_sp_orders jo ON jo.jng_sp_orders_id=joi.jng_sp_orders_id WHERE joi.jng_sp_orders_items_id={$items_id}");
     $order = tep_db_fetch_array($q);
     if ($new_status == '12' && strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_PREPAYMENT)) {
         /*----------------------------------------------------------------------------------------
           * MAKE RETURN ENTRY FOR "PREPAYMENT ONLY" ON "CANCEL CONFIRM", SINCE FOR NON-PREPAYMENT, 
           * PAYONE INVOICE WILL CREATED WHEN PRODUCTS IS SENT, 
           * SO NO NEED TO ADJUST IT OR CREATE RETURN CONTAINER WHEN CANCEL CONFIRM PROCESS
           -----------------------------------------------------------------------------------------*/
         use_class('payone');
         use_class('payone_invoice');
         $class_payone = new payone();
         $payi = new payone_invoice('invoice_order_id', $order['jng_sp_orders_id'], "invoice_order_type = 'S'");
         if ($payi->isUncapturedPrePayment()) {
             //UNCAPTURED PREAUTH PREPAYMENT NEED TO RECALCULATE INVOICE
             $payi->recalculate();
             //SET AS PAID WHEN OPEN BALANCE LEAVE SMALL AMOUNT OR THIS CANCEL PROCESS MAKES UNDERPAID BALANCE BECOMES PAID/OVERPAID
             if ($payi->getBalance() * 100 <= PAYONE_MAX_RETURNED_OPEN_PAYMENT) {
                 $this->updatePaymentStatus($item['jng_sp_orders_id'], '1', 'auto-set');
             }
         } else {
             //AUTH PREPAYMENT, CAPTURED PREAUTH PREPAYMENT (ADD TO RETURN CONTAINER)
             $class_payone->createReturnContainerSP('NULL', $item['order_quantity'], $items_id);
         }
     }
     //NEED TO RECALCULATE INVOICE WHEN REVIVING UNCAPTURED PREAUTH PREPAYMENT
     if ($is_reviving && strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_PREPAYMENT)) {
         use_class('payone_invoice');
         $payi = new payone_invoice('invoice_order_id', $order['jng_sp_orders_id'], "invoice_order_type = 'S'");
         if ($payi->isUncapturedPrePayment()) {
             $payi->recalculate();
         }
     }
     //SET READY TO CAPTURED FOR PREPAYMENT PREAUTH THAT ALREADY SENT
     if ($new_status == '9' && strtoupper($order['payment_method']) == strtoupper(PAYMENT_METHOD_PREPAYMENT)) {
         use_class('payone_invoice');
         $payi = new payone_invoice('invoice_order_id', $item['jng_sp_orders_id'], "invoice_order_type = 'S'");
         $payi->setIsCaptured('2');
     }
     return $new_status;
 }