function cip_db_query($query, $report = 'no', $link = 'db_link')
{
    //     $report manage a way of error reporting and can be:
    //     no, direct, return, add_session, add
    global ${$link}, $logger, $message;
    $result = mysql_query($query, ${$link});
    if (defined('STORE_DB_TRANSACTIONS') && STORE_DB_TRANSACTIONS == 'true') {
        if (!is_object($logger)) {
            $logger = new logger();
        }
        $logger->write($query, 'QUERY');
        if ($result === false) {
            $logger->write(mysql_error(), 'ERROR');
        }
    }
    if ($result === false) {
        $error = 'SQL error :<b>' . mysql_errno() . ' - ' . mysql_error() . '<br>' . $query;
        if ($report == 'direct') {
            echo $error;
        } elseif ($report == 'return') {
            $result = $error;
        } elseif ($report == 'add') {
            $message->add($error, 'error');
        } elseif ($report == 'add_session') {
            $message->add_session($error, 'error');
        }
        return false;
    } else {
        //         Только для запросов SELECT, SHOW, EXPLAIN, DESCRIBE
        //         mysql_query() возвращает указатель на результат запроса
        return $result;
    }
}
Beispiel #2
0
 /**
  * Sending Push Notification
  */
 public function send_notification($registatoin_ids, $message)
 {
     // include config
     include_once 'config.php';
     include_once 'logger.php';
     $logger = new logger();
     // Set POST variables
     $url = 'https://android.googleapis.com/gcm/send';
     $fields = array('registration_ids' => $registatoin_ids, 'data' => $message);
     $headers = array('Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json');
     // Open connection
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
     // Set the url, number of POST vars, POST data
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     // Disabling SSL Certificate support temporarly
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
     // Execute post
     $result = curl_exec($ch);
     $logger->write("Result+" . $result);
     if ($result === FALSE) {
         die('Curl failed: ' . curl_error($ch));
     }
     // Close connection
     curl_close($ch);
     //echo $result;
 }
 /**
  * Log exception message
  *
  * @param       Exception       $error      Exception to log
  */
 protected function log_exception(Exception $error)
 {
     if (!isset($this->_logger)) {
         $this->_logger = new logger();
     }
     $this->_logger->write($error->getMessage(), 'ERROR');
 }
Beispiel #4
0
function tep_db_query($query, $link = 'db_link')
{
    global ${$link}, $logger;
    if (defined('STORE_DB_TRANSACTIONS') && STORE_DB_TRANSACTIONS == 'true') {
        if (!is_object($logger)) {
            $logger = new logger();
        }
        $logger->write($query, 'QUERY');
    }
    $result = mysql_query($query, ${$link}) or tep_db_error($query, mysql_errno(), mysql_error());
    if (defined('STORE_DB_TRANSACTIONS') && STORE_DB_TRANSACTIONS == 'true') {
        if (mysql_error()) {
            $logger->write(mysql_error(), 'ERROR');
        }
    }
    return $result;
}
function xtc_db_query($query, $link = 'db_link')
{
    global ${$link}, $logger;
    if (STORE_DB_TRANSACTIONS == 'true') {
        if (!is_object($logger)) {
            $logger = new logger();
        }
        $logger->write($query, 'QUERY');
    }
    $result = mysqli_query(${$link}, $query) or xtc_db_error($query, mysqli_errno(${$link}), mysqli_error(${$link}));
    if (STORE_DB_TRANSACTIONS == 'true') {
        if (mysqli_error(${$link})) {
            $logger->write(mysqli_error(${$link}), 'ERROR');
        }
    }
    return $result;
}
 /**
  * Log exception message
  *
  * @param       Exception       $error      Exception to log
  */
 protected function log_exception(Exception $error)
 {
     if (!isset($this->_logger)) {
         require DIR_WS_CLASSES . 'logger.php';
         $this->_logger = new logger();
     }
     $this->_logger->write((string) $error, 'ERROR');
 }
