From 3aaa6c66805e03c79f09f6a3a9286be0c268621b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CVeLiTi=E2=80=9D?= <“info@veliti.nl”> Date: Mon, 17 Feb 2025 19:01:04 +0100 Subject: [PATCH] CMXX - Checkout and Placeorder --- api/v2/get/discounts.php | 135 ++++++++++ api/v2/get/invoice.php | 127 +++++++++ api/v2/get/products_categories.php | 4 + api/v2/get/shipping.php | 155 +++++++++++ api/v2/get/taxes.php | 115 ++++++++ api/v2/get/transactions.php | 118 +++++++++ api/v2/get/transactions_items.php | 118 +++++++++ api/v2/post/checkout.php | 52 ++++ api/v2/post/discounts.php | 103 ++++++++ api/v2/post/invoice.php | 121 +++++++++ api/v2/post/placeorder.php | 144 ++++++++++ api/v2/post/shipping.php | 99 +++++++ api/v2/post/shopping_cart.php | 14 + api/v2/post/transactions.php | 125 +++++++++ assets/functions.php | 407 +++++++++++++++++++++++++++++ discount.php | 190 ++++++++++++++ discounts.php | 152 +++++++++++ order.php | 290 ++++++++++++++++++++ orders.php | 172 ++++++++++++ settings/settingsmenu.php | 19 +- settings/settingsprofiles.php | 2 +- settings/settingsviews.php | 12 +- shipping.php | 159 +++++++++++ shipping_manage.php | 169 ++++++++++++ tax.php | 75 ++++++ taxes.php | 75 ++++++ 26 files changed, 3148 insertions(+), 4 deletions(-) create mode 100644 api/v2/get/discounts.php create mode 100644 api/v2/get/invoice.php create mode 100644 api/v2/get/shipping.php create mode 100644 api/v2/get/taxes.php create mode 100644 api/v2/get/transactions.php create mode 100644 api/v2/get/transactions_items.php create mode 100644 api/v2/post/checkout.php create mode 100644 api/v2/post/discounts.php create mode 100644 api/v2/post/invoice.php create mode 100644 api/v2/post/placeorder.php create mode 100644 api/v2/post/shipping.php create mode 100644 api/v2/post/transactions.php create mode 100644 discount.php create mode 100644 discounts.php create mode 100644 order.php create mode 100644 orders.php create mode 100644 shipping.php create mode 100644 shipping_manage.php create mode 100644 tax.php create mode 100644 taxes.php diff --git a/api/v2/get/discounts.php b/api/v2/get/discounts.php new file mode 100644 index 0000000..964a275 --- /dev/null +++ b/api/v2/get/discounts.php @@ -0,0 +1,135 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE d.accounthierarchy like "'.$condition.'"'; + break; +} + +//NEW ARRAY +$criterias = []; +$clause = ''; + +//Check for $_GET variables and build up clause +if(isset($get_content) && $get_content!=''){ + //GET VARIABLES FROM URL + $requests = explode("&", $get_content); + //Check for keys and values + foreach ($requests as $y){ + $v = explode("=", $y); + //INCLUDE VARIABLES IN ARRAY + $criterias[$v[0]] = $v[1]; + + if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history'|| $v[0] =='success_msg'){ + //do nothing + } + elseif ($v[0] == 'search') { + //build up search + $clause .= ' AND name like :'.$v[0]; + } + elseif ($v[0] == 'discount_category_id'){ + $clause .= ' AND d.id = :'.$v[0]; + } + elseif ($v[0] == 'discount_products_id'){ + $clause .= ' AND d.id = :'.$v[0]; + } + else {//create clause + $clause .= ' AND d.'.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//Define Query +if(isset($criterias['totals']) && $criterias['totals'] ==''){ +//Request for total rows + $sql = 'SELECT count(*) as count FROM discounts '.$whereclause.''; +} +elseif(isset($criterias['discount_category_id']) && $criterias['discount_category_id'] !=''){ + $sql ='SELECT c.name, c.rowID FROM discounts d JOIN categories c ON FIND_IN_SET(c.rowID, d.category_ids) '.$whereclause; +} +elseif(isset($criterias['discount_products_id']) && $criterias['discount_products_id'] !=''){ + $sql ='SELECT p.productname, p.rowID FROM discounts d JOIN products p ON FIND_IN_SET(p.rowID, d.product_ids) '.$whereclause; +} +else { + //SQL for Paging + $sql = 'SELECT d.*, GROUP_CONCAT(DISTINCT p.productname) product_names, GROUP_CONCAT(DISTINCT c.name) category_names FROM discounts d LEFT JOIN products p ON FIND_IN_SET(p.rowID, d.product_ids) LEFT JOIN categories c ON FIND_IN_SET(c.rowID, d.category_ids) '.$whereclause.' GROUP BY d.id, d.category_ids, d.product_ids, d.discount_code, d.discount_type, d.discount_type, d.discount_value, d.start_date, d.end_date LIMIT :page,:num_products'; +} +$stmt = $pdo->prepare($sql); + +//Bind to query +if (str_contains($whereclause, ':condition')){ + $stmt->bindValue('condition', $condition, PDO::PARAM_STR); +} + +if (!empty($criterias)){ + foreach ($criterias as $key => $value){ + $key_condition = ':'.$key; + if (str_contains($whereclause, $key_condition)){ + if ($key == 'search'){ + $search_value = '%'.$value.'%'; + $stmt->bindValue($key, $search_value, PDO::PARAM_STR); + } + else { + $stmt->bindValue($key, $value, PDO::PARAM_STR); + } + } + } +} + +//Add paging details +if(isset($criterias['totals']) && $criterias['totals']==''){ + $stmt->execute(); + $messages = $stmt->fetch(); + $messages = $messages[0]; +} else if ((isset($criterias['discount_category_id']) && $criterias['discount_category_id'] !='') || (isset($criterias['discount_products_id']) && $criterias['discount_products_id'] !='')){ + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} +else { + $current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1; + $stmt->bindValue('page', ($current_page - 1) * $page_rows_discounts, PDO::PARAM_INT); + $stmt->bindValue('num_products', $page_rows_discounts, PDO::PARAM_INT); + + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} + +//------------------------------------------ +//JSON_ENCODE +//------------------------------------------ +$messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + +//Send results +echo $messages; + +?> \ No newline at end of file diff --git a/api/v2/get/invoice.php b/api/v2/get/invoice.php new file mode 100644 index 0000000..c38c1f7 --- /dev/null +++ b/api/v2/get/invoice.php @@ -0,0 +1,127 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE inv.accounthierarchy like "'.$condition.'"'; + break; +} + +//NEW ARRAY +$criterias = []; +$clause = ''; + +//Check for $_GET variables and build up clause +if(isset($get_content) && $get_content!=''){ + //GET VARIABLES FROM URL + $requests = explode("&", $get_content); + //Check for keys and values + foreach ($requests as $y){ + $v = explode("=", $y); + //INCLUDE VARIABLES IN ARRAY + $criterias[$v[0]] = $v[1]; + + if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history'|| $v[0] =='success_msg'){ + //do nothing + } + else {//create clause + $clause .= ' AND inv.'.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//Define Query +if(isset($criterias['totals']) && $criterias['totals'] ==''){ +//Request for total rows + $sql = 'SELECT count(*) as count FROM invoice inv '.$whereclause.''; +} +elseif (isset($criterias['list']) && $criterias['list'] =='invoice'){ + //SQL for Paging + $sql = 'SELECT tx.*, txi.*, p.productname, inv.id as invoice, inv.created as invoice_created FROM transactions tx + left join invoice inv ON tx.id = inv.txn_id + left join transactions_items txi ON tx.id = txi.txn_id + left join products p ON p.rowID = txi.item_id '.$whereclause; +} +else { + //SQL for Paging + $sql = 'SELECT * FROM invoice inv '.$whereclause.' LIMIT :page,:num_products'; +} +$stmt = $pdo->prepare($sql); + +//Bind to query +if (str_contains($whereclause, ':condition')){ + $stmt->bindValue('condition', $condition, PDO::PARAM_STR); +} + +if (!empty($criterias)){ + foreach ($criterias as $key => $value){ + $key_condition = ':'.$key; + if (str_contains($whereclause, $key_condition)){ + if ($key == 'search'){ + $search_value = '%'.$value.'%'; + $stmt->bindValue($key, $search_value, PDO::PARAM_STR); + } + else { + $stmt->bindValue($key, $value, PDO::PARAM_STR); + } + } + } +} + +//Add paging details +if(isset($criterias['totals']) && $criterias['totals']==''){ + $stmt->execute(); + $messages = $stmt->fetch(); + $messages = $messages[0]; +} +elseif (isset($criterias['list']) && $criterias['list']=='invoice'){ + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); + $messages = transformOrderData($messages); +} +else { + $current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1; + $stmt->bindValue('page', ($current_page - 1) * $page_rows_invoice, PDO::PARAM_INT); + $stmt->bindValue('num_products', $page_rows_invoice, PDO::PARAM_INT); + + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} + +//------------------------------------------ +//JSON_ENCODE +//------------------------------------------ +$messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + +//Send results +echo $messages; + +?> \ No newline at end of file diff --git a/api/v2/get/products_categories.php b/api/v2/get/products_categories.php index 882b388..f6f5939 100644 --- a/api/v2/get/products_categories.php +++ b/api/v2/get/products_categories.php @@ -104,6 +104,10 @@ if(isset($get_content) && $get_content!=''){ //build up filter $clause .= ' AND c.filter = :'.$v[0]; } + elseif ($v[0] == 'status') { + //build up filter + $clause .= ' AND c.status = :'.$v[0]; + } else {//create clause $clause .= ' AND pc.'.$v[0].' = :'.$v[0]; } diff --git a/api/v2/get/shipping.php b/api/v2/get/shipping.php new file mode 100644 index 0000000..c2d80ea --- /dev/null +++ b/api/v2/get/shipping.php @@ -0,0 +1,155 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE accounthierarchy like "'.$condition.'"'; + break; +} + +//NEW ARRAY +$criterias = []; +$clause = ''; + +//Check for $_GET variables and build up clause +if(isset($get_content) && $get_content!=''){ + //GET VARIABLES FROM URL + $requests = explode("&", $get_content); + //Check for keys and values + foreach ($requests as $y){ + $v = explode("=", $y); + //INCLUDE VARIABLES IN ARRAY + $criterias[$v[0]] = $v[1]; + + if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history'|| $v[0] =='success_msg'){ + //do nothing + } + elseif ($v[0] == 'search') { + //build up search + $clause .= ' AND name like :'.$v[0]; + } + elseif ($v[0] == 'weight_total') { + //build up search + $clause .= ' AND weight_from <= :'.$v[0].' AND (weight_to >= :'.$v[0].' OR weight_to = 0)'; + } + elseif ($v[0] == 'price_total') { + //build up search + $clause .= ' AND price_from <= :'.$v[0].' AND (price_to >= :'.$v[0].' OR price_to = 0)'; + } + elseif ($v[0] == 'country') { + + if ($v[1] != ''){ + //CHECK IF SPECIFIC COUNTRY RECORD IS FOUND OTHERWISE CHECK FOR GLOBAL SHIPPING RECORDS + $sql = "SELECT COUNT(*) as count FROM shipping WHERE FIND_IN_SET(?, countries)"; + $stmt = $pdo->prepare($sql); + $stmt->execute([$v[1]]); + $result = $stmt->fetch(); + $result = $result[0]; + + if ($result > 0) { + $clause .= ' AND FIND_IN_SET(:'.$v[0].', countries) > 0'; + } else { + //GET ALL COUNTRIES + $clause .= ' AND countries = ""'; + } + } + else { + //GET ALL COUNTRIES + $clause .= ' AND countries = :'.$v[0]; + } + } + else {//create clause + $clause .= ' AND '.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//Define Query +if(isset($criterias['totals']) && $criterias['totals'] ==''){ +//Request for total rows + $sql = 'SELECT count(*) as count FROM shipping '.$whereclause.''; +} +elseif(isset($criterias['list']) && $criterias['list'] =='methods'){ + $sql = 'SELECT * FROM shipping '.$whereclause; +} +else { + //SQL for Paging + $sql = 'SELECT * FROM shipping '.$whereclause.' LIMIT :page,:num_products'; +} +$stmt = $pdo->prepare($sql); + +//Bind to query +if (str_contains($whereclause, ':condition')){ + $stmt->bindValue('condition', $condition, PDO::PARAM_STR); +} + +if (!empty($criterias)){ + foreach ($criterias as $key => $value){ + $key_condition = ':'.$key; + if (str_contains($whereclause, $key_condition)){ + if ($key == 'search'){ + $search_value = '%'.$value.'%'; + $stmt->bindValue($key, $search_value, PDO::PARAM_STR); + } + else { + $stmt->bindValue($key, $value, PDO::PARAM_STR); + } + } + } +} + +//Add paging details +if(isset($criterias['totals']) && $criterias['totals']==''){ + $stmt->execute(); + $messages = $stmt->fetch(); + $messages = $messages[0]; +} +elseif(isset($criterias['list']) && $criterias['list']=='methods'){ + $stmt->execute(); + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} +else { + $current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1; + $stmt->bindValue('page', ($current_page - 1) * $page_rows_shipping, PDO::PARAM_INT); + $stmt->bindValue('num_products', $page_rows_shipping, PDO::PARAM_INT); + + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} + +//------------------------------------------ +//JSON_ENCODE +//------------------------------------------ +$messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + +//Send results +echo $messages; + +?> \ No newline at end of file diff --git a/api/v2/get/taxes.php b/api/v2/get/taxes.php new file mode 100644 index 0000000..8a845b2 --- /dev/null +++ b/api/v2/get/taxes.php @@ -0,0 +1,115 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE accounthierarchy like "'.$condition.'"'; + break; +} + +//NEW ARRAY +$criterias = []; +$clause = ''; + +//Check for $_GET variables and build up clause +if(isset($get_content) && $get_content!=''){ + //GET VARIABLES FROM URL + $requests = explode("&", $get_content); + //Check for keys and values + foreach ($requests as $y){ + $v = explode("=", $y); + //INCLUDE VARIABLES IN ARRAY + $criterias[$v[0]] = $v[1]; + + if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history'|| $v[0] =='success_msg'){ + //do nothing + } + elseif ($v[0] == 'search') { + //build up search + $clause .= ' AND name like :'.$v[0]; + } + else {//create clause + $clause .= ' AND '.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//Define Query +if(isset($criterias['totals']) && $criterias['totals'] ==''){ +//Request for total rows + $sql = 'SELECT count(*) as count FROM taxes '.$whereclause.''; +} +else { + //SQL for Paging + $sql = 'SELECT * FROM taxes '.$whereclause; +} +$stmt = $pdo->prepare($sql); + +//Bind to query +if (str_contains($whereclause, ':condition')){ + $stmt->bindValue('condition', $condition, PDO::PARAM_STR); +} + +if (!empty($criterias)){ + foreach ($criterias as $key => $value){ + $key_condition = ':'.$key; + if (str_contains($whereclause, $key_condition)){ + if ($key == 'search'){ + $search_value = '%'.$value.'%'; + $stmt->bindValue($key, $search_value, PDO::PARAM_STR); + } + else { + $stmt->bindValue($key, $value, PDO::PARAM_STR); + } + } + } +} + +//Add paging details +if(isset($criterias['totals']) && $criterias['totals']==''){ + $stmt->execute(); + $messages = $stmt->fetch(); + $messages = $messages[0]; +} +else { + + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} + +//------------------------------------------ +//JSON_ENCODE +//------------------------------------------ +$messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + +//Send results +echo $messages; + +?> \ No newline at end of file diff --git a/api/v2/get/transactions.php b/api/v2/get/transactions.php new file mode 100644 index 0000000..935039b --- /dev/null +++ b/api/v2/get/transactions.php @@ -0,0 +1,118 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE tx.accounthierarchy like "'.$condition.'"'; + break; +} + +//NEW ARRAY +$criterias = []; +$clause = ''; + +//Check for $_GET variables and build up clause +if(isset($get_content) && $get_content!=''){ + //GET VARIABLES FROM URL + $requests = explode("&", $get_content); + //Check for keys and values + foreach ($requests as $y){ + $v = explode("=", $y); + //INCLUDE VARIABLES IN ARRAY + $criterias[$v[0]] = $v[1]; + + if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history'|| $v[0] =='success_msg'){ + //do nothing + } + elseif ($v[0] == 'search') { + //build up search + $clause .= ' AND tx.name like :'.$v[0]; + } + else {//create clause + $clause .= ' AND tx.'.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//Define Query +if(isset($criterias['totals']) && $criterias['totals'] ==''){ +//Request for total rows + $sql = 'SELECT count(*) as count FROM transactions '.$whereclause.''; +} +else { + //SQL for Paging + $sql = 'SELECT * FROM transactions tx '.$whereclause.' LIMIT :page,:num_products'; +} +$stmt = $pdo->prepare($sql); + +//Bind to query +if (str_contains($whereclause, ':condition')){ + $stmt->bindValue('condition', $condition, PDO::PARAM_STR); +} + +if (!empty($criterias)){ + foreach ($criterias as $key => $value){ + $key_condition = ':'.$key; + if (str_contains($whereclause, $key_condition)){ + if ($key == 'search'){ + $search_value = '%'.$value.'%'; + $stmt->bindValue($key, $search_value, PDO::PARAM_STR); + } + else { + $stmt->bindValue($key, $value, PDO::PARAM_STR); + } + } + } +} + +//Add paging details +if(isset($criterias['totals']) && $criterias['totals']==''){ + $stmt->execute(); + $messages = $stmt->fetch(); + $messages = $messages[0]; +} +else { + $current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1; + $stmt->bindValue('page', ($current_page - 1) * $page_rows_transactions, PDO::PARAM_INT); + $stmt->bindValue('num_products', $page_rows_transactions, PDO::PARAM_INT); + + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} + +//------------------------------------------ +//JSON_ENCODE +//------------------------------------------ +$messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + +//Send results +echo $messages; + +?> \ No newline at end of file diff --git a/api/v2/get/transactions_items.php b/api/v2/get/transactions_items.php new file mode 100644 index 0000000..f63f05c --- /dev/null +++ b/api/v2/get/transactions_items.php @@ -0,0 +1,118 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE accounthierarchy like "'.$condition.'"'; + break; +} + +//NEW ARRAY +$criterias = []; +$clause = ''; + +//Check for $_GET variables and build up clause +if(isset($get_content) && $get_content!=''){ + //GET VARIABLES FROM URL + $requests = explode("&", $get_content); + //Check for keys and values + foreach ($requests as $y){ + $v = explode("=", $y); + //INCLUDE VARIABLES IN ARRAY + $criterias[$v[0]] = $v[1]; + + if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history'|| $v[0] =='success_msg'){ + //do nothing + } + elseif ($v[0] == 'search') { + //build up search + $clause .= ' AND name like :'.$v[0]; + } + else {//create clause + $clause .= ' AND tai.'.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//Define Query +if(isset($criterias['totals']) && $criterias['totals'] ==''){ +//Request for total rows + $sql = 'SELECT count(*) as count FROM transactions_items tai '.$whereclause.''; +} +else { + //SQL for Paging + $sql = 'SELECT ta.*, tai.* FROM transactions ta left join transactions_items tai ON ta.id = tai.txn_id '.$whereclause; +} +$stmt = $pdo->prepare($sql); + +//Bind to query +if (str_contains($whereclause, ':condition')){ + $stmt->bindValue('condition', $condition, PDO::PARAM_STR); +} + +if (!empty($criterias)){ + foreach ($criterias as $key => $value){ + $key_condition = ':'.$key; + if (str_contains($whereclause, $key_condition)){ + if ($key == 'search'){ + $search_value = '%'.$value.'%'; + $stmt->bindValue($key, $search_value, PDO::PARAM_STR); + } + else { + $stmt->bindValue($key, $value, PDO::PARAM_STR); + } + } + } +} + +//Add paging details +if(isset($criterias['totals']) && $criterias['totals']==''){ + $stmt->execute(); + $messages = $stmt->fetch(); + $messages = $messages[0]; +} +else { + //$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1; + //$stmt->bindValue('page', ($current_page - 1) * $page_rows_transactions, PDO::PARAM_INT); + //$stmt->bindValue('num_products', $page_rows_transactions, PDO::PARAM_INT); + + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); +} + +//------------------------------------------ +//JSON_ENCODE +//------------------------------------------ +$messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + +//Send results +echo $messages; + +?> \ No newline at end of file diff --git a/api/v2/post/checkout.php b/api/v2/post/checkout.php new file mode 100644 index 0000000..11dccfe --- /dev/null +++ b/api/v2/post/checkout.php @@ -0,0 +1,52 @@ + $post_content['cart'], + "selected_country" => $post_content['checkout_input']['selected_country'], + "selected_shipping_method" => $post_content['checkout_input']['selected_shipment_method'], + "business_type" => $post_content['checkout_input']['business_type'], + "discount_code" => $post_content['checkout_input']['discount_code'] + ]; + + //Initialize calculator + $calculator = new ShoppingCartCalculator( + $checkout_input['products_validated'], + $checkout_input['selected_country'], + $checkout_input['selected_shipping_method'], + $checkout_input['business_type'], + $checkout_input['discount_code'], + $pdo + ); + + // Get all calculations in one array + $messages = $calculator->calculateTotals(); + + //------------------------------------------ + //JSON_ENCODE + //------------------------------------------ + $messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + + //Send results + echo $messages; +} +else +{ + //------------------------------------------ + // Payload not correct + //------------------------------------------ + http_response_code(400); // Payload not correct +} +?> \ No newline at end of file diff --git a/api/v2/post/discounts.php b/api/v2/post/discounts.php new file mode 100644 index 0000000..8c17d4c --- /dev/null +++ b/api/v2/post/discounts.php @@ -0,0 +1,103 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; +} + +//BUILD UP PARTNERHIERARCHY FROM USER +$partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE); + +$id = $post_content['id'] ?? ''; //check for rowID +$command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT +if (isset($post_content['delete'])){$command = 'delete';} //change command to delete + +//CREATE EMPTY STRINGS +$clause = ''; +$clause_insert =''; +$input_insert = ''; + +//IMPLODE CATEGORIES AND PRODUCTS +$post_content['category_ids'] = isset($post_content['categories']) ? implode(',', $post_content['categories']) : ''; +$post_content['product_ids'] = isset($post_content['products']) ? implode(',', $post_content['products']) : ''; +//REMOVE categories and products from post_content +if (isset($post_content['categories'])) { unset($post_content['categories']);} +if (isset($post_content['products'])) { unset($post_content['products']);} + +if ($command == 'update'){ +} +if ($command == 'insert'){ + $post_content['accounthierarchy'] = $partner_product; +} + +//CREAT NEW ARRAY AND MAP TO CLAUSE +if(isset($post_content) && $post_content!=''){ + foreach ($post_content as $key => $var){ + if ($key == 'submit' || $key == 'rowID'){ + //do nothing + } + else { + $criterias[$key] = $var; + $clause .= ' , '.$key.' = ?'; + $clause_insert .= ' , '.$key.''; + $input_insert .= ', ?'; // ? for each insert item + $execute_input[]= $var; // Build array for input + } + } +} + +//CLEAN UP INPUT +$clause = substr($clause, 2); //Clean clause - remove first comma +$clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma +$input_insert = substr($input_insert, 1); //Clean clause - remove first comma + +//QUERY AND VERIFY ALLOWED +if ($command == 'update' && isAllowed('discounts',$profile,$permission,'U') === 1){ + $sql = 'UPDATE discounts SET '.$clause.' WHERE id = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'insert' && isAllowed('discounts',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO discounts ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'delete' && isAllowed('discounts',$profile,$permission,'D') === 1){ + $sql = 'DELETE FROM discounts WHERE id = ? '.$whereclause; + $stmt = $pdo->prepare($sql); + $stmt->execute([$id]); + + //Add deletion to changelog + changelog($dbname,'discounts',$id,'Delete','Delete',$username); +} else +{ + //do nothing +} + + +?> \ No newline at end of file diff --git a/api/v2/post/invoice.php b/api/v2/post/invoice.php new file mode 100644 index 0000000..b229643 --- /dev/null +++ b/api/v2/post/invoice.php @@ -0,0 +1,121 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; +} + +//SET PARAMETERS FOR QUERY +$id = $post_content['id'] ?? ''; //check for rowID +$command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT +if (isset($post_content['delete'])){$command = 'delete';} //change command to delete + +//CREATE EMPTY STRINGS +$clause = ''; +$clause_insert =''; +$input_insert = ''; + +//BUILD UP PARTNERHIERARCHY FROM USER +$partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE); + +//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE +if ($command == 'update'){ + +} +elseif ($command == 'insert' && (isset($post_content['txn_id']) && $post_content['txn_id'] != '')){ + + //GET RELATED TRANSACTION DETAILS + $sql = 'SELECT * FROM transactions WHERE id = ? AND payment_status = "0"'; + $stmt = $pdo->prepare($sql); + //Excute Query + $stmt->execute([$post_content['txn_id']]); + //Get results + if ($messages = $stmt->fetch(PDO::FETCH_ASSOC)) { + //ADD ADDITIONAL POST CONTENT + $post_content['payment_amount'] = $messages['payment_amount']; + $post_content['shipping_amount'] = $messages['shipping_amount']; + $post_content['discount_amount'] = $messages['discount_amount']; + $post_content['tax_amount'] = $messages['tax_amount']; + $post_content['payment_status'] = $messages['payment_status']; + $post_content['accounthierarchy'] = $partner_product; + } +} +else { + //do nothing +} + +//CREAT NEW ARRAY AND MAP TO CLAUSE +if(isset($post_content) && $post_content!=''){ + foreach ($post_content as $key => $var){ + if ($key == 'submit' || $key == 'rowID'){ + //do nothing + } + else { + $criterias[$key] = $var; + $clause .= ' , '.$key.' = ?'; + $clause_insert .= ' , '.$key.''; + $input_insert .= ', ?'; // ? for each insert item + $execute_input[]= $var; // Build array for input + } + } +} + +//CLEAN UP INPUT +$clause = substr($clause, 2); //Clean clause - remove first comma +$clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma +$input_insert = substr($input_insert, 1); //Clean clause - remove first comma + +//QUERY AND VERIFY ALLOWED +if ($command == 'update' && isAllowed('invoice',$profile,$permission,'U') === 1){ + $sql = 'UPDATE invoice SET '.$clause.' WHERE id = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'insert' && isAllowed('invoice',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO invoice ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + + //GET LAST_ID + $last_id = $pdo->lastInsertId(); + $messages = json_encode(array('invoice_id'=> $last_id), JSON_UNESCAPED_UNICODE); + //Send results + echo $messages; +} +elseif ($command == 'delete' && isAllowed('invoice',$profile,$permission,'D') === 1){ + $stmt = $pdo->prepare('DELETE FROM invoice WHERE id = ? '.$whereclause.''); + $stmt->execute([ $id ]); + + //Add deletion to changelog + changelog($dbname,'invoice',$id,'Delete','Delete',$username); +} else +{ + //do nothing +} + +?> \ No newline at end of file diff --git a/api/v2/post/placeorder.php b/api/v2/post/placeorder.php new file mode 100644 index 0000000..67acfae --- /dev/null +++ b/api/v2/post/placeorder.php @@ -0,0 +1,144 @@ + $errors + ]; + } + else { + + //CHECKOUT INPUT + $checkout_input = [ + "products_validated" => $post_content['cart'], + "selected_country" => $post_content['checkout_input']['selected_country'], + "selected_shipping_method" => $post_content['checkout_input']['selected_shipment_method'], + "business_type" => $post_content['checkout_input']['business_type'], + "discount_code" => $post_content['checkout_input']['discount_code'], + "payment_method" => $post_content['checkout_input']['payment_method'] + ]; + + //Customer details + $customer_details = [ + 'account_id' => $post_content['customer_details']['account_id'] ?? '', + 'email' => $post_content['customer_details']['email'] ?? '', + 'first_name' => $post_content['customer_details']['first_name'] ?? '', + 'last_name' => $post_content['customer_details']['last_name'] ?? '', + 'address_street' => $post_content['customer_details']['address_street'] ?? '', + 'address_city' => $post_content['customer_details']['address_city'] ?? '', + 'address_state' => $post_content['customer_details']['address_state'] ?? '', + 'address_zip' => $post_content['customer_details']['address_zip'] ?? '', + 'address_country' => $post_content['customer_details']['address_country'] ?? '', + 'address_phone' => $post_content['customer_details']['address_phone'] ?? '' + ]; + + //Initialize calculator + $calculator = new ShoppingCartCalculator( + $checkout_input['products_validated'], + $checkout_input['selected_country'], + $checkout_input['selected_shipping_method'], + $checkout_input['business_type'], + $checkout_input['discount_code'], + $pdo + ); + + //Recalculate the checkout + $products_in_cart = $calculator->calculateTotals(); + + $subtotal = $products_in_cart['totals']['subtotal']; + $shippingtotal = $products_in_cart['totals']['shippingtotal']; + $discounttotal = $products_in_cart['totals']['discounttotal']; + $taxtotal = $products_in_cart['totals']['taxtotal']; + $total = $products_in_cart['totals']['total']; + + //BUILD UP PARTNERHIERARCHY FROM USER + $partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE); + + // Generate unique transaction ID + $txn_id = strtoupper(uniqid('SC') . substr(md5(mt_rand()), 0, 5)); + + // Insert transaction header + $stmt = $pdo->prepare('INSERT INTO transactions (txn_id, payment_amount, payment_status, payer_email, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, address_phone, account_id, payment_method, shipping_method, shipping_amount, discount_amount, discount_code, tax_amount,accounthierarchy) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'); + $stmt->execute([ + $txn_id, + $total, + 0, + $customer_details['email'], + $customer_details['first_name'], + $customer_details['last_name'], + $customer_details['address_street'], + $customer_details['address_city'], + $customer_details['address_state'], + $customer_details['address_zip'], + $customer_details['address_country'], + $customer_details['address_phone'], + $customer_details['account_id'], + $checkout_input['payment_method'], + $checkout_input['selected_shipping_method'], + $shippingtotal, + $discounttotal, + $checkout_input['discount_code'], + $taxtotal, + $partner_product + ]); + // Get order ID + $transaction_id = $pdo->lastInsertId(); + + //Insert transaction items + foreach ($products_in_cart['cart_details']['products'] as $product) { + // JSON_ENCODE OPTIONS + $options = json_encode($product['options'],JSON_UNESCAPED_UNICODE) ?? ''; + // For every product in the shopping cart insert a new transaction_item + $stmt = $pdo->prepare('INSERT INTO transactions_items (txn_id, item_id, item_price, item_quantity, item_options) VALUES (?,?,?,?,?)'); + $stmt->execute([$transaction_id, $product['id'], $product['options_price'], $product['quantity'], $options]); + } + + //Return to checkout page + $messages = [ + "id" => $transaction_id, + "transaction_id" => $txn_id, + "payment_amount" => $total, + "payment_method" => $checkout_input['payment_method'], + "products_checked-out" => $products_in_cart['cart_details'], + "subtotal" => $subtotal, + "discounttotal" => $discounttotal, + "shippingtotal" => $shippingtotal, + "taxtotal" => $taxtotal, + "messages" => '', + "error" => '' + ]; + } + + //------------------------------------------ + //JSON_ENCODE + //------------------------------------------ + $messages = json_encode($messages, JSON_UNESCAPED_UNICODE); + + //Send results + echo $messages; +} +else +{ + //------------------------------------------ + // Payload not correct + //------------------------------------------ + http_response_code(400); // Payload not correct +} +?> \ No newline at end of file diff --git a/api/v2/post/shipping.php b/api/v2/post/shipping.php new file mode 100644 index 0000000..dc0b8c3 --- /dev/null +++ b/api/v2/post/shipping.php @@ -0,0 +1,99 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; +} + +//BUILD UP PARTNERHIERARCHY FROM USER +$partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE); + +$id = $post_content['id'] ?? ''; //check for rowID +$command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT +if (isset($post_content['delete'])){$command = 'delete';} //change command to delete + +//CREATE EMPTY STRINGS +$clause = ''; +$clause_insert =''; +$input_insert = ''; + +//IMPLODE CATEGORIES AND PRODUCTS +$post_content['countries'] = isset($post_content['countries']) ? implode(',', $post_content['countries']) : ''; + +if ($command == 'update'){ +} +if ($command == 'insert'){ + $post_content['accounthierarchy'] = $partner_product; +} + +//CREAT NEW ARRAY AND MAP TO CLAUSE +if(isset($post_content) && $post_content!=''){ + foreach ($post_content as $key => $var){ + if ($key == 'submit' || $key == 'rowID'){ + //do nothing + } + else { + $criterias[$key] = $var; + $clause .= ' , '.$key.' = ?'; + $clause_insert .= ' , '.$key.''; + $input_insert .= ', ?'; // ? for each insert item + $execute_input[]= $var; // Build array for input + } + } +} + +//CLEAN UP INPUT +$clause = substr($clause, 2); //Clean clause - remove first comma +$clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma +$input_insert = substr($input_insert, 1); //Clean clause - remove first comma + +//QUERY AND VERIFY ALLOWED +if ($command == 'update' && isAllowed('shipping',$profile,$permission,'U') === 1){ + $sql = 'UPDATE shipping SET '.$clause.' WHERE id = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'insert' && isAllowed('shipping',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO shipping ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'delete' && isAllowed('shipping',$profile,$permission,'D') === 1){ + $sql = 'DELETE FROM shipping WHERE id = ? '.$whereclause; + $stmt = $pdo->prepare($sql); + $stmt->execute([$id]); + + //Add deletion to changelog + changelog($dbname,'shipping',$id,'Delete','Delete',$username); +} else +{ + //do nothing +} + + +?> \ No newline at end of file diff --git a/api/v2/post/shopping_cart.php b/api/v2/post/shopping_cart.php index 6da1df1..0f2ba56 100644 --- a/api/v2/post/shopping_cart.php +++ b/api/v2/post/shopping_cart.php @@ -43,6 +43,19 @@ if (isset($post_content['product']) && $post_content['product'] != '' && isset($ $options_weight = 0; $options = $result['selected_items']; + //------------------------------------------ + // ADD Product categories + //------------------------------------------ + $cat_products = ioAPIv2('/v2/products_categories/status=1&product_id='.$product_ID,'',$clientsecret); + $cat_products = json_decode($cat_products,true); + + $cat_input = ''; + foreach($cat_products as $cat_product_id){ + $cat_input .= $cat_product_id['rowID'].','; + } + $categories = substr($cat_input,0,-1); + + $products_validated = [ 'id' => $product_in_cart['rowID'], 'meta' => @@ -50,6 +63,7 @@ if (isset($post_content['product']) && $post_content['product'] != '' && isset($ "img" => $product_in_cart['full_path'], "name" => $product_in_cart['productname'], "productcode" => $product_in_cart['productcode'], + "category_ids" => $categories ], 'quantity' => $quantity, 'options' => [$options], diff --git a/api/v2/post/transactions.php b/api/v2/post/transactions.php new file mode 100644 index 0000000..a8ea78c --- /dev/null +++ b/api/v2/post/transactions.php @@ -0,0 +1,125 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; +} + +//WEBSHOP UPDATE CAN SEND TXN_ID ONLY +if (isset($post_content['txn_id']) && $post_content['txn_id'] != '' && !isset($post_content['id'])){ + + //CHECK IF TXN_ID is send and valid + $sql = 'SELECT * FROM transactions WHERE txn_id = ?'; + $stmt = $pdo->prepare($sql); + //Excute Query + $stmt->execute([$post_content['txn_id']]); + + //Get results + if ($messages = $stmt->fetch(PDO::FETCH_ASSOC)){ + //UPDATE ID TO TXN_ID RELATED ID + $post_content['id'] = $messages['id']; + unset($post_content['txn_id']); + } +} + +//SET PARAMETERS FOR QUERY +$id = $post_content['id'] ?? ''; //check for rowID +$command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT +if (isset($post_content['delete'])){$command = 'delete';} //change command to delete + +//CHECK FOR ERRORS +$errors = validateTransactionData($post_content); + +//CREATE EMPTY STRINGS +$clause = ''; +$clause_insert =''; +$input_insert = ''; + +//BUILD UP PARTNERHIERARCHY FROM USER +$partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE); + +//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE +if ($command == 'update'){ + +} +elseif ($command == 'insert'){ + $post_content['accounthierarchy'] = $partner_product; +} +else { + //do nothing +} + +//CREAT NEW ARRAY AND MAP TO CLAUSE +if(isset($post_content) && $post_content!=''){ + foreach ($post_content as $key => $var){ + if ($key == 'submit' || $key == 'rowID'){ + //do nothing + } + else { + $criterias[$key] = $var; + $clause .= ' , '.$key.' = ?'; + $clause_insert .= ' , '.$key.''; + $input_insert .= ', ?'; // ? for each insert item + $execute_input[]= $var; // Build array for input + } + } +} + +//CLEAN UP INPUT +$clause = substr($clause, 2); //Clean clause - remove first comma +$clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma +$input_insert = substr($input_insert, 1); //Clean clause - remove first comma + +//QUERY AND VERIFY ALLOWED +if ($command == 'update' && isAllowed('transactions',$profile,$permission,'U') === 1){ + $sql = 'UPDATE transactions SET '.$clause.' WHERE id = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + + //RETURN UPDATED ID + $messages = json_encode(array('transaction_id'=> $id), JSON_UNESCAPED_UNICODE); + //Send results + echo $messages; +} +elseif ($command == 'insert' && empty($errors) && isAllowed('transactions',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO transactions ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'delete' && isAllowed('transactions',$profile,$permission,'D') === 1){ + $stmt = $pdo->prepare('DELETE FROM transactions WHERE id = ? '.$whereclause.''); + $stmt->execute([ $id ]); + + //Add deletion to changelog + changelog($dbname,'transactions',$id,'Delete','Delete',$username); +} else +{ + //do nothing +} + +?> \ No newline at end of file diff --git a/assets/functions.php b/assets/functions.php index 4f21da0..a88acaf 100644 --- a/assets/functions.php +++ b/assets/functions.php @@ -3086,4 +3086,411 @@ function calculateTotalPrice($product_data, $selected_options) { 'total_price' => $total_price, 'selected_items' => implode(', ', $selected_item_names) ]; +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// ShoppingCartCalulator ++++++++++++++ +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +class ShoppingCartCalculator { + private $products; + private $selected_country; + private $selected_shipping_method; + private $business_type; + private $discount_code; + private $db; + private $discount_message; + private $tax_rate; + + public function __construct($products, $selected_country, $selected_shipping_method, $business_type, $discount_code, $db) { + $this->products = $products; + $this->selected_country = $selected_country; + $this->selected_shipping_method = $selected_shipping_method; + $this->business_type = strtolower($business_type); + $this->discount_code = $discount_code; + $this->db = $db; + $this->discount_message = ''; + $this->tax_rate = $this->getTaxRate(); + } + + public function calculateTotals() { + // Calculate basic totals + $subtotal = $this->calculateSubtotal(); + $weighttotal = $this->calculateWeightTotal(); + $shippingtotal = $this->calculateShippingTotal($subtotal, $weighttotal,$this->selected_shipping_method); + $discounttotal = $this->calculateDiscountTotal(); + $taxtotal = $this->calculateTaxTotal($subtotal - $discounttotal + $shippingtotal); + + // Calculate final total based on business type + $total = $this->calculateFinalTotal($subtotal, $shippingtotal, $discounttotal, $taxtotal); + + + return [ + 'cart_details' => [ + 'products' => $this->products, + 'selected_country' => $this->selected_country, + 'selected_shipping_method' => $this->selected_shipping_method, + 'business_type' => $this->business_type, + 'discount_code' => $this->discount_code + + ], + 'totals' => [ + 'subtotal' => number_format($subtotal, 2, '.', ''), + 'weighttotal' => number_format($weighttotal, 2, '.', ''), + 'shippingtotal' => number_format($shippingtotal, 2, '.', ''), + 'discounttotal' => number_format($discounttotal, 2, '.', ''), + 'discount_message' => $this->discount_message, + 'tax_rate' => number_format($this->tax_rate, 2, '.', '') . '%', + 'taxtotal' => number_format($taxtotal, 2, '.', ''), + 'total' => number_format($total, 2, '.', '') + ] + ]; + } + + + private function getTaxRate() { + $sql = "SELECT rate FROM taxes WHERE country = ?"; + $stmt = $this->db->prepare($sql); + $stmt->execute([$this->selected_country]); + $tax = $stmt->fetch(PDO::FETCH_ASSOC); + return $tax ? floatval($tax['rate']) : 0; + } + + private function calculateSubtotal() { + $subtotal = 0; + foreach ($this->products as $product) { + $product_price = floatval(str_replace(',', '.', $product['options_price'])); + $subtotal += $product_price * $product['quantity']; + } + return $subtotal; + } + + private function calculateWeightTotal() { + $weighttotal = 0; + foreach ($this->products as $product) { + $options_weight = floatval($product['options_weight']); + $weighttotal += $options_weight * $product['quantity']; + } + return $weighttotal; + } + + private function calculateDiscountTotal() { + if (empty($this->discount_code)) { + $this->discount_message = ''; + return 0; + } + + $current_date = date('Y-m-d H:i:s'); + + // First check if discount code exists and is valid + $sql = "SELECT * FROM discounts WHERE discount_code = ?"; + $stmt = $this->db->prepare($sql); + $stmt->execute([$this->discount_code]); + $discount = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$discount) { + $this->discount_message = 'Invalid discount code'; + return 0; + } + + // Check date validity + if ($current_date < $discount['start_date']) { + $this->discount_message = 'Discount code not yet active'; + return 0; + } + + if ($current_date > $discount['end_date']) { + $this->discount_message = 'Discount code expired'; + return 0; + } + + // Convert string of IDs to arrays + $discount_product_ids = !empty($discount['product_ids']) ? + array_map('trim', explode(',', $discount['product_ids'])) : []; + $discount_category_ids = !empty($discount['category_ids']) ? + array_map('trim', explode(',', $discount['category_ids'])) : []; + + $discounttotal = 0; + $eligible_products_found = false; + $total_eligible_price = 0; + + // Calculate total eligible price + foreach ($this->products as $product) { + if ($this->isProductEligibleForDiscount($product, $discount_product_ids, $discount_category_ids)) { + $eligible_products_found = true; + $product_price = floatval(str_replace(',', '.', $product['options_price'])) * $product['quantity']; + $total_eligible_price += $product_price; + } + } + + // Calculate discount if eligible products found + if ($eligible_products_found) { + if ($discount['discount_type'] == 1) { + // Percentage discount + $discounttotal = $total_eligible_price * ($discount['discount_value'] / 100); + } else { + // Fixed amount discount + $discounttotal = min($discount['discount_value'], $total_eligible_price); + } + + $discount_type = $discount['discount_type'] == 1 ? + $discount['discount_value'] . '% discount' : + '€' . number_format($discount['discount_value'], 2) . ' discount'; + $this->discount_message = "Discount applied successfully: " . $discount_type; + } else { + $this->discount_message = 'No eligible products for this discount code'; + $discounttotal = 0; + } + + return $discounttotal; + } + + private function isProductEligibleForDiscount($product, $discount_product_ids, $discount_category_ids) { + // If no specific products or categories are set, discount applies to all products + if (empty($discount_product_ids) && empty($discount_category_ids)) { + return true; + } + + $product_match = false; + $category_match = false; + + // Check product ID match + if (!empty($discount_product_ids)) { + $product_match = in_array($product['id'], $discount_product_ids); + + // If only product IDs are specified (no categories), return the product match result + if (empty($discount_category_ids)) { + return $product_match; + } + } else { + // If no product IDs specified, set product_match to true + $product_match = true; + } + + // Check category match + if (!empty($discount_category_ids)) { + if (isset($product['meta']['category_ids'])) { + $product_categories = is_array($product['meta']['category_ids']) ? + $product['meta']['category_ids'] : + array_map('trim', explode(',', $product['meta']['category_ids'])); + + $category_match = !empty(array_intersect($product_categories, $discount_category_ids)); + } else { + $category_match = false; + } + + // If only categories are specified (no products), return the category match result + if (empty($discount_product_ids)) { + return $category_match; + } + } else { + // If no categories specified, set category_match to true + $category_match = true; + } + + // If both product IDs and categories are specified, both must match + return $product_match && $category_match; + } + + private function calculateShippingTotal($subtotal, $weighttotal,$selected_shipping_method) { + + + //USER PROVIDED SHIPMENT METHOD + $sql = "SELECT price FROM shipping WHERE ID = ?"; + $stmt = $this->db->prepare($sql); + $stmt->execute([$this->selected_shipping_method]); + + $shipping = $stmt->fetch(PDO::FETCH_ASSOC); + return $shipping ? floatval($shipping['price']) : 0; + } + + private function calculateTaxTotal($amount_to_tax) { + $sql = "SELECT rate FROM taxes WHERE country = ?"; + $stmt = $this->db->prepare($sql); + $stmt->execute([$this->selected_country]); + $tax = $stmt->fetch(PDO::FETCH_ASSOC); + + return $tax ? ($amount_to_tax * ($tax['rate'] / 100)) : 0; + } + + private function calculateFinalTotal($subtotal, $shippingtotal, $discounttotal, $taxtotal) { + $base = $subtotal - $discounttotal + $shippingtotal; + + if ($this->business_type === 'b2c') { + // Tax is included in final price + return $base; + } else { + // Tax is added on top for B2B + return $base + $taxtotal; + } + } +} + +function validateCheckoutData($post_content) { + $errors = []; + + // Required fields for checkout input + $required_checkout_fields = [ + 'cart' => 'Products', + 'checkout_input.selected_country' => 'Country', + 'checkout_input.selected_shipment_method' => 'Shipping method', + 'checkout_input.business_type' => 'Business type', + 'checkout_input.payment_method' => 'Payment method' + ]; + + // Required fields for customer details + $required_customer_fields = [ + 'customer_details.email' => 'Email', + 'customer_details.first_name' => 'First name', + 'customer_details.last_name' => 'Last name', + 'customer_details.address_street' => 'Street address', + 'customer_details.address_city' => 'City', + 'customer_details.address_zip' => 'ZIP code', + 'customer_details.address_country' => 'Country', + 'customer_details.address_phone' => 'Phone number' + ]; + + // Validate checkout input fields + foreach ($required_checkout_fields as $field => $label) { + $keys = explode('.', $field); + if (count($keys) === 1) { + if (!isset($post_content[$keys[0]]) || empty($post_content[$keys[0]])) { + $errors[] = "$label is required"; + } + } else { + if (!isset($post_content[$keys[0]][$keys[1]]) || empty($post_content[$keys[0]][$keys[1]])) { + $errors[] = "$label is required"; + } + } + } + + // Validate customer details fields + foreach ($required_customer_fields as $field => $label) { + $keys = explode('.', $field); + if (!isset($post_content[$keys[0]][$keys[1]]) || empty($post_content[$keys[0]][$keys[1]])) { + $errors[] = "$label is required"; + } + } + + // Additional validation for email format + if (isset($post_content['customer_details']['email']) && !empty($post_content['customer_details']['email'])) { + if (!filter_var($post_content['customer_details']['email'], FILTER_VALIDATE_EMAIL)) { + $errors[] = "Invalid email format"; + } + } + + // Additional validation for phone number (basic format check) + if (isset($post_content['customer_details']['address_phone']) && !empty($post_content['customer_details']['address_phone'])) { + if (!preg_match("/^[0-9\-\(\)\/\+\s]*$/", $post_content['customer_details']['address_phone'])) { + $errors[] = "Invalid phone number format"; + } + } + + return $errors; +} + +function validateTransactionData($post_content) { + $errors = []; + + // Required fields for customer details + $required_fields = [ + 'customer_details.email' => 'Email', + 'customer_details.first_name' => 'First name', + 'customer_details.last_name' => 'Last name', + 'customer_details.address_street' => 'Street address', + 'customer_details.address_city' => 'City', + 'customer_details.address_zip' => 'ZIP code', + 'customer_details.address_country' => 'Country', + 'total.payment_amount' => 'Payment_amount', + + ]; + + // Validate customer details fields + foreach ($required_fields as $field => $label) { + $keys = explode('.', $field); + if (!isset($post_content[$keys[0]][$keys[1]]) || empty($post_content[$keys[0]][$keys[1]])) { + $errors[] = "$label is required"; + } + } + + return $errors; +} + +function getCountryNamesByIds($countries, $idString) { + // Create a lookup array where ID is the key and country name is the value + $countryMap = array_column($countries, 'country', 'id'); + + // Convert comma-separated string to array + $ids = explode(',', $idString); + + // Get country names for each ID + $countryNames = []; + foreach ($ids as $id) { + $id = trim($id); + if (isset($countryMap[$id])) { + $countryNames[] = $countryMap[$id]; + } + } + + return $countryNames; +} + +function transformOrderData(array $orderData): array { + // Initialize the result array with the first row's common data + $firstRow = $orderData[0]; + + $result = [ + 'customer' => [ + 'email' => $firstRow['payer_email'], + 'name' => $firstRow['first_name'] . ' ' . $firstRow['last_name'], + 'street' => $firstRow['address_street'], + 'zip' => $firstRow['address_zip'], + 'city' => $firstRow['address_city'], + 'country' => $firstRow['address_country'] + + ], + 'products' => [], + 'invoice' => [ + 'id' => $firstRow['invoice'], + 'created' => $firstRow['invoice_created'], + 'payment_status' => $firstRow['payment_status'] + ], + 'pricing' => [ + 'subtotal' => 0, + 'shipping_total' => $firstRow['shipping_amount'], + 'tax_total' => $firstRow['tax_amount'], + 'discount_total' => $firstRow['discount_amount'], + 'payment_amount' => $firstRow['payment_amount'] + ] + ]; + + // Process products from all rows + foreach ($orderData as $row) { + // Decode JSON string for item options + $itemOptions = json_decode($row['item_options'], true) ?? []; + + // Calculate line total + $lineTotal = floatval($row['item_price']) * intval($row['item_quantity']); + + // Add to subtotal + $result['pricing']['subtotal'] += $lineTotal; + + // Add product information + $result['products'][] = [ + 'item_id' => $row['item_id'], + 'product_name' => $row['productname'], + 'options' => $itemOptions, + 'quantity' => $row['item_quantity'], + 'price' => $row['item_price'], + 'line_total' => number_format($lineTotal, 2, '.', '') + ]; + } + + // Format monetary values + $result['pricing']['subtotal'] = number_format($result['pricing']['subtotal'], 2, '.', ''); + $result['pricing']['shipping_total'] = number_format(floatval($result['pricing']['shipping_total']), 2, '.', ''); + $result['pricing']['tax_total'] = number_format(floatval($result['pricing']['tax_total']), 2, '.', ''); + $result['pricing']['discount_total'] = number_format(floatval($result['pricing']['discount_total']), 2, '.', ''); + $result['pricing']['payment_amount'] = number_format(floatval($result['pricing']['payment_amount']), 2, '.', ''); + + return $result; } \ No newline at end of file diff --git a/discount.php b/discount.php new file mode 100644 index 0000000..7ad0af6 --- /dev/null +++ b/discount.php @@ -0,0 +1,190 @@ +'', + 'category_ids' => '', + 'product_ids' => '', + 'discount_code' => '', + 'discount_type' => 1, + 'discount_value' => 0, + 'start_date' => date('Y-m-d\TH:i'), + 'end_date' => date('Y-m-d\TH:i', strtotime('+1 month', strtotime(date('Y-m-d\TH:i')))), + 'categories' => [], + 'products' => [] +]; + +//GET ALL CATEGORIES +$api_url = '/v2/categories/'; +$categories = ioServer($api_url,''); +//Decode Payload +if (!empty($categories)){$categories = json_decode($categories,true);}else{$categories = null;} + +//GET PRODUCTS +$api_url = '/v2/products/list='; +$products = ioServer($api_url,''); +//Decode Payload +if (!empty($products)){$products = json_decode($products,true);}else{$products = null;} + +if (isset($_GET['id'])) { + + //CALL TO API FOR DISCOUNT + $api_url = '/v2/discounts/id='.$_GET['id']; + $discount = ioServer($api_url,''); + //Decode Payload + if (!empty($discount)){$discount = json_decode($discount,true);}else{$discount = null;} + $discount = $discount[0]; + + //GET CATEGORY NAMES RELATED TO DISCOUNT discount_category_id + $api_url = '/v2/discounts/discount_category_id='.$_GET['id']; + $discount_cat = ioServer($api_url,''); + //Decode Payload + if (!empty($discount_cat)){$discount['categories'] = json_decode($discount_cat,true);}else{$discount['categories']= null;} + + //GET CATEGORY NAMES RELATED TO DISCOUNT discount_products_id + $api_url = '/v2/discounts/discount_products_id='.$_GET['id']; + $discount_prod = ioServer($api_url,''); + //Decode Payload + if (!empty($discount_prod)){$discount['products'] = json_decode($discount_prod,true);}else{$discount['products']= null;} + + + if (isset($_POST['submit'])) { + //Update the discount + + //GET ALL POST DATA + $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE); + //API call + $responses = ioServer('/v2/discounts', $payload); + if ($responses === 'NOK'){ + + } else { + header('Location: index.php?page=discounts&success_msg=2'); + exit; + } + } + if (isset($_POST['delete'])) { + //GET ALL POST DATA + $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE); + var_dump($payload); + //API call + $responses = ioServer('/v2/discounts', $payload); + if ($responses === 'NOK'){ + + } else { + //Redirect and delete product + header('Location: index.php?page=discounts&success_msg=3'); + exit; + } + } + +} else { + + // Create a new discount + $page = 'Create'; + if (isset($_POST['submit'])) { + //GET ALL POST DATA + $payload = json_encode($_POST , JSON_UNESCAPED_UNICODE); + //API call + $responses = ioServer('/v2/discounts', $payload); + if ($responses === 'NOK'){ + // DO nothing + } + else { + header('Location: index.php?page=discounts&success_msg=1'); + exit; + } + } +} + +template_header('discount', 'discounts', 'manage'); + +$view =' +
'; + +//Output +echo $view; +template_footer(); +?> \ No newline at end of file diff --git a/discounts.php b/discounts.php new file mode 100644 index 0000000..f511e7d --- /dev/null +++ b/discounts.php @@ -0,0 +1,152 @@ + +'.($discounts_p ?? '').'
+'.$success_msg.'
+ +| '.($discounts_id ?? '#').' | +'.($discounts_code ?? 'Code').' | +'.($discounts_active ?? 'Active').' | +'.($discounts_category ?? 'Categories').' | +'.($discounts_product ?? 'Products').' | +'.($discounts_type ?? 'Type').' | +'.($discounts_value ?? 'Value').' | +'.($discounts_start_date ?? 'Start Date').' | +'.($discounts_end_date ?? 'End Date').' | +'.$general_actions.' | +
| '.($message_no_discounts ?? 'There are no discounts').' | +|||||||||
| '.$discount['id'].' | +'.$discount['discount_code'].' | +'.(($current_date >= strtotime($discount['start_date']) && $current_date <= strtotime($discount['end_date'])) ? $general_yes : $general_no).' | +'.($discount['category_names'] ? str_replace(',', ', ', $discount['category_names']) : $general_all ?? 'all').' | +'.($discount['product_names'] ? str_replace(',', ', ', $discount['product_names']) : $general_all ?? 'all').' | +'.$discount['discount_type'].' | +'.$discount['discount_value'].' | +'.date('Y-m-d h:ia', strtotime($discount['start_date'])).' | +'.date('Y-m-d h:ia', strtotime($discount['end_date'])).' | +'.$general_view.' | +
=$order['id']?>
+=$order['txn_id']?>
+=$order['shipping_method'] ? htmlspecialchars($order['shipping_method'], ENT_QUOTES) : '--'?>
+=$order['payment_method']?>
+=$order['payment_status']?>
+=date('F j, Y H:ia', strtotime($order['created']))?>
+=htmlspecialchars($order['discount_code'], ENT_QUOTES)?>
+=htmlspecialchars($order['a_first_name'], ENT_QUOTES)?> =htmlspecialchars($order['a_last_name'], ENT_QUOTES)?>
+=htmlspecialchars($order['a_address_street'], ENT_QUOTES)?>
+ =htmlspecialchars($order['a_address_city'], ENT_QUOTES)?>
+ =htmlspecialchars($order['a_address_state'], ENT_QUOTES)?>
+ =htmlspecialchars($order['a_address_zip'], ENT_QUOTES)?>
+ =htmlspecialchars($order['a_address_country'], ENT_QUOTES)?>
+
=htmlspecialchars($order['a_address_phone'], ENT_QUOTES)?> +
+The order is not associated with an account.
+ +=htmlspecialchars($order['payer_email'], ENT_QUOTES)?>
+=htmlspecialchars($order['first_name'], ENT_QUOTES)?> =htmlspecialchars($order['last_name'], ENT_QUOTES)?>
+=htmlspecialchars($order['address_street'], ENT_QUOTES)?>
+ =htmlspecialchars($order['address_city'], ENT_QUOTES)?>
+ =htmlspecialchars($order['address_state'], ENT_QUOTES)?>
+ =htmlspecialchars($order['address_zip'], ENT_QUOTES)?>
+ =htmlspecialchars($order['address_country'], ENT_QUOTES)?>
+
=htmlspecialchars($order['a_address_phone'], ENT_QUOTES)?> +
+| Product | +Options | +Qty | +Price | +Total | +
| There are no order items | +||||
| =$item['productcode']?> =$item['name'] ? htmlspecialchars($item['name'], ENT_QUOTES) : '(Product ' . $item['item_id'] . ')'?> | +=$item['item_options'] ? htmlspecialchars(str_replace(',', ', ', $item['item_options']), ENT_QUOTES) : '--'?> | +=$item['item_quantity']?> | +=currency_code?>=number_format($item['item_price'], 2)?> | +=currency_code?>=number_format($item['item_price']*$item['item_quantity'], 2)?> | +
| + | ||||
| Subtotal | +=currency_code?>=number_format($subtotal, 2)?> | +|||
| Shipping | +=currency_code?>=number_format($order['shipping_amount'], 2)?> | +|||
| Discount | +=currency_code?>=number_format(($order['payment_amount']+$order['shipping_amount'])-($subtotal), 2)?> | +|||
| VAT | +=currency_code?>=number_format($order['tax_amount'], 2)?> | +|||
| Total | +=currency_code?>=number_format($order['payment_amount'], 2)?> | +|||
| Giftcard | +Valid | +Value | +||
| There are no order items | +||||
| =$giftcard['discount_code']?> | +=$current_date >= strtotime($giftcard['start_date']) && $current_date <= strtotime($giftcard['end_date']) ? 'Yes' : 'No'?> | +=currency_code?>=number_format($giftcard['discount_value'], 2)?> | +||
| + | ||||
| + + | ++ + | ++ + | +
View, create, and search orders.
+=$success_msg?>
+ +| # | +Customer | +Products | +Total | +Method | +Status | +Date | +Actions | +|
| There are no orders | +||||||||
| =$i['id']?> | +=htmlspecialchars($i['first_name'], ENT_QUOTES)?> =htmlspecialchars($i['last_name'], ENT_QUOTES)?> | +=htmlspecialchars($i['payer_email'], ENT_QUOTES)?> | +=$i['total_products']?> | +=currency_code?>=number_format($i['payment_amount'], 2)?> | +=$i['payment_method']?> | +=$i['payment_status']?> | +=date('F j, Y', strtotime($i['created']))?> | +View Edit | +
'.($shipping_p ?? '').'
+'.$success_msg.'
+ +| '.($shipping_id ?? '#').' | +'.($shipping_name ?? 'name').' | +'.($shipping_type ?? 'Type').' | +'.($shipping_category ?? 'Countries').' | +'.($shipping_price ?? 'Price Range').' | +'.($shipping_weight ?? 'Weight Range').' | +'.($shipping_price_total ?? 'Total price').' | +'.$general_actions.' | +
| '.($message_no_shipping ?? 'There are no shipping').' | +|||||||
| '.$shipment['id'].' | +'.$shipment['name'].' | +'.($shipment['type'] == 0 ? ($shipping_type_standard ?? 'Standard' ) : ($shipping_type_express ?? 'Express')).' | +'.$shipping_countries.' | +'.number_format($shipment['price_from'], 2).' - '.number_format($shipment['price_to'], 2).' | +'.number_format($shipment['weight_from'], 2).' kg - '.number_format($shipment['weight_to'], 2).' kg | +=currency_code?>'.number_format($shipment['price'], 2).' | +'.$general_view.' | +
View, create, and edit taxes.
+=$success_msg?>
+ +| # | +Country | +Tax Rate | +Actions | +
| There are no taxes | +|||
| =$tax['id']?> | +=$tax['country']?> | +=$tax['rate']?>% | +Edit | +