function xos_db_query($query, $link = 'db_link')
{
    global ${$link}, $logger;
    if (defined('STORE_DB_TRANSACTIONS') && STORE_DB_TRANSACTIONS == 'true') {
        if (!is_object($logger)) {
            $logger = new logger();
        }
        $logger->write($query, 'QUERY');
    }
    $result = mysqli_query(${$link}, $query) or xos_db_error($query, mysqli_errno(${$link}), mysqli_error(${$link}));
    return $result;
}
 public function __construct()
 {
     if ($GLOBALS['distribution_cfg']['OSS_TYPE'] && $GLOBALS['distribution_cfg']['OSS_TYPE'] == "ES_FILE") {
         logger::write($GLOBALS['distribution_cfg']['OSS_DOMAIN'] . "/es_file.php");
         global $syn_image_ci;
         global $curl_param;
         //global $syn_image_idx;
         $syn_image_idx = 0;
         $syn_image_ci = curl_init($GLOBALS['distribution_cfg']['OSS_DOMAIN'] . "/es_file.php");
         curl_setopt($syn_image_ci, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($syn_image_ci, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($syn_image_ci, CURLOPT_SSL_VERIFYHOST, false);
         curl_setopt($syn_image_ci, CURLOPT_NOPROGRESS, true);
         curl_setopt($syn_image_ci, CURLOPT_HEADER, false);
         curl_setopt($syn_image_ci, CURLOPT_POST, TRUE);
         curl_setopt($syn_image_ci, CURLOPT_TIMEOUT, 1);
         curl_setopt($syn_image_ci, CURLOPT_TIMECONDITION, 1);
         $curl_param['username'] = $GLOBALS['distribution_cfg']['OSS_ACCESS_ID'];
         $curl_param['password'] = $GLOBALS['distribution_cfg']['OSS_ACCESS_KEY'];
         $curl_param['act'] = 2;
     }
     $GLOBALS['tmpl']->assign("MODULE_NAME", MODULE_NAME);
     $GLOBALS['tmpl']->assign("ACTION_NAME", ACTION_NAME);
     $GLOBALS['cache']->set_dir(APP_ROOT_PATH . "public/runtime/data/page_static_cache/");
     $GLOBALS['dynamic_cache'] = $GLOBALS['cache']->get("APP_DYNAMIC_CACHE_" . APP_INDEX . "_" . MODULE_NAME . "_" . ACTION_NAME);
     $GLOBALS['cache']->set_dir(APP_ROOT_PATH . "public/runtime/data/avatar_cache/");
     $GLOBALS['dynamic_avatar_cache'] = $GLOBALS['cache']->get("AVATAR_DYNAMIC_CACHE");
     //头像的动态缓存
     //输出导航菜单
     $nav_list = get_nav_list();
     $nav_list = init_nav_list($nav_list);
     foreach ($nav_list as $k => $v) {
         $nav_list[$k]['sub_nav'] = init_nav_list($v['sub_nav']);
     }
     $GLOBALS['tmpl']->assign("nav_list", $nav_list);
     //输出在线客服与时间
     if (app_conf("ONLINE_QQ") != "") {
         $qq = unserialize(app_conf("ONLINE_QQ"));
         $GLOBALS['tmpl']->assign("online_qq", $qq);
     }
     //输出页面的标题关键词与描述
     $GLOBALS['tmpl']->assign("site_info", get_site_info());
     //输出系统文章
     $system_article = get_article_list(8, 0, "ac.type_id = 3", "", true);
     $GLOBALS['tmpl']->assign("system_article", $system_article['list']);
     //输出帮助
     $deal_help = get_help();
     $GLOBALS['tmpl']->assign("deal_help", $deal_help);
     if (MODULE_NAME == "acate" && ACTION_NAME == "index" || MODULE_NAME == "article" && ACTION_NAME == "index" || MODULE_NAME == "cate" && ACTION_NAME == "index" || MODULE_NAME == "comment" && ACTION_NAME == "index" || MODULE_NAME == "help" && ACTION_NAME == "index" || MODULE_NAME == "link" && ACTION_NAME == "index" || MODULE_NAME == "mobile" && ACTION_NAME == "index" || MODULE_NAME == "msg" && ACTION_NAME == "index" || MODULE_NAME == "notice" && ACTION_NAME == "index" || MODULE_NAME == "notice" && ACTION_NAME == "list_notice" || MODULE_NAME == "rec" && ACTION_NAME == "rhot" || MODULE_NAME == "rec" && ACTION_NAME == "rnew" || MODULE_NAME == "rec" && ACTION_NAME == "rbest" || MODULE_NAME == "rec" && ACTION_NAME == "rsale" || MODULE_NAME == "score" && ACTION_NAME == "index" || MODULE_NAME == "space" && ACTION_NAME == "index" || MODULE_NAME == "space" && ACTION_NAME == "fav" || MODULE_NAME == "space" && ACTION_NAME == "fans" || MODULE_NAME == "space" && ACTION_NAME == "focus" || MODULE_NAME == "msg" && ACTION_NAME == "index" || MODULE_NAME == "ss" && ACTION_NAME == "index" || MODULE_NAME == "ss" && ACTION_NAME == "pick" || MODULE_NAME == "sys" && ACTION_NAME == "index" || MODULE_NAME == "sys" && ACTION_NAME == "list_notice" || MODULE_NAME == "vote" && ACTION_NAME == "index") {
         set_gopreview();
     }
 }
Beispiel #9
0
function tep_db_query($query, $link = 'db_link')
{
    global ${$link}, $logger;
    if (defined('STORE_DB_TRANSACTIONS') && STORE_DB_TRANSACTIONS == 'true') {
        if (!is_object($logger)) {
            $logger = new logger();
        }
        $logger->write($query, 'QUERY');
    }
    $query = preg_replace('/\\s+/', ' ', $query);
    //$start_time = microtime(true);
    $result = mysql_query($query, ${$link}) or tep_db_error($query, mysql_errno(), mysql_error());
    //$stop_time = microtime(true);
    //echo '<br><br>Total Records: '.mysql_num_rows($result);
    //echo '<br>Time taken: '.number_format($stop_time-$start_time,4);
    if (defined('STORE_DB_TRANSACTIONS') && STORE_DB_TRANSACTIONS == 'true') {
        if (mysql_error()) {
            $logger->write(mysql_error(), 'ERROR');
        }
    }
    return $result;
}
Beispiel #10
0
 /**
  * Send file to target folder from opened ftp connection
  * @param String $filename
  * @param String $target_filename
  * @return Boolean $result
  */
 public function send($filename, $target_filename)
 {
     $result = false;
     $failure1 = false;
     $failure2 = false;
     $logger = new logger('classes', 'tradebyte_send');
     if ($this->ftps_login && (file_exists($filename) && !is_dir($filename))) {
         $target_filename_upload = "{$target_filename}.upload";
         //MAKE STREAMING FILE AS .upload SO IT WON'T DIRECTLY PROCESSED BY TRADEBYTE
         //$status = ftp_put($this->conn_id, $target_filename_upload, $filename, FTP_ASCII);
         $local_filesize = filesize($filename);
         $res_target = @fopen("ssh2.sftp://{$this->sftp}/{$target_filename_upload}", 'w');
         if (!$res_target) {
             throw new Exception("Could not create file {$target_filename_upload} on TB server");
             $logger->write("Could not create file {$target_filename_upload} on TB server");
             $failure1 = true;
         }
         $res_local = @fopen($filename, 'r');
         if (!$res_local) {
             throw new Exception("Could not read file {$filename} from local source");
             $logger->write("Could not read file {$filename} from local source");
             $failure2 = true;
         }
         if (!$failure1 && !$failure2) {
             $written_bytes = stream_copy_to_stream($res_local, $res_target);
             if ($written_bytes >= $local_filesize) {
                 //RENAME xxx.xml.upload TO xxx.xml FOR ALLOWING TRADEBYTE TO PROCESS THE FINISHED UPLOAD XML FILE
                 //ftp_rename($this->conn_id, $target_filename_upload, $target_filename);
                 ssh2_sftp_rename($this->sftp, $target_filename_upload, $target_filename);
                 $result = true;
                 $logger->write("Success send {$filename} to Tradebyte");
             }
         }
         fclose($res_target);
         fclose($res_local);
     }
     $logger->close();
     return $result;
 }
Beispiel #11
0
 /**
  * 连接指定的连接池
  * @param unknown_type $pid
  */
 function connect_pid($pid, $charset = 'utf8')
 {
     $dbhost = $GLOBALS['distribution_cfg']['DB_DISTRIBUTION'][$pid]['DB_HOST'];
     $dbport = $GLOBALS['distribution_cfg']['DB_DISTRIBUTION'][$pid]['DB_PORT'];
     $dbuser = $GLOBALS['distribution_cfg']['DB_DISTRIBUTION'][$pid]['DB_USER'];
     $dbpw = $GLOBALS['distribution_cfg']['DB_DISTRIBUTION'][$pid]['DB_PWD'];
     $dbname = $GLOBALS['distribution_cfg']['DB_DISTRIBUTION'][$pid]['DB_NAME'];
     $dbhost .= ":" . $dbport;
     if (PHP_VERSION >= '4.2') {
         $this->link_list[$pid] = @mysql_connect($dbhost, $dbuser, $dbpw, true);
     } else {
         $this->link_list[$pid] = @mysql_connect($dbhost, $dbuser, $dbpw);
     }
     if ($this->link_list[$pid]) {
         $this->version = mysql_get_server_info($this->link_list[$pid]);
         /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */
         if ($this->version > '4.1') {
             if ($charset != 'latin1') {
                 mysql_query("SET character_set_connection={$charset}, character_set_results={$charset}, character_set_client=binary", $this->link_list[$pid]);
             }
             if ($this->version > '5.0.1') {
                 mysql_query("SET sql_mode=''", $this->link_list[$pid]);
             }
         }
         if ($dbname) {
             if (mysql_select_db($dbname, $this->link_list[$pid]) === false) {
                 @mysql_close($this->link_list[$pid]);
                 $this->link_list[$pid] = null;
             } else {
                 return true;
             }
         } else {
             @mysql_close($this->link_list[$pid]);
             $this->link_list[$pid] = null;
         }
     }
     logger::write("db_distribution_init_err:" . $pid, logger::ERR, logger::FILE, "db_distribution");
     return false;
 }
            }
            $value = $brand_id;
            $type = str_replace('set-', '', $type);
        } else {
            $pbgs = array('value' => $value);
            tep_db_perform('products_best_good_settings', $pbgs, 'update', "id={$type}");
        }
        $result['type'] = $type;
        $result['value'] = $value;
        ajaxReturn($result);
        exit;
    } elseif ($_POST['me_action'] == 'RECALCMARGIN') {
        set_time_limit(0);
        use_class('logger');
        $logger = new logger('cron', 'daily-counter-products-matexp');
        $logger->write('Margin is recalculated manually by ' . $session_userinfo['username']);
        $products = $class_pm->retrieveList("active_status=1");
        $pcounter = 0;
        foreach ($products as $p) {
            $pcounter++;
            $class_pm->updateMargin($p['products_id']);
            echo '. ';
        }
        $logger->write($pcounter . ' products updated successfully');
        $logger->close();
        echo 'DONE!';
        exit;
    }
}
$sop_mouse_over = array();
$sop_mouse_over['hide_hard'] = 'Report 0 stock for products with Hard Complexity and no depot stock on J&G and all SP Websites';
$api_status_ok = true;
$exchange_rate = array();
$exchange_rate['date'] = date('d.m.Y H:i:s');
$currencies = getAllCurrencies();
foreach ($currencies as $c_from) {
    foreach ($currencies as $c_to) {
        $key = generateExchangeRateKey($c_from, $c_to);
        if ($c_from == $c_to) {
            $rate = 1;
        } else {
            $rate = getExchangeRateOnline($c_from, $c_to);
            if ($rate == 0 || $rate === false) {
                $api_status_ok = false;
            }
        }
        $exchange_rate[$key] = $rate;
        $logger->write('Rate for ' . $key . ': ' . $rate);
    }
}
if ($api_status_ok) {
    save_config('exchange-rate', $exchange_rate);
    $logger->write('Save rate to configuration file');
} else {
    $subject = 'IMPORTANT & URGENT: Exchange Rate Cron Failed!';
    $content = '<p>Dear All, there seems to be a problem running ' . 'cron/daily-exchange-rate.php! It is not saved and ' . 'last success value is kept.</p>' . '<p>Please check the log and try to rerun it manually.' . ' If you keep receiving this error, create a 2 stars bug report!</p>';
    tep_mail(EMAIL_NAME_DEBUGR, EMAIL_ADDRESS_DEBUGR, $subject, $content, FROM_EMAIL_NAME, FROM_EMAIL_ADDRESS);
    $logger->write('Problem found! A notification is sent to IT Team.');
}
$logger->close();
echo 'Done!';
tep_db_close();
    $sales_report_filename = $config['srlastgeneratedfilename'];
    $base_filename = basename($sales_report_filename);
    $from_email_name = FROM_EMAIL_NAME;
    $from_email_address = FROM_EMAIL_ADDRESS;
    $success = array();
    $failed = array();
    foreach ($recipients as $member) {
        $to_name = $member['username'];
        $to_email_address = $member['email'];
        include '../' . DIR_WS_EMAILS . 'english/sales-report-weekly-products.php';
        if (!empty($to_email_address)) {
            tep_mail($to_name, $to_email_address, $email_subject, $email_text, $from_email_name, $from_email_address, true);
            $success[] = "{$to_name}-{$to_email_address}";
        } else {
            $failed[] = "{$to_name}-{$to_email_address}";
            $logger->write("- Send Email error to {$to_name} ({$to_email_address})");
        }
    }
}
if (count($success) > 0) {
    $msg = "Success send link SR file {$base_filename} to (" . implode(', ', $success) . ")";
    $logger->write($msg);
    echo "{$msg}\n";
}
if (count($failed) > 0) {
    $msg = "Failed send link SR file {$base_filename} to (" . implode(', ', $failed) . ")";
    $logger->write($msg);
    echo $msg;
}
$logger->close();
tep_db_close();
$num_op = tep_db_num_rows($r_op);
$arr_op = array();
while ($op = tep_db_fetch_array($r_op)) {
    $arr_op[] = $op['orders_products_id'];
}
// check total products on jng_sp_orders_items
$r_jo = tep_db_query("SELECT * FROM jng_sp_orders_items WHERE status=8 AND print_count>0");
$num_jo = tep_db_num_rows($r_jo);
$arr_jo = array();
while ($jo = tep_db_fetch_array($r_jo)) {
    $arr_jo[] = $jo['jng_sp_orders_items_id'];
}
// total products from both table
$num_total = $num_op + $num_jo;
if ($RUN_UPDATE_QUERY) {
    $logger->write("Running in UPDATE mode (orders will be updated for auto reprint)");
    if ($num_total == 0) {
        $logger->write("No orders found");
    } elseif ($num_total <= $max_total_orders_allowed) {
        // check if total count less than 10 product then reset query
        tep_db_query("UPDATE orders_products SET print_count=0 WHERE status=8 AND print_count>0");
        $total_reset_jg = tep_db_affected_rows();
        $logger->write("- TOTAL RESET JG = {$total_reset_jg} ");
        if ($total_reset_jg > 0) {
            $logger->write(implode(", ", $arr_op));
        }
        tep_db_query("UPDATE jng_sp_orders_items SET print_count=0 WHERE status=8 AND print_count>0");
        $total_reset_sp = tep_db_affected_rows();
        $logger->write("- TOTAL RESET SP = {$total_reset_sp} ");
        if ($total_reset_sp > 0) {
            $logger->write(implode(", ", $arr_jo));
Beispiel #16
0
                     $class_pm->stockReduce($jng_warehouses_id, $products_id, $articles_id, $bin['products_stock'], "CLEAR RACK by {$session_userinfo['username']}");
                 }
             }
         }
     }
     header("Location: ?open=rack-info&id={$rack_id}&reloadsegment=true" . ($hidemenuscript != '' ? '&hidemenu=true' : ''));
     exit;
 } elseif ($_POST['me_action'] == 'CLEARRACKNBS') {
     $logger = new logger('modules', 'rack-info');
     use_class('products_minierp');
     $class_pm = new products_minierp();
     $segment = $class_bin->retrieveSegmentDetail($rack['segment_id']);
     $jng_warehouses_id = $segment['warehouses_id'];
     $rack_bins = $class_bin->retrieveBins($rack['segment_id'], $rack_id);
     $bins_cleared = array();
     $logger->write('Clearing NBS for Rack ' . $rack_no);
     foreach ($rack_bins as $bin) {
         if ($bin['is_bestselling'] != '1') {
             $products_id = $bin['products_id'];
             $articles_id = $bin['articles_id'];
             if ($products_id > 0) {
                 $booked = $class_pm->productsBookedCount($jng_warehouses_id, $products_id, $articles_id);
                 if ($booked === 0) {
                     $class_bin->removeProductFromBox($bin['bins_id']);
                     if ($bin['products_stock'] > 0) {
                         $class_pm->stockReduce($jng_warehouses_id, $products_id, $articles_id, $bin['products_stock'], "CLEAR NBS RACK by {$session_userinfo['username']}");
                     }
                     $bins_cleared[] = $bin['code'];
                     $logger->write('BIN:' . $bin['code'] . ' > PID-AID:' . $products_id . '-' . $articles_id . ' > STOCK:' . $bin['products_stock']);
                 }
             }
                $q = '';
                if ($prefix == 'SP') {
                    //$q = "SELECT COUNT(*) AS total FROM jng_sp_orders_items WHERE jng_sp_orders_id = '$orders_id' AND status = 3";
                    $q = "SELECT COUNT(*) AS total FROM jng_sp_orders_items WHERE jng_sp_orders_items_id = '{$orders_items_id}' AND status = 3";
                } elseif ($prefix == 'JG') {
                    //$q = "SELECT COUNT(*) AS total FROM orders_products WHERE orders_id = '$orders_id' AND status = 3";
                    $q = "SELECT COUNT(*) AS total FROM orders_products WHERE orders_products_id = '{$orders_items_id}' AND status = 3";
                } elseif ($prefix == 'DP') {
                    $q = "SELECT COUNT(*) AS total FROM depot_orders WHERE depot_orders_id = '{$orders_items_id}' AND status = 3";
                }
                //TODO: ALSO CLEAN FOR batches PI FILES
                if ($q != '') {
                    $dbq = tep_db_query($q);
                    $res = tep_db_fetch_array($dbq);
                    //IF PI NOT GOES TO PRODUCTION YET (WE ASSUME THIS PI NOT DOWNLOADED AND PRINTED YET)
                    if ($res['total'] > 0) {
                        //MOVE REQUESTED PI FILE FROM "on_download" FOLDER TO RELATED PREFIX PI FOLDER (SP, JG, DP) FOR RE-DOWNLOAD AND PRINT
                        rename($pi_on_download_path . $file, $pi_cache_path . $prefix . '/' . $file);
                        $logger->write("MOVED '{$pi_on_download_path}{$file}' TO '{$pi_cache_path}{$prefix}/{$file}'");
                    } else {
                        //THIS PI ALREADY DOWNLOADED AND PRINTED BUT PROBLEM CONFIRMING TO SERVER (WE CONSIDER TO DELETE THIS PI)
                        unlink($pi_on_download_path . $file);
                        $logger->write("DELETED FROM {$pi_on_download_path}.{$file}");
                    }
                }
            }
        }
    }
}
$logger->close();
tep_db_close();
$class_pm = new products_minierp();
$class_do = new depot_orders();
$class_s = new styles();
$whid = WAREHOUSE_ID_FOR_HANDLING_ORDERS;
$segment_id = SEGMENT_ID_DEFAULT;
//Grab all data that can be retrieved collectively for the whole products
//stock from below function already exclude active booking
$products_stock = $class_pm->stockRetrieveAll($whid, '', true);
//Grab all required Settings
Product::loadDIOHsettings();
//For now we can not run auto cancel in Manobo Local due to the
//sync issues of Depot Orders with Manobo Central
if (!SERVER_IS_LOCAL) {
    //query all auto refill orders currently open
    //and can still be canceled(grouped by article)
    $logger->write('1) AUTO CANCEL');
    $logger->write('Query orders which can still be canceled:');
    $q = "SELECT products_id, articles_id, SUM(quantity) AS total_qty" . ", GROUP_CONCAT(depot_orders_id) AS order_ids" . ", GROUP_CONCAT(status) AS order_status" . " FROM depot_orders" . " WHERE trans_type = 'AR' AND" . " trans_id = " . depot_orders::AUTO_REFILL_ID_DAILYCRON . " AND (status IN (1,2,3) OR (status = 4 AND prod_status = 'P'))" . " GROUP BY products_id, articles_id";
    " ORDER BY products_id, articles_id";
    $r = tep_db_query($q);
    $total_found = tep_db_num_rows($r);
    $logger->write("{$total_found} article(s) found");
    if ($total_found > 0) {
        $canceled_qty_total = 0;
        while ($row = tep_db_fetch_array($r)) {
            $pid = $row['products_id'];
            $aid = $row['articles_id'];
            $stock_id = $pid . '-' . $aid;
            if (!isset($p) || !is_object($p) || $p->id != $pid) {
                $p = new Product($pid);
            }
 function constructQuery($jng_sp_id, $filters = array())
 {
     $res_filter = $this->constructFilters($filters, $jng_sp_id);
     $filter = $res_filter['filter'];
     $filter_having = $res_filter['filter_having'];
     $filter_join = $res_filter['filter_join'];
     $field_used_in_filter = $res_filter['field_used_in_filter'];
     $is_all_sp = $jng_sp_id == 'allsp' ? true : false;
     $query = "SELECT e.*";
     $query .= ", el.used_in_products, el.weekly_sold, el.weekly_sold_products";
     $query .= ", ec.name AS cat_name, pm.material_name AS mat_name, cpd.name AS color_name, ei.name AS size_name, eh.name AS holesize_name";
     $query .= ", es.name AS shape_name, es.shape_image, eu.name AS surface_name, eu.surface_image, et.name AS cut_name, et.cuts_image AS cut_image";
     $query .= ", ehe.name AS height_name, ew.name AS width_name, eth.name AS thickness_name";
     $query .= " FROM element e";
     $query .= " LEFT JOIN elements_log el ON el.elements_id=e.elements_id";
     $query .= " LEFT JOIN elements_log_static els ON els.elements_id=e.elements_id";
     $query .= " LEFT JOIN elements_to_elements_suppliers etes ON etes.elements_id = e.elements_id AND is_default = 1";
     $query .= " LEFT JOIN element_category ec ON ec.element_category_id=e.attribute_category_id";
     $query .= " LEFT JOIN products_materials pm ON pm.products_materials_id=e.attribute_material_id";
     $query .= " LEFT JOIN color_pattern cp ON cp.color_pattern_id=e.attribute_color_id";
     $query .= " LEFT JOIN color_pattern_description cpd ON cpd.color_pattern_id=e.attribute_color_id AND languages_id=1";
     $query .= " LEFT JOIN element_size ei ON ei.element_size_id=e.attribute_size_id";
     $query .= " LEFT JOIN element_holesize eh ON eh.element_holesize_id=e.attribute_holesize_id";
     $query .= " LEFT JOIN element_shape es ON es.element_shape_id=e.attribute_shape_id";
     $query .= " LEFT JOIN element_surface eu ON eu.element_surface_id=e.attribute_surface_id";
     $query .= " LEFT JOIN element_cut et ON et.element_cut_id=e.attribute_cut_id";
     $query .= " LEFT JOIN element_height ehe ON ehe.element_height_id=e.attribute_height_id";
     $query .= " LEFT JOIN element_width ew ON ew.element_width_id=e.attribute_width_id";
     $query .= " LEFT JOIN element_thickness eth ON eth.element_thickness_id=e.attribute_thickness_id";
     if (in_array("elstock", $field_used_in_filter)) {
         $query .= " LEFT JOIN elements_stock est ON est.elements_id = e.elements_id AND est.jng_warehouses_id = " . WAREHOUSE_ID_ELEMENTS;
     }
     if (in_array("isnoproducts", $field_used_in_filter)) {
         $query .= " LEFT JOIN (SELECT DISTINCT(elements_id) FROM products_use_elements pue";
         $query .= " INNER JOIN products p ON p.products_id = pue.products_id AND p.products_status = 1) pue ON pue.elements_id = e.elements_id";
         $query .= " LEFT JOIN (SELECT DISTINCT(paue.elements_id) FROM products_articles_use_elements paue";
         $query .= " INNER JOIN products_use_elements pue ON pue.products_use_elements_id = paue.products_use_elements_id";
         $query .= " INNER JOIN products p ON p.products_id = pue.products_id AND p.products_status = 1";
         $query .= " AND paue.elements_id > 0) paue ON paue.elements_id = e.elements_id";
     }
     foreach ($filter_join as $fjk => $fjv) {
         $query .= $fjv;
     }
     $query .= " WHERE e.is_finalized='1'";
     if ($filter != '') {
         $query .= " AND {$filter}";
     }
     if ($filter_having != '') {
         $query .= " GROUP BY e.elements_id HAVING " . $filter_having;
     }
     $query .= " ORDER BY e.elements_id";
     //save query to a log file
     $logger = new logger('classes', 'elements_search_query_executed');
     $logger->write($query);
     $logger->close();
     return $query;
 }
<?php

set_time_limit(0);
global $db;
require_once '../confy.php';
require_once '../functions.php';
require_once '../functions-2.php';
tep_db_connect();
use_class('logger');
$logger = new logger('cron', 'daily-counter-products-matexp');
use_class("products_minierp");
$class_pm = new products_minierp();
$products = array();
$products = $class_pm->retrieveList("active_status=1");
$pcount = 0;
foreach ($products as $p) {
    $pcount++;
    $class_pm->calculateMaterialExpenses($p['products_id']);
    $logger->write("{$pcount} - PID: " . $p['products_id'] . ' - TS: ' . time());
    echo '. ';
}
$logger->close();
echo 'Done!';
tep_db_close();
global $db;
require_once '../confy.php';
require_once '../functions.php';
require_once '../functions-2.php';
tep_db_connect();
use_class('logger');
$logger = new logger('cron', 'daily-counter-products');
use_class('forecasting');
use_class('product');
use_class('products_minierp');
$class_pm = new products_minierp();
////////////////////////////////////
// SP PRODUCTS ACTIVE AGE COUNTER //
////////////////////////////////////
tep_db_query("UPDATE jng_sp_catalog SET active_age=active_age+1 WHERE last_active_status='1'");
$logger->write("DONE - SP PRODUCTS ACTIVE AGE COUNTER");
///////////////////////
// MATERIAL EXPENSES //
///////////////////////
// MOVED TO cron/daily-counter-products-matexp.php
///////////////////////
//////////////////////////////
// PRODUCT LOG DATA COUNTER //
//////////////////////////////
//MONTHLY VIEWED
//Data is never used, stop querying it
//$products = array();
//$top_products_month = $class_pm->getTopProducts(0, 30);
//foreach($top_products_month as $p) {
//    $pid = $p['products_id'];
//    if(!isset($products[$pid])) $products[$pid] = array('products_id'=>$pid);
require_once '../functions-2.php';
require_once '../functions-xml.php';
require_once DIR_WS_FUNCTIONS . 'html_output.php';
tep_db_connect();
use_class('xml_tools');
use_class('depot_orders');
use_class('logger');
use_class('Product');
use_class('bins');
$logger = new logger('cron', 'depot-refill-local-xml-generator');
$class_do = new depot_orders();
$class_bins = new bins();
$today_datetime = date('Y-m-d H:i:s');
$today = date('Y-m-d', strtotime($today_datetime));
$country_name = getCountryName($server_local_code);
$logger->write("PREPARE XML DEPOT REFILL - START");
//GET TODAYS DEPOT REFILL CREATED
$q = "SELECT * FROM depot_orders" . " WHERE segments_id = {$segment_id_default} " . " AND trans_type = 'AR' AND trans_id = " . depot_orders::AUTO_REFILL_ID_DAILYCRON . " AND order_date >= '{$today} 00:00:00' AND order_date <= '{$today} 23:59:59'";
$r = tep_db_query($q);
if (tep_db_num_rows($r) > 0) {
    $segment = $class_bins->retrieveSegmentDetail($segment_id_default);
    //PREPARE FOR CREATE XML DEPOT REFILL LOCAL
    $xmlt = new xml_tools('1.0', 'UTF-8');
    //DEPOT_REFILL_LOCAL
    $depot_refill_local = $xmlt->drawTag($xmlt, 'DEPOT_REFILL_LOCAL');
    //LOCAL_INFO
    $local_info = $xmlt->drawTag($depot_refill_local, 'LOCAL_INFO');
    $xmlt->drawTag($local_info, 'SEGMENT_ID', $segment_id_default);
    $xmlt->drawTag($local_info, 'CREATED_DATE', date('Y-m-d H:i:s'));
    $group_name = "Manobo Local Orders ({$country_name})";
    $xmlt->drawTag($local_info, 'GROUP_NAME', $group_name);
Beispiel #23
0
 public function newUser()
 {
     $sess = new ppg_session();
     $this->dbAccess = $sess->start("new_account.php");
     $sess_data = $sess->get_data();
     $log = new logger($sess_data->ppg_sessionId, "new_account.php");
     $log->write("Starting up");
     $postdata = file_get_contents("php://input");
     $request = json_decode($postdata);
     $log->write("got the following");
     if (!isset($request->email)) {
         $log->write("Email isn't set on calling object", 9);
         echo "Invalid Request sent";
         return;
     }
     $log->write("Email gives -> {$request->email}");
     $log->write("Password gives -> " . $request->pass);
     $log->write("Handle gives -> " . $request->handle);
     $result = $this->dbAccess->db_prepare("SELECT email,password,handle FROM `users` WHERE email = ?");
     $result->bind_param('s', $request->email);
     $this->dbAccess->db_execute(1, $result);
     $result->bind_result($emName, $cPass, $shortName);
     $rwCnt = 0;
     if (!$this->validateEmail($request->email)) {
         $log->write("Invalid e-mail entered - {$request->email}", 9);
         $eMsg = "Invalid e-mail address";
         echo $eMsg;
         return;
     }
     while ($result->fetch()) {
         $rwCnt++;
     }
     $log->write("Got {$rwCnt} from query");
     $eMsg = "This address is already registered";
     if ($rwCnt == 1) {
         //email not found
         $log->write("Email address found - {$request->email}");
         echo $eMsg;
         return;
     }
     if ($rwCnt == 0) {
         //password validation - just in case some mong is trying it on.
         if (strlen($request->pass <= '8')) {
             echo "Your Password Must Contain At Least 8 Characters!";
             return;
         } elseif (!preg_match("#[0-9]+#", $request->pass)) {
             echo "Your Password Must Contain At Least 1 Number!";
             return;
         } elseif (!preg_match("#[A-Z]+#", $request->pass)) {
             echo "Your Password Must Contain At Least 1 Capital Letter!";
             return;
         } elseif (!preg_match("#[a-z]+#", $request->pass)) {
             echo "Your Password Must Contain At Least 1 Lowercase Letter!";
             return;
         }
         $log->write("Valid email address");
         $log->write("Valid password");
         $passHash = crypt($request->pass, "\$5\$poopingisalways1");
         $result = $this->dbAccess->db_prepare("INSERT INTO `users` (\n   \t\t\t\t\t`organisations_id`,\n   \t\t\t\t\t`user_profiles_id`,\n   \t\t\t\t\t`roles_id`,\n   \t\t\t\t\t`calendars_id`,\n   \t\t\t\t\t`resources_id`,\n   \t\t\t\t\t`email`,\n   \t\t\t\t\t`password`,\n   \t\t\t\t\t`handle`,\n   \t\t\t\t\t`verifylink`)\t\n   \t\t\t\t\tVALUES(?,?,?,?,?,?,?,?,?)");
         $orgId = 1;
         $userProf = 2;
         $roleId = 1;
         $calId = 1;
         $resourceId = 1;
         $result->bind_param("iiiiissss", $orgId, $userProf, $roleId, $calId, $resourceId, $request->email, $passHash, $request->handle, $this->usrToken);
         $this->dbAccess->db_execute(4, $result);
         $subject = 'Welcome to PlanPrintGo';
         $message = "Hello,\n\nPlease click or copy the link into your browser to activate your newly created Plan Print Go account.\n\n" . "http://192.168.56.10/php/verify.php?id={$this->usrToken}\n\n" . "If you didn't create this account please let us know at admin@planprintgo.com\n\nThanks from the team at PPG\n";
         $headers = 'From: admin@planprintgo.com' . "\r\n" . 'Reply-To: admin@planprintgo.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
         mail($request->email, $subject, $message, $headers);
         $log->write("Login URL = http://192.168.56.10/php/verify.php?id={$this->usrToken}");
         echo "cool";
         return;
     }
 }
                $messagebox->add($order_created . ' new orders created!', 'green');
            }
        }
    } else {
        $messagebox->add('Upload Failed! Only CSV File is allowed,' . ' please check your file type: ' . $file['type']);
    }
}
if (isset($_FILES['orders_file_update'])) {
    set_time_limit(0);
    ini_set('memory_limit', '512M');
    $jng_sp_id = tep_db_prepare_input($_POST['jng_sp_id']);
    $sp_detail = $class_sp->retrieveDetail($jng_sp_id);
    $file = $_FILES['orders_file_update'];
    if (isFileTypeCSV($file['type'])) {
        $logger = new logger('modules', 'sp-orders-locals');
        $logger->write('Processing file: ' . $file['name']);
        $update_date = date('Y-m-d H:i:s');
        $file_handler = fopen($file['tmp_name'], "r");
        $item_total = 0;
        $item_updated = 0;
        $new_tracking_code = 0;
        $row_count = 0;
        while ($columns = fgetcsv($file_handler, 0, $csv_seperator, $csv_data_wrapper)) {
            $row_count++;
            if ($row_count % 25 == 0) {
                $class_jo = Order::getOldOrderFunctionSP();
                unset($class_jo->items);
            }
            $logger->write('- Reading row ' . $row_count);
            if ($row_count == 1) {
                $col_rules = $columns;
                    echo '<div>' . ucwords(str_replace('_', ' ', $key)) . ' = ' . $value_used . '</div>';
                }
                $receipts = ReportBookkeeping::getTotalReceipts($period);
                $returns = ReportBookkeeping::getTotalReturns($period);
                echo '<div>Total Amount Received = ' . number_format($receipts, 2) . '</div>' . '<div>Total Returns (including refund & non refund, ' . 'shipping cost and small amount adjustment) = ' . number_format($returns, 2) . '</div>' . '<div>&nbsp;<br />&nbsp;</div>';
            }
        }
    }
} else {
    //WHEN CALLED WITHOUT SPECIFIC PERIOD (BY CRON)
    //NO NEED TO DISPLAY RESULT AND SAVE QUERIED DATA OF CURRENT PERIOD
    //set timetamp based on when cron is called,
    //if >=23 then consider grabbing today as period
    //else then always use previous day as period
    ReportBookkeeping::setOptionArchiveQueryAsExcel(true);
    $logger->write('Generating Period');
    $period_timestamp = date('G') >= 23 ? time() : strtotime('-1 day');
    $period = date(ReportBookkeeping::PERIOD_DATE_FORMAT, $period_timestamp);
    $logger->write('Query Invoices in Period');
    $invoice_quantity = ReportBookkeeping::getInvoiceTotalQuantity($period);
    $invoice_amount = ReportBookkeeping::getInvoiceTotalAmount($period);
    $logger->write('Query Receipts in Period');
    $receipts = ReportBookkeeping::getReceiptTotal($period);
    $receipts_late_from_prev_month = ReportBookkeeping::getReceiptTotalLateFromPreviousPeriod($period);
    $logger->write('Query Returns');
    $returns = ReportBookkeeping::getReturnTotal($period);
    $returns_same_period = ReportBookkeeping::getTotalReturnsSamePeriod($period);
    $logger->write('Query Open Amount');
    $open_amount = ReportBookkeeping::getOpenInvoiceTotalAmount($period, ReportBookkeeping::OPEN_INVOICE_MODE_CURRENT);
    $open_amount_prev0 = ReportBookkeeping::getOpenInvoiceTotalAmount($period, ReportBookkeeping::OPEN_INVOICE_MODE_CURRENT_PREV_PERIOD0);
    $open_amount_prev1 = ReportBookkeeping::getOpenInvoiceTotalAmount($period, ReportBookkeeping::OPEN_INVOICE_MODE_CURRENT_PREV_PERIOD1);
            if ($p['status'] == $status) {
                if ($order['order_type'] == Order::ORDER_TYPE_JULIE_GRACE) {
                    $class_o->updateProductStatusNotification($p['orders_products_id'], $status);
                } elseif ($order['order_type'] == Order::ORDER_TYPE_SALES_PARTNER) {
                    $class_jo->updateProductStatusNotification($p['jng_sp_orders_items_id'], $status);
                }
            }
        }
    }
    //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') {
require_once '../functions.php';
require_once '../functions-2.php';
tep_db_connect();
use_class('logger');
$logger = new logger('cron', 'daily-counter');
use_class('jng_sp');
use_class('jng_sp_orders');
use_class('jng_sp_catalog');
$class_sp = new jng_sp();
$class_jo = new jng_sp_orders();
$class_jc = new jng_sp_catalog();
$sp_data = $class_sp->retrieveList();
//////////////////////////////
// SP PRODUCTS SOLD COUNTER //
//////////////////////////////
$logger->write('1 - Product Sold Counter');
//TODO: The calculation is still based on jng_sp_catalog, which means SP with no
//catalog (like buyvip/retails) will not be included in this calculation!
foreach ($sp_data as $sp_list) {
    $class_jo->productsSoldCounter($sp_list['jng_sp_id']);
}
unset($sp);
/* WE STOP CALCULATING VC USING OLD METHOD
 * NEW VC CALCULATION IS NOT IN ORDER BASED, BUT IN SP BASED
///////////////////////
// SP VC CALCULATION //
///////////////////////
$logger->write('2 - SP VC Calculation');
foreach($sp_data as $sp_list) {
    // VC Prediction
    $jng_sp_id = $sp_list['jng_sp_id'];
 //var_dump($items_confirmed);
 //echo '</pre>';
 //die('xml created!');
 //SEND XML TO TRADEBYTE SERVER VIA FTP SSL
 use_class('tradebyte');
 $tb = new tradebyte();
 $tb->connect();
 $target_filename = TRADEBYTE_FTP_IN_PATH . $xml_file;
 $success_upload = false;
 if ($tb->send($xml_filename, $target_filename)) {
     rename($xml_filename, TRADEBYTE_ARCHIVE_MESSAGES_PATH . $xml_file);
     $success_upload = true;
 }
 $tb->disconnect();
 if ($success_upload) {
     $logger->write("Success sent MESSAGES xml {$xml_file} to TB");
     $total_confirm_R = count($items_confirmed['R']);
     if ($total_confirm_R > 0) {
         $class_jo->confirmOrderReturn($items_confirmed['R']);
         $logger->write("{$total_confirm_R} returned items confirmed");
     }
     $total_confirm_S = count($items_confirmed['S']);
     if ($total_confirm_S > 0) {
         $class_jo->confirmOrderDelivery($items_confirmed['S']);
         $logger->write("{$total_confirm_S} sent/canceled items confirmed");
     }
 } else {
     $logger->write("Failed sent MESSAGES xml {$xml_file} to TB");
 }
 //DELIVERY NOTIFICATION IS HANDLED IN cron/dhl-easylog-export-processor.php
 if (count($orders_canceled) > 0) {
require_once '../functions-2.php';
require_once DIR_WS_FUNCTIONS . 'html_output.php';
require_once DIR_WS_CLASSES . 'fpdf.php';
tep_db_connect();
define('FPDF_IMGPATH', DIR_WS_IMAGES . 'pdf/');
define('FPDF_FONTPATH', FPDF_IMGPATH . 'fonts/');
use_class('logger');
$logger = new logger('print', 'sales-report-weekly-products');
use_class('jng_sp');
$class_sp = new jng_sp();
$sp_list = $class_sp->retrieveList();
$pid = !empty($_POST['pid']) ? $_POST['pid'] : '';
$filter_date = !empty($_POST['filter_date']) ? $_POST['filter_date'] : date('Y-m-d h:i:s');
$filename = !empty($_POST['filename']) ? $_POST['filename'] : 'sales-report-weekly-products-';
$filename = $filename . date('YmdHi', strtotime($filter_date)) . '.pdf';
$logger->write('Filter Date: ' . $filter_date);
class PDF extends FPDF
{
    var $margin = 10;
    //Create image stars
    function drawStar($stars_amount, $xpos, $ypos, $stars_max = 3, $width = 5, $height = 5)
    {
        $uri = @$_SERVER["HTTPS"] == "on" ? "https://" : "http://";
        $uri .= "manobo.de/images/";
        $stars = '';
        if ($stars_amount > 0) {
            for ($s = 1; $s <= $stars_amount; $s++) {
                $stars .= $this->Image($uri . 'icon-star-filled.jpg', $xpos, $ypos, $width, $height);
                $xpos += 6;
            }
        }
$sp_use_tb_ids = array_keys($sp_use_tb);
$sp_use_tb_ids_filter = implode(',', $sp_use_tb_ids);
//ONCE A WEEK WE WILL UPLOAD FULL CATALOG UPDATE TO TRADEBYTE.
//THIS IS A WORKAROUND TO SOLVE ISSUE WHERE PRICE IS NOT AUTO UPDATED
//AND ALSO IF AN UPLOAD ERROR EXIST WHICH PREVENTED TRADEBYTE TO RECEIVE
//THE LATEST STOCK CONDITION
//The current settings is every thursday at 3am and reupload again from 6am
$config_upload_day = 4;
$config_upload_hour = 3;
$config_upload_wait_until = 6;
$day = intval(date('N'));
$hour = intval(date('H'));
$mins = intval(date('i'));
if ($day == $config_upload_day) {
    if ($hour == $config_upload_hour && $mins == 0) {
        $logger->write('Update flag so all articles will be uploaded');
        //TODO: When possible or needed remove zalando catalog from below query
        $q = "UPDATE products_stock ps" . " LEFT JOIN products p ON p.products_id=ps.products_id" . " LEFT JOIN jng_sp_catalog jc" . " ON jc.jng_sp_id IN ({$sp_use_tb_ids_filter})" . " AND jc.products_id=ps.products_id" . " SET ps.tb_need_update=1" . " WHERE p.tb_status IN (1, 2) AND jc.last_active_status=1";
        tep_db_query($q);
    } else {
        //now we should give tradebyte server some time to process it
        if ($hour >= $config_upload_hour && $hour < $config_upload_wait_until) {
            $logger->write('Skip upload so tradebyte has enough time to' . ' process last full upload');
            $logger->close();
            die('Skipped!');
        }
    }
}
$reported_products = array();
//GET ALL PRODUCTS STOCK CONNECTED TO TRADEBYTE AND FLAG AS NEED STOCK UPDATE
$q = "SELECT ps.products_id, ps.articles_id" . ", ps.stock, ps.booking_active, p.products_model, p.active_status" . ", IFNULL(pa.active_status, p.active_status) AS article_status" . ", IF(ps.articles_id=0, pnc.products_length, pa.length) AS length" . ", jc.jng_sp_id, jc.active_status AS catalog_status" . ", jc.price, jc.price_old" . " FROM products_stock ps" . " INNER JOIN jng_sp_catalog jc" . " ON jc.jng_sp_id in ({$sp_use_tb_ids_filter})" . " AND jc.products_id=ps.products_id" . " INNER JOIN products p ON p.products_id=ps.products_id" . " LEFT JOIN products_non_configurator pnc" . " ON pnc.products_id=ps.products_id" . " LEFT JOIN products_articles pa" . " ON pa.products_articles_id=ps.articles_id" . " WHERE p.tb_status IN (1, 2, 3) AND ps.tb_need_update = 1" . " ORDER BY ps.products_id, ps.articles_id";