diff --git a/api/v1/get/application.php b/api/v1/get/application.php index 562a157..80c6bc4 100644 --- a/api/v1/get/application.php +++ b/api/v1/get/application.php @@ -67,7 +67,33 @@ if(isset($get_content) && $get_content!=''){ $criterias[$v[0]] = $v[1]; if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='history' || $v[0] =='target' || $v[0] =='success_msg'){ //do nothing - } + } + elseif ($v[0] == 'serialnumber') { + //build up serialnumber + //check if multiple serialnumbers are provided + if (str_contains($v[1], ',')){ + $inputs = explode(",",$v[1]); + $new_querystring = ''; //empty querystring + $x=0; + foreach($inputs as $input){ + //create key + $new_key = $v[0].'_'.$x; + //inject new key/value to array + $criterias[$new_key] = $input; + $new_querystring .= ':'.$new_key.','; + $x++; + } + //remove obsolete last character from new_querystring + $new_querystring = substr($new_querystring,0, -1); + //add new_querystring to clause + $clause .= ' AND e.serialnumber IN ('.$new_querystring.')'; + //remove original key/value from array + unset($criterias[$v[0]]); + } + else { + $clause .= ' AND e.serialnumber IN (:'.$v[0].')'; + } + } else {//create clause $clause .= ' AND '.$v[0].' = :'.$v[0]; } @@ -155,6 +181,10 @@ switch ($action) { $sql = 'SELECT YEAR(h.created) AS year, QUARTER(h.created) AS quarter, MONTH(h.created) as month, count(h.rowID) AS count FROM history h LEFT JOIN equipment e ON h.equipmentid = e.rowID where h.type = "ServiceReport" AND NOT e.productrowid = "31" GROUP BY YEAR(h.created), QUARTER(h.created), MONTH(h.created)'; break; + case 'contract_usage_servicereports': + $sql = 'SELECT YEAR(h.created) AS year, QUARTER(h.created) AS quarter, MONTH(h.created) as month, count(h.rowID) AS count FROM history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.' GROUP BY YEAR(h.created), QUARTER(h.created), MONTH(h.created)'; + break; + case 'report_usage_firmware': $sql = 'SELECT YEAR(h.created) AS year,QUARTER(h.created) AS quarter, MONTH(h.created) as month, count(h.rowID) AS count FROM history h LEFT JOIN equipment e ON h.equipmentid=e.rowID where h.type="Firmware" AND NOT e.productrowid="31" GROUP BY YEAR(h.created),QUARTER(h.created), MONTH(h.created)'; break; diff --git a/api/v1/get/contracts.php b/api/v1/get/contracts.php index f5323df..f9053b8 100644 --- a/api/v1/get/contracts.php +++ b/api/v1/get/contracts.php @@ -8,11 +8,33 @@ defined($security_key) or exit; //Connect to DB $pdo = dbConnect($dbname); +//Get user_rights from users.php +$partner = json_decode($partnerhierarchy); + //SoldTo is empty if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + case '2': + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE accounthierarchy like :condition '; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%'; + $whereclause = 'WHERE accounthierarchy like :condition '; + break; +} + //NEW ARRAY -$whereclause =''; $criterias = []; $clause = ''; diff --git a/api/v1/get/products_versions.php b/api/v1/get/products_versions.php new file mode 100644 index 0000000..e5b0fd0 --- /dev/null +++ b/api/v1/get/products_versions.php @@ -0,0 +1,140 @@ +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 productcode like :'.$v[0]; + } + else {//create clause + $clause .= ' AND '.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//ENSURE PRODUCTROWID IS SEND +if (isset($criterias['productrowid']) && $criterias['productrowid'] != ''){ + + //CHECK IF ALLOWED TO CRUD VERSIONS + $sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause.'"; + $stmt = $pdo->prepare($sql); + $stmt->execute([$criterias['productrowid']]); + $product_data = $stmt->fetch(); + $product_owner = ($product_data['rowID'])? 1 : 0; + + //IF PRODUCT IS OWNED THEN CRUD is ALLOWED + if ($product_owner === 1 ){ + + //Define Query + if(isset($criterias['totals']) && $criterias['totals'] ==''){ + //Request for total rows + $sql = 'SELECT count(*) as count FROM products_versions '.$whereclause.''; + } + elseif (isset($criterias['list']) && $criterias['list'] =='') { + //SQL for Paging + $sql = 'SELECT * FROM products_versions '.$whereclause.''; + } + else { + //SQL for Paging + $sql = 'SELECT * FROM products_versions '.$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]; + } + elseif(isset($criterias['list']) && $criterias['list']==''){ + //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_products, PDO::PARAM_INT); + //$stmt->bindValue('num_products', $page_rows_products, PDO::PARAM_INT); + + //Excute Query + $stmt->execute(); + //Get results + $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); + } + //Encrypt results + $messages = generate_payload($messages); + + //Send results + echo $messages; + } +} +?> \ No newline at end of file diff --git a/api/v1/get/user_credentials.php b/api/v1/get/user_credentials.php index 3423300..3f98774 100644 --- a/api/v1/get/user_credentials.php +++ b/api/v1/get/user_credentials.php @@ -23,6 +23,7 @@ if ($stmt->rowCount() == 1) { $servicekey = $user_data['service']; $language = $user_data['language']; $partner = json_decode($partnerhierarchy); + $clientsecret = $user_data['userkey']; //Update Lastlogin $logindate = date('Y-m-d H:i:s'); diff --git a/api/v1/post/contracts.php b/api/v1/post/contracts.php index 17409bc..e7d5458 100644 --- a/api/v1/post/contracts.php +++ b/api/v1/post/contracts.php @@ -13,9 +13,26 @@ $post_content = json_decode(decode_payload($input),true); //SoldTo is empty if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} -//default whereclause to check if data is owned buy user +//default whereclause $whereclause = ''; +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + case '2': + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%'; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; +} + //SET PARAMETERS FOR QUERY $id = $post_content['rowID'] ?? ''; //check for rowID $command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT @@ -27,17 +44,161 @@ $clause = ''; $clause_insert =''; $input_insert = ''; +//remove blanks from array +if (isset($post_content['servicetool'])){ + $post_content['servicetool'] = array_map('trim', $post_content['servicetool']); + $post_content['servicetool'] = array_filter($post_content['servicetool'], 'strlen'); +} +if (isset($post_content['assigned_users'])){ + $post_content['assigned_users'] = array_map('trim', $post_content['assigned_users']); + $post_content['assigned_users'] = array_filter($post_content['assigned_users'], 'strlen'); +} +if ($id != ''){ + + //DEFINE ACCOUNTHIERARCHY + $stmt = $pdo->prepare('SELECT * FROM contracts WHERE rowID = ?'); + $stmt->execute([$id]); + $contract_data = $stmt->fetch(); + + $contract_old = json_decode($contract_data['accounthierarchy']); + $salesid_new = (($post_content['salesid'] != '' && $post_content['salesid'] != $contract_old->salesid)? $post_content['salesid'] : $contract_old->salesid); + $soldto_new = (($post_content['soldto'] != '' && $post_content['soldto'] != $contract_old->soldto)? $post_content['soldto'] : $contract_old->soldto); + $shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $contract_old->shipto)? $post_content['shipto'] : $contract_old->shipto); + $location_new = (($post_content['location'] != '' && $post_content['location'] != $contract_old->location)? $post_content['location'] : $contract_old->location); + + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + $account = array( + "salesid"=>$salesid_new, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + elseif ($permission == 3) { + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$contract_old->salesid, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + else { + $account = array( + "salesid"=>$contract_old->salesid, + "soldto"=>$contract_old->soldto, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + + //CHECK FOR CHANGES IN ASSIGNED_USERS + if (isset($post_content['assigned_users'])){ + $assigned_users_current = json_decode($contract_data['assigned_users'],true); + $assigned_users_new = $post_content['assigned_users']; + + // Find deleted items (items in current but not in new) + $deletedItems = array_diff($assigned_users_current, $assigned_users_new); + // Find added items (items in new but not in current) + $addedItems = array_diff($assigned_users_new, $assigned_users_current); + + //When deleted items are found + if (!empty($deletedItems)){ + foreach ($deletedItems as $item){ + //CALL TO API FOR General information + $api_url = '/v2/users/username='.$item; + $responses = ioApi($api_url,'',$clientsecret); + if (!empty($responses)){ + $response = json_decode($responses,true); + + //If response is not null update the service flag of the user + if (count($response) != 0){ + $id_removed_user = $response[0]['id']; + //Remove serviceflag from user + $sql = 'UPDATE users SET service = "" WHERE id = ? '; + $stmt = $pdo->prepare($sql); + $stmt->execute([$id_removed_user]); + } + } + } + } + + } +} +else { + //ID is empty => INSERT / NEW RECORD + if ($permission == 4){ + $account = array( + "salesid"=>$post_content['salesid'], + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } + elseif ($permission == 3){ + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + }else { + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$partner->soldto, + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } +} + +// CREATE ACCOUNTHIERARCHY JSON FROM ACCOUNT ARRAY +$post_content['accounthierarchy'] = json_encode($account, JSON_UNESCAPED_UNICODE); + if ($command == 'insert' && !isset($post_content['delete'])){ $post_content['created'] = $date; $post_content['createdby'] = $username; } -$post_content['assigned_users'] = json_encode($post_content['assigned_users'], JSON_UNESCAPED_UNICODE); +//remove blanks from array +if (isset($post_content['servicetool'])){ + $post_content['servicetool'] = json_encode($post_content['servicetool'], JSON_UNESCAPED_UNICODE); +} +if (isset($post_content['assigned_users'])){ + //Check for all users in array if exist then update service or create + foreach ($post_content['assigned_users'] as $user_assigned){ + //CALL TO API FOR General information + $responses = ioApi('/v2/users/username='.$user_assigned,'',$clientsecret); + if (!empty($responses)){ + $response = json_decode($responses,true); + + //If response is not null update the service flag of the user + if (count($response) != 0){ + $id_exist_user = $response[0]['id']; + $generate_service = bin2hex(random_bytes(25)); + //Remove serviceflag from user + $sql = 'UPDATE users SET service = ? WHERE id = ? '; + $stmt = $pdo->prepare($sql); + $stmt->execute([$generate_service,$id_exist_user]); + } else { + //Decode the account structure of the contract and create user + $ah_array = json_decode($post_content['accounthierarchy'],true); + $data = json_encode(array("username" => $user_assigned, "email"=> $user_assigned,"view" => 2 ,"settings"=>"service","service"=> 1,"userkey"=> 1, "salesid" => $ah_array['salesid'], "soldto" => $ah_array['soldto'],"shipto" => $ah_array['shipto'],"location" => $ah_array['location']), JSON_UNESCAPED_UNICODE); + //call the API to create user + ioApi('/v2/users',$data,$clientsecret); + } + } + } -//CREAT NEW ARRAY AND MAP TO CLAUSE + // UPDATE TO JSON + $post_content['assigned_users'] = json_encode($post_content['assigned_users'], JSON_UNESCAPED_UNICODE); +} + +//CREATE NEW ARRAY AND MAP TO CLAUSE if(isset($post_content) && $post_content!=''){ foreach ($post_content as $key => $var){ - if ($key == 'submit' || $key == 'delete' || $key == 'rowID'|| $key == 'id' || str_contains($key, 'old_')|| $key == 'salesid' || $key == 'soldto'){ + if ($key == 'submit' || $key == 'delete' || $key == 'rowID'|| $key == 'id' || str_contains($key, 'old_')|| $key == 'salesid' || $key == 'soldto' || $key == 'shipto' || $key == 'location'){ //do nothing } else { @@ -61,6 +222,7 @@ if ($command == 'update' && !isset($post_content['delete']) && isAllowed('contra $execute_input[] = $id; $stmt = $pdo->prepare($sql); $stmt->execute($execute_input); + } elseif ($command == 'insert' && !isset($post_content['delete']) && isAllowed('contract',$profile,$permission,'C') === 1){ $sql = 'INSERT INTO contracts ('.$clause_insert.') VALUES ('.$input_insert.')'; diff --git a/api/v1/post/equipments.php b/api/v1/post/equipments.php index 42a231e..b985e06 100644 --- a/api/v1/post/equipments.php +++ b/api/v1/post/equipments.php @@ -62,8 +62,8 @@ if ($id != ''){ $owner_equipment = (($equipment_data['createdby'] == $username)? 1 : 0); - if ($permission == 3 || $permission == 4){ - //ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD $account = array( "salesid"=>$salesid_new, "soldto"=>$soldto_new, @@ -71,7 +71,18 @@ if ($id != ''){ "location"=>$location_new, "section"=>$section_new ); - } else { + } + elseif ($permission == 3) { + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$equipment_old->salesid, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new, + "section"=>$section_new + ); + } + else { $account = array( "salesid"=>$equipment_old->salesid, "soldto"=>$equipment_old->soldto, @@ -83,7 +94,7 @@ if ($id != ''){ } else { //ID is empty => INSERT / NEW RECORD - if ($permission == 3 || $permission == 4){ + if ($permission == 4){ $account = array( "salesid"=>$post_content['salesid'], "soldto"=>$post_content['soldto'], @@ -92,7 +103,17 @@ else { "section"=>$post_content['section'] ); - } else { + } + elseif ($permission == 3){ + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'], + "section"=>$post_content['section'] + + ); + }else { $account = array( "salesid"=>$partner->salesid, "soldto"=>$partner->soldto, diff --git a/api/v1/post/products_versions.php b/api/v1/post/products_versions.php new file mode 100644 index 0000000..beda5a3 --- /dev/null +++ b/api/v1/post/products_versions.php @@ -0,0 +1,105 @@ +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; +} + +//ENSURE PRODUCTROWID IS SEND +if (isset($post_content['productrowid']) && $post_content['productrowid'] != ''){ + + //CHECK IF ALLOWED TO CRUD VERSIONS + $sql = 'SELECT * FROM products WHERE rowID = ? '.$whereclause.''; + $stmt = $pdo->prepare($sql); + $stmt->execute([$post_content['productrowid']]); + $product_data = $stmt->fetch(); + $product_owner = ($product_data['rowID'])? 1 : 0; + + //IF PRODUCT IS OWNED THEN CRUD is ALLOWED + if ($product_owner === 1 ){ + //SET PARAMETERS FOR QUERY + $id = $post_content['rowID'] ?? ''; //check for rowID + $command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT + if (isset($post_content['delete'])){$command = 'delete';} //change command to delete + $date = date('Y-m-d H:i:s'); + + //CREATE EMPTY STRINGS + $clause = ''; + $clause_insert =''; + $input_insert = ''; + + if ($command == 'insert'){ + $post_content['created'] = $date; + $post_content['createdby'] = $username; + } + + //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('products_versions',$profile,$permission,'U') === 1){ + $sql = 'UPDATE products_versions SET '.$clause.' WHERE rowID = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + } + elseif ($command == 'insert' && isAllowed('products_versions',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO products_versions ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + } + elseif ($command == 'delete' && isAllowed('products_versions',$profile,$permission,'D') === 1){ + $stmt = $pdo->prepare('DELETE FROM products_versions WHERE rowID = ? '.$whereclause.''); + $stmt->execute([ $id ]); + + //Add deletion to changelog + changelog($dbname,'products_versions',$id,'Delete','Delete',$username); + } else + { + //do nothing + } + } +} +?> \ No newline at end of file diff --git a/api/v1/post/users.php b/api/v1/post/users.php index 2c898fd..2730789 100644 --- a/api/v1/post/users.php +++ b/api/v1/post/users.php @@ -14,7 +14,7 @@ $owner_user = 0; //SoldTo is empty if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} -//default whereclause to check if data is owned buy user +//default whereclause to check if data is owned by user $whereclause = ''; switch ($permission) { @@ -35,7 +35,7 @@ switch ($permission) { } //SET PARAMETERS FOR QUERY -$id = $post_content['id'] ?? ''; //check for rowID +$id = (isset($post_content['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 if (isset($post_content['reset'])){$command = 'reset';} //change command to reset @@ -64,15 +64,24 @@ $soldto_new = ((isset($post_content['soldto']) && $post_content['soldto'] != '' $shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $partnerhierarchy_old->shipto)? $post_content['shipto'] : $partnerhierarchy_old->shipto); $location_new = (($post_content['location'] != '' && $post_content['location'] != $partnerhierarchy_old->location)? $post_content['location'] : $partnerhierarchy_old->location); -if ($permission == 3 || $permission == 4){ - //ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD $account = array( "salesid"=>$salesid_new, "soldto"=>$soldto_new, "shipto"=>$shipto_new, "location"=>$location_new ); - } else { + }elseif ($permission == 3) { + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + else { $account = array( "salesid"=>$partner->salesid, "soldto"=>$partner->soldto, @@ -82,15 +91,25 @@ if ($permission == 3 || $permission == 4){ } } elseif ($command == 'insert') { //ID is empty => INSERT / NEW RECORD - if ($permission == 3 || $permission == 4){ - //ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD $account = array( "salesid"=>$post_content['salesid'], "soldto"=>$post_content['soldto'], "shipto"=>$post_content['shipto'], "location"=>$post_content['location'] ); - } else { + } + elseif ($permission == 3){ + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } + else { $account = array( "salesid"=>$partner->salesid, "soldto"=>$partner->soldto, @@ -124,14 +143,15 @@ $accounthierarchy = json_encode($account, JSON_UNESCAPED_UNICODE); //Create resetkey & tokens $headers = array('alg'=>'HS256','typ'=>'JWT'); $payload = array('username'=>$post_content['username'], 'exp'=>(time() + 1800)); -$post_content['service'] = ($post_content['service'] == 1) ? bin2hex(random_bytes(25)) : ''; -$post_content['userkey'] = ($post_content['userkey'] == 1) ? bin2hex(random_bytes(25)) : ''; +$post_content['service'] = (isset($post_content['service']) && $post_content['service'] == 1) ? bin2hex(random_bytes(25)) : ''; +$post_content['userkey'] = (isset($post_content['userkey']) && $post_content['userkey'] == 1) ? bin2hex(random_bytes(25)) : ''; //ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE if ($command == 'update'){ $post_content['partnerhierarchy'] = $accounthierarchy; } elseif ($command == 'insert'){ + $post_content['resetkey'] = $resetkey = generate_jwt($headers, $payload); $post_content['password'] = generate_jwt($headers, $payload); $post_content['partnerhierarchy'] = $accounthierarchy; $post_content['salesID'] = $partner->salesid; @@ -230,10 +250,6 @@ elseif ($command == 'insert' && isAllowed('user',$profile,$permission,'C') === 1 $stmt = $pdo->prepare($sql); $stmt->execute($execute_input); - //STEP 1- create resetkey - $headers = array('alg'=>'HS256','typ'=>'JWT'); - $payload = array('username'=>$post_content['username'], 'exp'=>(time() + 1800)); - $resetkey = generate_jwt($headers, $payload); //STEP 2- Send to user include_once './assets/mail/email_template_new.php'; send_mail($post_content['email'],$subject,$message,'',''); diff --git a/api/v2/authorization.php b/api/v2/authorization.php index 1f99643..c8c38b3 100644 --- a/api/v2/authorization.php +++ b/api/v2/authorization.php @@ -7,7 +7,8 @@ defined($security_key) or exit; $user_credentials = json_decode($input,true); //Connect to DB $pdo = dbConnect($dbname); -$username = $user_credentials['username'] ?? ''; +//User username or clientID +$username = (isset($user_credentials['username']))? $user_credentials['username'] : (isset($user_credentials['clientID'])? $user_credentials['clientID'] : ''); //Define Query $stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?'); //Excute Query @@ -21,8 +22,8 @@ if ($stmt->rowCount() == 1) { $user_data = $stmt->fetch(); $permission = userRights($user_data['view']); $profile = getProfile($user_data['settings'],$permission); - $password = $user_credentials['password']; - + $password = (isset($user_credentials['password']))? $user_credentials['password'] : (isset($user_credentials['clientsecret'])? $user_credentials['clientsecret'] : ''); + if ($user_data['login_count'] < 5){ if (array_key_exists('resetkey', $user_credentials)){ @@ -51,9 +52,10 @@ if ($stmt->rowCount() == 1) { //RETURN JWT AND CLIENTSECRET $user = array( - 'clientID' => $user_data['id'], + 'clientID' => $user_data['username'], 'token' => $token, - 'clientsecret' => $user_data['userkey'] + 'token_valid' => date('Y-m-d H:i:s',time() + 1800), + 'userkey' => $user_data['userkey'] ); //Reset login count after succesfull attempt diff --git a/api/v2/get/changelog.php b/api/v2/get/changelog.php index 09e3203..4f3f595 100644 --- a/api/v2/get/changelog.php +++ b/api/v2/get/changelog.php @@ -132,7 +132,7 @@ else { } //------------------------------------------ -//JSON_DECODE +//JSON_ENCODE //------------------------------------------ $messages = json_encode($messages, JSON_UNESCAPED_UNICODE); //Send results diff --git a/api/v2/get/contracts.php b/api/v2/get/contracts.php new file mode 100644 index 0000000..74cd53d --- /dev/null +++ b/api/v2/get/contracts.php @@ -0,0 +1,134 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + case '2': + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE accounthierarchy like :condition '; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%'; + $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 reference 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 contracts '.$whereclause.''; +} +elseif (isset($criterias['list']) && $criterias['list'] =='') { + //SQL for Paging + $sql = 'SELECT * FROM contracts '.$whereclause.''; +} +else { + //SQL for Paging + $sql = 'SELECT * FROM contracts '.$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']==''){ + //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_contracts, PDO::PARAM_INT); + $stmt->bindValue('num_products', $page_rows_contracts, 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/equipments.php b/api/v2/get/equipments.php index a780cfe..aee748e 100644 --- a/api/v2/get/equipments.php +++ b/api/v2/get/equipments.php @@ -11,7 +11,6 @@ $pdo = dbConnect($dbname); //Get user_rights from users.php $partner = json_decode($partnerhierarchy); - //SoldTo is empty if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} @@ -293,7 +292,7 @@ else { $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); } //------------------------------------------ -//JSON_DECODE +//JSON_EnCODE //------------------------------------------ $messages = json_encode($messages, JSON_UNESCAPED_UNICODE); //------------------------------------------ diff --git a/api/v2/get/products_versions.php b/api/v2/get/products_versions.php new file mode 100644 index 0000000..9316ecb --- /dev/null +++ b/api/v2/get/products_versions.php @@ -0,0 +1,142 @@ +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 productcode like :'.$v[0]; + } + else {//create clause + $clause .= ' AND '.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +//ENSURE PRODUCTROWID IS SEND +if (isset($criterias['productrowid']) && $criterias['productrowid'] != ''){ + + //CHECK IF ALLOWED TO CRUD VERSIONS + $sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause.'"; + $stmt = $pdo->prepare($sql); + $stmt->execute([$criterias['productrowid']]); + $product_data = $stmt->fetch(); + $product_owner = ($product_data['rowID'])? 1 : 0; + + //IF PRODUCT IS OWNED THEN CRUD is ALLOWED + if ($product_owner === 1 ){ + + //Define Query + if(isset($criterias['totals']) && $criterias['totals'] ==''){ + //Request for total rows + $sql = 'SELECT count(*) as count FROM products_versions '.$whereclause.''; + } + elseif (isset($criterias['list']) && $criterias['list'] =='') { + //SQL for Paging + $sql = 'SELECT * FROM products_versions '.$whereclause.''; + } + else { + //SQL for Paging + $sql = 'SELECT * FROM products_versions '.$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]; + } + elseif(isset($criterias['list']) && $criterias['list']==''){ + //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_products, PDO::PARAM_INT); + //$stmt->bindValue('num_products', $page_rows_products, 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/users.php b/api/v2/get/users.php new file mode 100644 index 0000000..1dd9496 --- /dev/null +++ b/api/v2/get/users.php @@ -0,0 +1,126 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + case '2': + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = 'WHERE partnerhierarchy like :condition '; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%'; + $whereclause = 'WHERE partnerhierarchy 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] =='success_msg'){ + //do nothing + } + elseif ($v[0] == 'search') { + //build up search + $clause .= ' AND username like :'.$v[0]; + } + elseif ($v[0] == 'partnerid') { + //check accounthierarchy related users + $clause .= ' AND partnerhierarchy like :'.$v[0]; + } + else {//create clause + $clause .= ' AND '.$v[0].' = :'.$v[0]; + } + } + if ($whereclause == '' && $clause !=''){ + $whereclause = 'WHERE '.substr($clause, 4); + } else { + $whereclause .= $clause; + } +} + +if(isset($criterias['totals']) && $criterias['totals'] ==''){ +//Request for total rows + $sql = 'SELECT count(*) as count from users '.$whereclause.''; +} +else { + //SQL for Paging + $sql = 'SELECT id,username, email, salesID, partnerhierarchy, view, created, service, settings, lastlogin, userkey, language,login_count FROM users '.$whereclause.' ORDER BY lastlogin DESC 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); + } + elseif ($key == 'partnerid'){ + $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_users, PDO::PARAM_INT); + $stmt->bindValue('num_products', $page_rows_users, 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; diff --git a/api/v2/post/contracts.php b/api/v2/post/contracts.php new file mode 100644 index 0000000..5d86d55 --- /dev/null +++ b/api/v2/post/contracts.php @@ -0,0 +1,243 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + case '2': + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%'; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; +} + +//SET PARAMETERS FOR QUERY +$id = $post_content['rowID'] ?? ''; //check for rowID +$command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT +if (isset($post_content['delete'])){$command = 'delete';} //change command to delete +$date = date('Y-m-d H:i:s'); + +//CREATE EMPTY STRINGS +$clause = ''; +$clause_insert =''; +$input_insert = ''; + +//remove blanks from array +if (isset($post_content['servicetool'])){ + $post_content['servicetool'] = array_map('trim', $post_content['servicetool']); + $post_content['servicetool'] = array_filter($post_content['servicetool'], 'strlen'); +} +if (isset($post_content['assigned_users'])){ + $post_content['assigned_users'] = array_map('trim', $post_content['assigned_users']); + $post_content['assigned_users'] = array_filter($post_content['assigned_users'], 'strlen'); +} +if ($id != ''){ + + //DEFINE ACCOUNTHIERARCHY + $stmt = $pdo->prepare('SELECT * FROM contracts WHERE rowID = ?'); + $stmt->execute([$id]); + $contract_data = $stmt->fetch(); + + $contract_old = json_decode($contract_data['accounthierarchy']); + $salesid_new = (($post_content['salesid'] != '' && $post_content['salesid'] != $contract_old->salesid)? $post_content['salesid'] : $contract_old->salesid); + $soldto_new = (($post_content['soldto'] != '' && $post_content['soldto'] != $contract_old->soldto)? $post_content['soldto'] : $contract_old->soldto); + $shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $contract_old->shipto)? $post_content['shipto'] : $contract_old->shipto); + $location_new = (($post_content['location'] != '' && $post_content['location'] != $contract_old->location)? $post_content['location'] : $contract_old->location); + + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + $account = array( + "salesid"=>$salesid_new, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + elseif ($permission == 3) { + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$contract_old->salesid, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + else { + $account = array( + "salesid"=>$contract_old->salesid, + "soldto"=>$contract_old->soldto, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + + //CHECK FOR CHANGES IN ASSIGNED_USERS + if (isset($post_content['assigned_users'])){ + $assigned_users_current = json_decode($contract_data['assigned_users'],true); + $assigned_users_new = $post_content['assigned_users']; + + // Find deleted items (items in current but not in new) + $deletedItems = array_diff($assigned_users_current, $assigned_users_new); + // Find added items (items in new but not in current) + $addedItems = array_diff($assigned_users_new, $assigned_users_current); + + //When deleted items are found + if (!empty($deletedItems)){ + foreach ($deletedItems as $item){ + //CALL TO API FOR General information + $api_url = '/v2/users/username='.$item; + $responses = ioApi($api_url,'',$clientsecret); + if (!empty($responses)){ + $response = json_decode($responses,true); + + //If response is not null update the service flag of the user + if (count($response) != 0){ + $id_removed_user = $response[0]['id']; + //Remove serviceflag from user + $sql = 'UPDATE users SET service = "" WHERE id = ? '; + $stmt = $pdo->prepare($sql); + $stmt->execute([$id_removed_user]); + } + } + } + } + + } +} +else { + //ID is empty => INSERT / NEW RECORD + if ($permission == 4){ + $account = array( + "salesid"=>$post_content['salesid'], + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } + elseif ($permission == 3){ + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + }else { + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$partner->soldto, + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } +} + +// CREATE ACCOUNTHIERARCHY JSON FROM ACCOUNT ARRAY +$post_content['accounthierarchy'] = json_encode($account, JSON_UNESCAPED_UNICODE); + +if ($command == 'insert' && !isset($post_content['delete'])){ + $post_content['created'] = $date; + $post_content['createdby'] = $username; +} + +//remove blanks from array +if (isset($post_content['servicetool'])){ + $post_content['servicetool'] = json_encode($post_content['servicetool'], JSON_UNESCAPED_UNICODE); +} +if (isset($post_content['assigned_users'])){ + //Check for all users in array if exist then update service or create + foreach ($post_content['assigned_users'] as $user_assigned){ + //CALL TO API FOR General information + $responses = ioApi('/v2/users/username='.$user_assigned,'',$clientsecret); + if (!empty($responses)){ + $response = json_decode($responses,true); + + //If response is not null update the service flag of the user + if (count($response) != 0){ + $id_exist_user = $response[0]['id']; + $generate_service = bin2hex(random_bytes(25)); + //Remove serviceflag from user + $sql = 'UPDATE users SET service = ? WHERE id = ? '; + $stmt = $pdo->prepare($sql); + $stmt->execute([$generate_service,$id_exist_user]); + } else { + //Decode the account structure of the contract and create user + $ah_array = json_decode($post_content['accounthierarchy'],true); + $data = json_encode(array("username" => $user_assigned, "email"=> $user_assigned,"view" => 2 ,"settings"=>"service","service"=> 1,"userkey"=> 1, "salesid" => $ah_array['salesid'], "soldto" => $ah_array['soldto'],"shipto" => $ah_array['shipto'],"location" => $ah_array['location']), JSON_UNESCAPED_UNICODE); + //call the API to create user + ioApi('/v2/users',$data,$clientsecret); + } + } + } + + // UPDATE TO JSON + $post_content['assigned_users'] = json_encode($post_content['assigned_users'], JSON_UNESCAPED_UNICODE); +} + +//CREATE NEW ARRAY AND MAP TO CLAUSE +if(isset($post_content) && $post_content!=''){ + foreach ($post_content as $key => $var){ + if ($key == 'submit' || $key == 'delete' || $key == 'rowID'|| $key == 'id' || str_contains($key, 'old_')|| $key == 'salesid' || $key == 'soldto' || $key == 'shipto' || $key == 'location'){ + //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' && !isset($post_content['delete']) && isAllowed('contract',$profile,$permission,'U') === 1){ + $sql = 'UPDATE contracts SET '.$clause.' WHERE rowID = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + +} +elseif ($command == 'insert' && !isset($post_content['delete']) && isAllowed('contract',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO contracts ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'delete' && isAllowed('contract',$profile,$permission,'D') === 1){ + $stmt = $pdo->prepare('DELETE FROM contracts WHERE rowID = ? '.$whereclause.''); + $stmt->execute([ $id ]); + + //Add deletion to changelog + changelog($dbname,'contracts',$id,'Delete','Delete',$username); +} else +{ + //do nothing +} + +?> \ No newline at end of file diff --git a/api/v2/post/equipments.php b/api/v2/post/equipments.php new file mode 100644 index 0000000..6c955b2 --- /dev/null +++ b/api/v2/post/equipments.php @@ -0,0 +1,248 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + case '2': + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%'; + $whereclause = ' AND accounthierarchy like "'.$condition.'"'; + break; +} + +//SET PARAMETERS FOR QUERY +$id = $post_content['rowID'] ?? ''; //check for rowID +$command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT +if (isset($post_content['delete'])){$command = 'delete';} //change command to delete +$date = date('Y-m-d H:i:s'); + +//CREATE EMPTY STRINGS +$owner_equipment = 0; +$clause = ''; +$clause_insert =''; +$input_insert = ''; + + +if ($id != ''){ + //DEFINE ACCOUNTHIERARCHY + $stmt = $pdo->prepare('SELECT * FROM equipment WHERE rowID = ?'); + $stmt->execute([$id]); + $equipment_data = $stmt->fetch(); + + $equipment_old = json_decode($equipment_data['accounthierarchy']); + + $salesid_new = (($post_content['salesid'] != '' && $post_content['salesid'] != $equipment_old->salesid)? $post_content['salesid'] : $equipment_old->salesid); + $soldto_new = (($post_content['soldto'] != '' && $post_content['soldto'] != $equipment_old->soldto)? $post_content['soldto'] : $equipment_old->soldto); + $shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $equipment_old->shipto)? $post_content['shipto'] : $equipment_old->shipto); + $location_new = (($post_content['location'] != '' && $post_content['location'] != $equipment_old->location)? $post_content['location'] : $equipment_old->location); + $section_new = (($post_content['section'] != '' && $post_content['section'] != $equipment_old->section)? $post_content['section'] : $equipment_old->section); + + $owner_equipment = (($equipment_data['createdby'] == $username)? 1 : 0); + + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + $account = array( + "salesid"=>$salesid_new, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new, + "section"=>$section_new + ); + } + elseif ($permission == 3) { + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$equipment_old->salesid, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new, + "section"=>$section_new + ); + } + else { + $account = array( + "salesid"=>$equipment_old->salesid, + "soldto"=>$equipment_old->soldto, + "shipto"=>$shipto_new, + "location"=>$location_new, + "section"=>$section_new + ); + } +} +else { + //ID is empty => INSERT / NEW RECORD + if ($permission == 4){ + $account = array( + "salesid"=>$post_content['salesid'], + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'], + "section"=>$post_content['section'] + + ); + } + elseif ($permission == 3){ + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'], + "section"=>$post_content['section'] + + ); + }else { + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$partner->soldto, + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'], + "section"=>$post_content['section'] + + ); + } +} +//CHECK IF PARTNER HAS PARTNER RECORD - IF NOT CREATE AND USE +foreach ($account as $key => $value){ + if ($key != "section"){ + //CHECK for id- pattern + if (empty($value) ||$value == '' || preg_match('/\-.*/',$value)){ + //Do Nothing + } + else { + //No partner ID found + switch ($key) { + case 'salesid': + $p_type = 'SalesID'; + break; + case 'soldto': + $p_type = 'SoldTo'; + break; + case 'shipto': + $p_type = 'ShipTo'; + break; + case 'location': + $p_type = 'Location'; + break; + } + //Create partner and push to array account + $account[$key] = createPartner($partner->salesid,$partner->soldto,$value,$p_type,$userkey); + } + } +} +// CREATE ACCOUNTHIERARCHY JSON FROM ACCOUNT ARRAY +$accounthierarchy = json_encode($account, JSON_UNESCAPED_UNICODE); + +//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE +if ($command == 'update'){ + + //RESET WARRANTY AND SERVICE DATES WHEN STATUS IS CHANGED TO SEND(3) + if (isset($post_content['status']) && $post_content['status'] == 3 && $equipment_data['status'] != 3) + { + $post_content['service_date'] = $date; + $post_content['warranty_date'] = $date; + + } + //UPDATE CHANGELOG BASED ON STATUS CHANGE + if (isset($post_content['status']) && $post_content['status'] != $equipment_data['status']) + { + changelog($dbname,'equipment',$equipment_data['rowID'],'status',$post_content['status'],$username); + } + //UPDATE CHANGELOG BASED ON ORDER_REF change + if (isset($post_content['order_ref']) && $post_content['order_ref'] != $equipment_data['order_ref']) + { + changelog($dbname,'equipment',$equipment_data['rowID'],'order_ref',$post_content['order_ref'],$username); + } + + $post_content['accounthierarchy'] = $accounthierarchy; + + //CHECK for special permissions + if (isAllowed('equipment_manage_edit',$profile,$permission,'U') === 0 && $owner_equipment === 0 ){ + $post_content['status'] = $equipment_data['status']; + $post_content['serialnumber'] = $equipment_data['serialnumber']; + $post_content['service_date'] = $equipment_data['service_date']; + $post_content['warranty_date'] = $equipment_data['warranty_date']; + } + +} +elseif ($command == 'insert'){ + $post_content['created'] = $date; + $post_content['createdby'] = $username; + $post_content['accounthierarchy'] = $accounthierarchy; + $post_content['service_date'] = $date; + $post_content['warranty_date'] = $date; +} +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' || str_contains($key, 'old_') || $key == 'salesid' || $key == 'soldto' || $key == 'shipto' || $key == 'location' || $key == 'section' || str_contains($key, 'productcode') || str_contains($key, 'productname')){ + //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('equipment_manage',$profile,$permission,'U') === 1 || isAllowed('equipments_mass_update',$profile,$permission,'U') === 1 || $owner_equipment === 1)){ + $sql = 'UPDATE equipment SET '.$clause.' WHERE rowID = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'insert' && isAllowed('equipment_manage',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO equipment ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); +} +elseif ($command == 'delete' && (isAllowed('equipment_manage',$profile,$permission,'D') === 1 || $owner_equipment === 1)){ + //delete equipment + $stmt = $pdo->prepare('DELETE FROM equipment WHERE rowID = ? '.$whereclause.''); + $stmt->execute([ $id ]); + //delete history related to equipment + $stmt = $pdo->prepare('DELETE FROM history WHERE equipmentid = ?'); + $stmt->execute([ $id ]); + //Add deletion to changelog + changelog($dbname,'equipment',$id,'Delete','Delete',$username); +} else +{ + //do nothing +} + +?> \ No newline at end of file diff --git a/api/v2/post/products_versions.php b/api/v2/post/products_versions.php new file mode 100644 index 0000000..2355dd3 --- /dev/null +++ b/api/v2/post/products_versions.php @@ -0,0 +1,105 @@ +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; +} + +//ENSURE PRODUCTROWID IS SEND +if (isset($post_content['productrowid']) && $post_content['productrowid'] != ''){ + + //CHECK IF ALLOWED TO CRUD VERSIONS + $sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause.'"; + $stmt = $pdo->prepare($sql); + $stmt->execute([$post_content['productrowid']]); + $product_data = $stmt->fetch(); + $product_owner = ($product_data['rowID'])? 1 : 0; + + //IF PRODUCT IS OWNED THEN CRUD is ALLOWED + if ($product_owner === 1 ){ + //SET PARAMETERS FOR QUERY + $id = $post_content['rowID'] ?? ''; //check for rowID + $command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT + if (isset($post_content['delete'])){$command = 'delete';} //change command to delete + $date = date('Y-m-d H:i:s'); + + //CREATE EMPTY STRINGS + $clause = ''; + $clause_insert =''; + $input_insert = ''; + + if ($command == 'insert'){ + $post_content['created'] = $date; + $post_content['createdby'] = $username; + } + + //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('products_versions',$profile,$permission,'U') === 1){ + $sql = 'UPDATE products_versions SET '.$clause.' WHERE rowID = ? '.$whereclause.''; + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + } + elseif ($command == 'insert' && isAllowed('products_versions',$profile,$permission,'C') === 1){ + $sql = 'INSERT INTO products_versions ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + } + elseif ($command == 'delete' && isAllowed('products_versions',$profile,$permission,'D') === 1){ + $stmt = $pdo->prepare('DELETE FROM products_versions WHERE rowID = ? '.$whereclause.''); + $stmt->execute([ $id ]); + + //Add deletion to changelog + changelog($dbname,'products_versions',$id,'Delete','Delete',$username); + } else + { + //do nothing + } + } +} +?> \ No newline at end of file diff --git a/api/v2/post/users.php b/api/v2/post/users.php new file mode 100644 index 0000000..f4740fd --- /dev/null +++ b/api/v2/post/users.php @@ -0,0 +1,279 @@ +soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';} + +//default whereclause to check if data is owned by user +$whereclause = ''; + +switch ($permission) { + case '4': + $whereclause = ''; + break; + case '3': + $whereclause = ''; + break; + case '2': + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search; + $whereclause = ' AND partnerhierarchy like "'.$condition.'"'; + break; + default: + $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%'; + $whereclause = ' AND partnerhierarchy like "'.$condition.'"'; + break; +} + +//SET PARAMETERS FOR QUERY +$id = (isset($post_content['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 +if (isset($post_content['reset'])){$command = 'reset';} //change command to reset +$date = date('Y-m-d H:i:s'); + +//CREATE EMPTY STRINGS +$clause = ''; +$clause_insert =''; +$input_insert = ''; + +//GET EXISTING USER DATA +if ($id != '' && $command != 'reset'){ +//Define Query +$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); +$stmt->execute([$id]); +$user_data = $stmt->fetch(); + +$owner_user = (($user_data['username'] == $username)? 1 : 0); + +$user_name_old = $user_data['username']; +$view_old = $user_data['view']; +$partnerhierarchy_old = json_decode($user_data['partnerhierarchy']); + +$salesid_new = ((isset($post_content['salesid']) && $post_content['salesid'] != '' && $post_content['salesid'] != $partnerhierarchy_old->salesid)? $post_content['salesid'] : $partnerhierarchy_old->salesid); +$soldto_new = ((isset($post_content['soldto']) && $post_content['soldto'] != '' && $post_content['soldto'] != $partnerhierarchy_old->soldto)? $post_content['soldto'] : $partnerhierarchy_old->soldto); +$shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $partnerhierarchy_old->shipto)? $post_content['shipto'] : $partnerhierarchy_old->shipto); +$location_new = (($post_content['location'] != '' && $post_content['location'] != $partnerhierarchy_old->location)? $post_content['location'] : $partnerhierarchy_old->location); + + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + $account = array( + "salesid"=>$salesid_new, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + }elseif ($permission == 3) { + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$soldto_new, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } + else { + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$partner->soldto, + "shipto"=>$shipto_new, + "location"=>$location_new + ); + } +} elseif ($command == 'insert') { + //ID is empty => INSERT / NEW RECORD + if ($permission == 4){ + //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD + $account = array( + "salesid"=>$post_content['salesid'], + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } + elseif ($permission == 3){ + //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$post_content['soldto'], + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } + else { + $account = array( + "salesid"=>$partner->salesid, + "soldto"=>$partner->soldto, + "shipto"=>$post_content['shipto'], + "location"=>$post_content['location'] + ); + } +} elseif ($id != '' && $command == 'reset'){ + //Reset user requested + //Get username + $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); + $stmt->execute([$id]); + $user_data = $stmt->fetch(); + //generate resetkey + $post_content['resetkey'] = generate_jwt($headers, $payload); + //STEP 1- create resetkey + $headers = array('alg'=>'HS256','typ'=>'JWT'); + $payload = array('username'=>$user_data['username'], 'exp'=>(time() + 1800)); + $resetkey = generate_jwt($headers, $payload); + //STEP 2- Store resetkey + $sql = 'UPDATE users SET resetkey = ? WHERE id = ? '.$whereclause.''; + $stmt = $pdo->prepare($sql); + $stmt->execute([$resetkey,$id]); + //STEP 3 - Send to user + include_once './assets/mail/email_template_reset.php'; + send_mail($user_data['email'],$subject,$message,'',''); +} + +$accounthierarchy = json_encode($account, JSON_UNESCAPED_UNICODE); + +//Create resetkey & tokens +$headers = array('alg'=>'HS256','typ'=>'JWT'); +$payload = array('username'=>$post_content['username'], 'exp'=>(time() + 1800)); +$post_content['service'] = (isset($post_content['service']) && $post_content['service'] == 1) ? bin2hex(random_bytes(25)) : ''; +$post_content['userkey'] = (isset($post_content['userkey']) && $post_content['userkey'] == 1) ? bin2hex(random_bytes(25)) : ''; + +//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE +if ($command == 'update'){ + $post_content['partnerhierarchy'] = $accounthierarchy; +} +elseif ($command == 'insert'){ + $post_content['resetkey'] = $resetkey = generate_jwt($headers, $payload); + $post_content['password'] = generate_jwt($headers, $payload); + $post_content['partnerhierarchy'] = $accounthierarchy; + $post_content['salesID'] = $partner->salesid; +} +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 == 'id' || str_contains($key, 'old_') || $key == 'salesid' || $key == 'soldto' || $key == 'shipto' || $key == 'location'){ + //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('user',$profile,$permission,'U') === 1 || $owner_user === 1)){ + $sql = 'UPDATE users SET '.$clause.' WHERE id = ? '.$whereclause.''; + + $execute_input[] = $id; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + + //Update the username in all tables when changed + if ($post_content['username'] != $user_name_old){ + $sql_like = '%'.$user_name_old.'%'; + $sql1= 'UPDATE equipment SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql2= 'UPDATE communication SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql3= 'UPDATE contracts SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql4= 'UPDATE feedback SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql5= 'UPDATE history SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql6= 'UPDATE opportunities SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql7= 'UPDATE orders SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql8= 'UPDATE products SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql_users = 'UPDATE account SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + $sql_partner = 'UPDATE partner SET createdby = REPLACE(createdby, ? , ?) WHERE createdby LIKE ?'; + + //SQL_users + $stmt = $pdo->prepare($sql_users); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL_partners + $stmt = $pdo->prepare($sql_partner); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + + $pdo = dbConnect($dbname); + //SQL1 + $stmt = $pdo->prepare($sql1); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL2 + $stmt = $pdo->prepare($sql2); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL3 + $stmt = $pdo->prepare($sql3); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL4 + $stmt = $pdo->prepare($sql4); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL5 + $stmt = $pdo->prepare($sql5); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL6 + $stmt = $pdo->prepare($sql6); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL7 + $stmt = $pdo->prepare($sql7); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + //SQL8 + $stmt = $pdo->prepare($sql8); + $stmt->execute([$user_name_old,$post_content['username'], $sql_like]); + } +} +elseif ($command == 'insert' && isAllowed('user',$profile,$permission,'C') === 1){ + + //check if user exists + $stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?'); + $stmt->execute([$post_content['username']]); + $user_exist = $stmt->fetch(); + + $exists = (isset($user_exist['username']))? 1 : 0; + if($user_exist == 0 ){ + $sql = 'INSERT INTO users ('.$clause_insert.') VALUES ('.$input_insert.')'; + $stmt = $pdo->prepare($sql); + $stmt->execute($execute_input); + + //STEP 2- Send to user + include_once './assets/mail/email_template_new.php'; + send_mail($post_content['email'],$subject,$message,'',''); + } else { + //------------------------------------------ + //JSON_ENCODE + //------------------------------------------ + $messages = json_encode($exists, JSON_UNESCAPED_UNICODE); + + //Send results + echo $messages; + } +} +elseif ($command == 'delete' && isAllowed('user',$profile,$permission,'D') === 1){ + //delete equipment + $stmt = $pdo->prepare('DELETE FROM users WHERE id = ? '.$whereclause.''); + $stmt->execute([ $id ]); + + //Add deletion to changelog + changelog($dbname,'users',$id,'Delete','Delete',$username); +} else +{ + //do nothing +} + + +?> \ No newline at end of file diff --git a/assets/functions.php b/assets/functions.php index 2e9f181..c0e8768 100644 --- a/assets/functions.php +++ b/assets/functions.php @@ -1968,20 +1968,20 @@ function changeLogVisual($totals,$details){ $totalcount += $total['total']; } - //GET SERIALNUMBERS - $url_input = ''; //used to collect serialnumber for onclick event - foreach ($details as $detail){ - $url_input .= $detail['serialnumber'].','; - } - - $view = '
+ $view = '
'; @@ -2228,4 +2228,116 @@ $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); //Excute Query $stmt->execute(); } +} +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// ML data preparations +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +function traintotalMeasurement($messages){ + +//total measurement internal array +$total_measurement = []; + +foreach ($messages as $message){ + //Cleanup input array + $dataset = json_decode($message['description'],true); + $dataset = $dataset["doubletestvalues"]; + foreach ($dataset as $measure){ + //Filter out correct measurements + if ($measure['pass'] === true){ + $measurementid = $message['equipmentid'].'-'.$message['rowID']; + $total_measurement[$measure['name']][$measurementid] = $measure['measure']; + } + } + } +return $total_measurement; +} + +function statisticalAnalyses($total_measurement){ + + //result array + $total_results = []; + + //STATISTICAL ANALYSES INTERNAL ARRAY + foreach ($total_measurement as $key => $value){ + $average = $total_results[$key]['average'] = average($value); + $median = $total_results[$key]['median'] = calculateMedian($value); + $stdev = $total_results[$key]['stdev'] = standDeviation($value); + $total_results[$key]['n'] = count($value); + + //GET STDEV -/+ + $total_results[$key]['stdev-1'] = $average - $stdev; + $total_results[$key]['stdev+1'] = $average + $stdev; + $total_results[$key]['stdev-2'] = $average - (2*$stdev); + $total_results[$key]['stdev+2'] = $average + (2*$stdev); + $total_results[$key]['stdev-3'] = $average - (3*$stdev); + $total_results[$key]['stdev+3'] = $average + (3*$stdev); + } + + return $total_results; +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// Main statiscal functions for ML +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +function standDeviation($arr) +{ + $num_of_elements = count($arr); + $variance = 0.0; + // Calculate mean using array_sum() method + $average = array_sum($arr) / $num_of_elements; + foreach($arr as $i) + { + // Sum of squares of differences between all numbers and means. + $variance += pow(($i - $average), 2); + } + return (float)sqrt($variance / $num_of_elements); +} +function average($arr) +{ + $num_of_elements = count($arr); + $average = array_sum($arr) / $num_of_elements; + return $average; +} +function calculateMedian($array) { + if (empty($array)) { + return null; + } else { + sort($array); + $lowMiddle = $array[floor((count($array) - 1) / 2)]; + $highMiddle = $array[ceil((count($array) - 1) / 2)]; + return ($lowMiddle + $highMiddle) / 2; + } +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// visual forecast for service and warranty+++++++++++++++ +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +function usageView($messages){ + + //GET TOTAL SERVICE COUNT + $totalcount = 0; + foreach ($messages as $message){ + $totalcount += $message['count']; + } + + $view = ' + Service = '.$totalcount.' +
+ +
+ '; + + return $view; } \ No newline at end of file diff --git a/contract.php b/contract.php index f75ad55..e84a037 100644 --- a/contract.php +++ b/contract.php @@ -1,223 +1,258 @@ '.$button_back.'':''; + //Check if allowed if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){ header('location: index.php'); exit; } + +//GET PARAMETERS && STORE in SESSION for FURTHER USE/NAVIGATION +$pagination_page = $_SESSION['p'] = isset($_GET['p']) ? $_GET['p'] : 1; + //PAGE Security +$page_manage = 'contract_manage'; $update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U'); -$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D'); -$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C'); - -// Default input product values -$contract = [ - 'rowID' => '', - 'type' => '', - 'status' => '', - 'accountID' => '', - 'start_date' => '', - 'duration' => '', - 'service_count' => '', - 'contract_details' => '', - 'created' => '', - 'createdby' => '', - 'billing_plan' => '', - 'pricing' => '', - 'reference' => '', - 'servicetool' => '', - 'assigned_users' => [] -]; +$update_allowed_edit = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'U'); +$delete_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'D'); +$create_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'C'); +//GET Details from URL +$GET_VALUES = urlGETdetails($_GET) ?? ''; $contract_ID = $_GET['rowID'] ?? ''; -if ($contract_ID !=''){ - $url = 'index.php?page=contract&rowID='.$contract_ID.''; -} else { - $url = 'index.php?page=contracts'; -} +//CALL TO API FOR General information +$api_url = '/v1/contracts/rowID='.$contract_ID;; +$responses = ioServer($api_url,''); +//Decode Payload +if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;} +$responses = $responses[0]; -if (isset($_GET['rowID'])) { - //CALL TO API - $api_url = '/v1/contracts/rowID='.$contract_ID; - $responses = ioServer($api_url,''); - //Decode Payload - if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;} - - $contract = json_decode(json_encode($responses[0]), true); +//------------------------------ +//Variables +//------------------------------ +$contract_status_text = 'contract_status'.$responses->status ?? ''; +$contract_type_text = 'contract_type'.$responses->type ?? ''; +$servicetools = json_decode($responses->servicetool,true) ?? ''; +$assigned_users = json_decode($responses->assigned_users,true) ?? ''; - if ($update_allowed === 1){ - if (isset($_POST['submit'])) { - //GET ALL POST DATA - $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); +//Partnerdata +$partner_data = json_decode($responses->accounthierarchy); +$salesid = getPartnerName($partner_data->salesid) ?? $not_specified; +$soldto = getPartnerName($partner_data->soldto) ?? '-'; +$shipto = getPartnerName($partner_data->shipto) ?? '-'; +$location = getPartnerName($partner_data->location) ?? '-'; - //Secure data - $payload = generate_payload($data); - - //API call - $responses = ioServer('/v1/contracts', $payload); - if ($responses === 'NOK'){ - - } else { - header('Location: index.php?page=contracts&success_msg=2'); - exit; - } - - } +// Handle success messages +if (isset($_GET['success_msg'])) { + if ($_GET['success_msg'] == 1) { + $success_msg = $message_contract_1; } - - if ($delete_allowed === 1){ - if (isset($_POST['delete'])) { - //GET ALL POST DATA - $data = json_encode($_POST , JSON_UNESCAPED_UNICODE); - //Secure data - $payload = generate_payload($data); - //API call - $responses = ioServer('/v1/contracts', $payload); - // Redirect and delete product - if ($responses === 'NOK'){ - - } else { - header('Location: index.php?page=contracts&success_msg=3'); - exit; - } - } + if ($_GET['success_msg'] == 2) { + $success_msg = $message_contract_2; } - -} else { - // Create a new product - if (isset($_POST['submit']) && $create_allowed === 1) { - //GET ALL POST DATA - $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); - //Secure data - $payload = generate_payload($data); - //API call - $responses = ioServer('/v1/contracts', $payload); - if ($responses === 'NOK'){ - - } else { - header('Location: index.php?page=contracts&success_msg=1'); - exit; - } + if ($_GET['success_msg'] == 3) { + $success_msg = $message_contract_3; } } -template_header('Contract', 'contract', 'manage'); - -$view =' -
+template_header('Contract', 'contract', 'view'); +$view = '
-

'.$contract_h2.'

- '.$button_cancel.' +

'.$responses->rowID.'

+ '.$button_cancel.' '; -if ($delete_allowed === 1){ - $view .= ''; + +//------------------------------------ +// +//------------------------------------ +if ($update_allowed_edit === 1){ + $view .= 'Edit'; } -if ($update_allowed === 1){ - $view .= ''; -} - + $view .= '
'; -$view .= '
- '.$tab1 .' - '.$tab2.' - '.$tab3.' +if (isset($success_msg)){ + $view .= '
+ +

'.$success_msg.'

+ +
'; +} + +$view .= '
'; + +$view .= '
+
+ '.($product_data ?? '').' +
+
+

'.$contract_id.'

+

'.$responses->rowID.'

+
+
+

'.$contract_status.'

+

'.$$contract_status_text.'

+
+
+

'.$contract_type.'

+

'.$$contract_type_text.'

+
+
+

'.$contract_start_date.'

+

'.$responses->start_date.'

+
+
+

'.$contract_duration.'

+

'.$responses->duration.'

+
+ '; + if ($responses->duration !='' && $responses->start_date !=''){ + $date = date('Y-m-d', strtotime('+'.$responses->duration.' months', strtotime($responses->start_date))); + + $view .= ' +
+

'.$contract_end_date.'

+

'.$date.'

+
'; + } + +$view .=' +
+'; + +$view .='
+
+ '.$view_asset_partners.' +
+
+

'.$general_salesid.'

+

'.$salesid.'

+
+
+

'.$general_soldto.'

+

'.$soldto.'

+
+
+

'.$general_shipto.'

+

'.$shipto.'

+
+
+

'.$general_location.'

+

'.$location.'

+
+
+

'.$contract_reference.'

+

'.$responses->reference.'

+
+ +
'; +$view .= '
'; + + +//Usageview + +//get all assigned serialnumbers +$url_input = ''; +foreach($servicetools as $service_tool){ + $url_input .= $service_tool.','; +} + +//Return report_usage_servicereports +$api_url = '/v1/application/type=ServiceReport&serialnumber='.substr($url_input,0,-1).'/contract_usage_servicereports'; +$contract_usage_servicereports = ioServer($api_url,''); +//Decode Payload +if (!empty($contract_usage_servicereports)){$contract_usage_servicereports = decode_payload($contract_usage_servicereports);}else{$contract_usage_servicereports = null;} + +$service_events = usageView(json_decode(json_encode($contract_usage_servicereports),true)); + +$view .= '
+
+ '.$menu_service_reports.' +
+
+ '.$service_events.' +
'; -$view .='
-
- - + +$view .= '
+
+ '.$contract_assigned_users.'
-
- - +
+ + '; + //Check for assigned users + foreach ($assigned_users as $user){ + $view .= ''; + } +$view .= ' + +
'.$user.'
-
- - -
'; - -//Define end_date based on duration -if ($contract['duration'] !='' && $contract['start_date'] !=''){ - $date = date('Y-m-d', strtotime('+'.$contract['duration'].' months', strtotime($contract['start_date']))); - - $view .= '
- - -
'; -} -$view .= '
- - -
-
- - -
-
'; - - - -//GET PARTNER DROPDOWN -$soldto_dropdown = listAccounts('accountID',$_SESSION['permission'],$contract['accountID']); - -$view .= '
-
- - '.$soldto_dropdown.' -
-
- - -
-
- '; - - -//Check for assigned users -$assigned_users = (is_string($contract['assigned_users']))? json_decode($contract['assigned_users']) : ''; - -if (is_array($assigned_users)) { - foreach ($assigned_users as $user){ - $view .= ''; - } -} else{ - $view .= ''; -} - -$view .='
- '.$contract_assigned_users_add.' -
'; - -$view .= '
-
- - - - -
-
'; + '; + +$view .= '
+
+ '. $contract_servicetool.' +
+
+ + '; + //Check for assigned tools + foreach ($servicetools as $tools){ + $view .= ''; + } +$view .= ' + +
'.$tools.'
+
+
+'; +$view .= '
+
+ '.$tab3.' +
+
+ + + + + + + + + +
'.$general_created.''.$responses->created.'
'.$general_createdby.''.$responses->createdby.'
+
+
+'; -$view .= ''; +$view .='
'; +//OUTPUT +echo $view; -//Output -echo $view; +template_footer() -template_footer()?> \ No newline at end of file +?> \ No newline at end of file diff --git a/contract_manage.php b/contract_manage.php new file mode 100644 index 0000000..10da93e --- /dev/null +++ b/contract_manage.php @@ -0,0 +1,250 @@ + '', + 'type' => '', + 'status' => '', + 'accountID' => '', + 'start_date' => '', + 'duration' => '', + 'service_count' => '', + 'contract_details' => '', + 'created' => '', + 'createdby' => '', + 'billing_plan' => '', + 'pricing' => '', + 'reference' => '', + 'servicetool' => [], + 'assigned_users' => [], + 'accounthierarchy' => $_SESSION['partnerhierarchy'] +]; + +$contract_ID = $_GET['rowID'] ?? ''; + +if ($contract_ID !=''){ + $url = 'index.php?page=contract&rowID='.$contract_ID.''; +} else { + $url = 'index.php?page=contracts'; +} + +if (isset($_GET['rowID'])) { + //CALL TO API + $api_url = '/v1/contracts/rowID='.$contract_ID; + $responses = ioServer($api_url,''); + //Decode Payload + if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;} + + $contract = json_decode(json_encode($responses[0]), true); + + if ($update_allowed === 1){ + if (isset($_POST['submit'])) { + //GET ALL POST DATA + $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); + var_dump($data); + //Secure data + $payload = generate_payload($data); + + //API call + $responses = ioServer('/v1/contracts', $payload); + if ($responses === 'NOK'){ + + } else { + header('Location: index.php?page=contract&rowID='.$contract_ID.'&success_msg=2'); + exit; + } + + } + } + + if ($delete_allowed === 1){ + if (isset($_POST['delete'])) { + //GET ALL POST DATA + $data = json_encode($_POST , JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/contracts', $payload); + // Redirect and delete product + if ($responses === 'NOK'){ + + } else { + header('Location: index.php?page=contracts&success_msg=3'); + exit; + } + } + } + +} else { + // Create a new product + if (isset($_POST['submit']) && $create_allowed === 1) { + //GET ALL POST DATA + $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/contracts', $payload); + if ($responses === 'NOK'){ + + } else { + header('Location: index.php?page=contracts&success_msg=1'); + exit; + } + } +} + +template_header('Contract', 'contract', 'manage'); + +$view =' +
+
+

'.$contract_h2.'

+ '.$button_cancel.' +'; + +if ($delete_allowed === 1){ + $view .= ''; +} +if ($update_allowed === 1){ + $view .= ''; +} + +$view .= '
'; + +$view .= ' + '; + +$view .='
+
+ + +
+
+ + +
+
+ + +
'; + +//Define end_date based on duration +if ($contract['duration'] !='' && $contract['start_date'] !=''){ + $date = date('Y-m-d', strtotime('+'.$contract['duration'].' months', strtotime($contract['start_date']))); + + $view .= '
+ + +
'; +} +$view .= '
+ + +
+
+ + +
'; + +$view .= '
+ '; + //Check for assigned servicetools +$assigned_servicetools = (empty($contract['servicetool']))? '' :json_decode($contract['servicetool'],true); + + if (!empty($assigned_servicetools || $assigned_servicetools !='')){ + foreach ($assigned_servicetools as $tool){ + $view .= ''; + } + } else { + $view .= ''; + + } +$view .='
+ '; + +$view .='
+ '; + +//Check for assigned users +$assigned_users = (empty($contract['assigned_users']))? '' :json_decode($contract['assigned_users'],true); + + if (!empty($assigned_users) || $assigned_users != ''){ + foreach ($assigned_users as $user){ + $view .= ''; + } + } else { + $view .= ''; + } + +$view .='
+ +
'; + +//GET PARTNERDATA +$partner_data = json_decode($contract['accounthierarchy']); + +//BUID UP DROPDOWNS +$salesid_dropdown = listPartner('salesid',$_SESSION['permission'],$partner_data->salesid); +$soldto_dropdown = listPartner('soldto',$_SESSION['permission'],$partner_data->soldto); +$shipto_dropdown = listPartner('shipto',$_SESSION['permission'],$partner_data->shipto); +$location_dropdown = listPartner('location',$_SESSION['permission'],$partner_data->location); + +//DISPLAY +$view .= '
+
+'; +$view .= ''; +$view .= $salesid_dropdown; +$view .= ''; +$view .= $soldto_dropdown; +$view .= ''; +$view .= $shipto_dropdown; +$view .= ''; +$view .= $location_dropdown; + +$view .= ' +
+
'; + +$view .= '
+
+ + + + + +
+
'; + + +$view .= '
'; + + +//Output +echo $view; + +template_footer()?> \ No newline at end of file diff --git a/contracts.php b/contracts.php index 3330d12..ba24d61 100644 --- a/contracts.php +++ b/contracts.php @@ -11,8 +11,8 @@ include_once './settings/settings.php'; //SET PAGE ORIGIN FOR NAVIGATION AND SECURITY +$page = $_SESSION['origin'] = 'contracts'; $prev_page = ($_SESSION['origin'] == 'equipments') ? $_SESSION['prev_origin_equipment'] : (($_SESSION['origin'] == 'account')? $_SESSION['prev_origin'] :''); -$page = 'contracts'; //create backbutton to prev_origin $back_btn_orgin = ($prev_page != '')? ''.$button_back.'':''; @@ -78,7 +78,7 @@ $view .= '
} $view .= '
- '.$button_create_contract.' + '.$button_create_contract.'
@@ -136,12 +136,15 @@ $view .= ' $type = 'contract_type'.$response->type; //calculate enddate from duration $date = date('Y-m-d', strtotime('+'.$response->duration.' months', strtotime($response->start_date))); - + + //GetPartnerDetails + $partner_data = json_decode($response->accounthierarchy); + $view .= ' '.$response->rowID.' '.(($response->status == 1)? ''.$$status:''.$$status).' - '.$response->accountID.' + '.$partner_data->soldto.' '.$$type.' '.$response->start_date.' '.$date.' diff --git a/dev.php b/dev.php index 6aec4b5..148f742 100644 --- a/dev.php +++ b/dev.php @@ -7,42 +7,92 @@ include './assets/functions.php'; include './settings/settings.php'; include './settings/config.php'; + +$tes= '40'; + +$test_r = (isset($test))? $test : (isset($test2)? $test2 : 'none'); + +echo $test_r; //Connect to DB $pdo = dbConnect($dbname); -$sql = 'SELECT description FROM history where type="Maintenance_Test" and description like "%doubletestvalues%"'; + + +//GET +$sql = 'SELECT rowID, description, equipmentid FROM history where type="Maintenance_Test" and description like "%doubletestvalues%"'; $stmt = $pdo->prepare($sql); $stmt->execute(); $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); -//total measurement internal array -$total_measurement = []; -foreach ($messages as $message){ - //Cleanup input array - $message = json_decode($message['description'],true); - $message = $message["doubletestvalues"]; - foreach ($message as $measure){ - //Filter out correct measurements - if ($measure['pass'] === true){ - $total_measurement[$measure['name']][] = $measure['measure']; +$watchlist_byproduct = []; +$watchlist_bytest = []; +$watchlist_totals = []; + +//train the model +$total_measurement = traintotalMeasurement($messages); + +//get statics on results +$total_results = statisticalAnalyses($total_measurement); + +//COMPARISON -- CHECK DEVIATIONS FROM STANDARD +foreach ($total_measurement as $measurement => $values){ + foreach($total_results as $total_result => $measured_values){ + if ($measurement == $total_result){ + foreach ($values as $id => $measured_value){ + if (($measured_value <= $total_results[$total_result]['stdev-3']) && ($measured_value >= $total_results[$total_result]['stdev+3'])){ + $watchlist_byproduct[$id][] = array( + "measurement" => $measurement, + "value" => $measured_value, + "deviation" => 3 + ); + $watchlist_bytest[$measurement][] = array( + "equipmentid" => $id, + "value" => $measured_value, + "deviation" => 3 + ); + } + elseif ((($measured_value <= $total_results[$total_result]['stdev-2']) && ($measured_value >= $total_results[$total_result]['stdev-3'])) || (($measured_value >= $total_results[$total_result]['stdev+2']) && ($measured_value <= $total_results[$total_result]['stdev+3']))){ + $watchlist_byproduct[$id][] = array( + "measurement" => $measurement, + "value" => $measured_value, + "deviation" => 2 + ); + $watchlist_bytest[$measurement][] = array( + "equipmentid" => $id, + "value" => $measured_value, + "deviation" => 2 + ); + } + elseif ((($measured_value <= $total_results[$total_result]['stdev-1']) && ($measured_value >= $total_results[$total_result]['stdev-2'])) || (($measured_value >= $total_results[$total_result]['stdev+1']) && ($measured_value <= $total_results[$total_result]['stdev+2']))){ + /*$watchlist_byproduct[$id][] = array( + "measurement" => $measurement, + "value" => $measured_value, + "deviation" => 1 + ); + $watchlist_bytest[$measurement][] = array( + "equipmentid" => $id, + "value" => $measured_value, + "deviation" => 1 + ); + */ + } + } } } } -//result array -$total_results = []; -//print "
";
-//print_r($total_measurement);
-//print "
"; - -foreach ($total_measurement as $key => $value){ - $total_results[$key]['average'] = average($value); - $total_results[$key]['median'] = calculateMedian($value); - $total_results[$key]['stdev'] = standDeviation($value); +//GET WATCHLIST SUMMARY +foreach ($watchlist_bytest as $test => $value){ + $watchlist_totals[$test]['n_deviation'] = count($value); + //calculate percentage + //$watchlist_totals[$test]['percentage'] = ($watchlist_totals[$test]['n_deviation'] / $watchlist_totals[$test]['n_total'])*100; } + print "
";
 print_r($total_results);
 print "
"; + +/*MAIN STATISCAL FUNCTION function standDeviation($arr) { $num_of_elements = count($arr); @@ -72,6 +122,6 @@ function calculateMedian($array) { return ($lowMiddle + $highMiddle) / 2; } } - +*/ ?> \ No newline at end of file diff --git a/equipments.php b/equipments.php index 67ce204..e4ae432 100644 --- a/equipments.php +++ b/equipments.php @@ -37,12 +37,13 @@ $servicedate = $_SESSION['servicedate'] = isset($_GET['servicedate']) ? '&servic $warrantydate = $_SESSION['warrantydate'] = isset($_GET['warrantydate']) ? '&warrantydate='.$_GET['warrantydate'] : ''; $partnerid = $_SESSION['partnerid'] = isset($_GET['partnerid']) ? '&partnerid='.$_GET['partnerid'] : ''; $productselected = $_SESSION['productcode'] = isset($_GET['productcode']) ? '&productcode='.$_GET['productcode'] : ''; +$serialnumber_input = $_SESSION['serialnumber'] = isset($_GET['serialnumber']) ? '&serialnumber='.$_GET['serialnumber'] : ''; //GET PARAMETERS FOR FILTERS $filter = urlGETdetailsFilter($_GET) ?? ''; // Determine the URL -$url = 'index.php?page=equipments'.$status.$search.$software.$servicedate.$warrantydate.$partnerid.$sort.$productselected; +$url = 'index.php?page=equipments'.$status.$search.$software.$servicedate.$warrantydate.$partnerid.$sort.$productselected.$serialnumber_input; //GET Details from URL $GET_VALUES = urlGETdetails($_GET) ?? ''; //CALL TO API diff --git a/product.php b/product.php index 147ad87..e87f31b 100644 --- a/product.php +++ b/product.php @@ -1,207 +1,249 @@ '.$button_back.'':''; + //Check if allowed if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){ header('location: index.php'); exit; } + +//GET PARAMETERS && STORE in SESSION for FURTHER USE/NAVIGATION +$pagination_page = $_SESSION['p'] = isset($_GET['p']) ? $_GET['p'] : 1; + //PAGE Security +$page_manage = 'product_manage'; $update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U'); -$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D'); -$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C'); +$update_allowed_edit = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'U'); +$delete_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'D'); +$create_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'C'); -// Default input product values -$product = [ - 'rowID' => '', - 'productcode' => '', - 'productname' => '', - 'productdescription' => '', - 'softwareversion' => 'v1.0', - 'created' => '', - 'createdby' => $_SESSION['username'], - 'parttype' => 1, - 'price' => '0', - 'salesflag' => 0, - 'updated' => '', - 'updatedby' => $_SESSION['username'], - 'product_category' => '', - 'status' => 1, - 'build' => 1, - 'partnerhierarchy' => '', - 'sn' =>'' -]; +//GET Details from URL +$GET_VALUES = urlGETdetails($_GET) ?? ''; -if (isset($_GET['id'])) { - // ID param exists, edit an existing product - //CALL TO API - $api_url = '/v1/products/rowID='.$_GET['id']; - $responses = ioServer($api_url,''); - //Decode Payload - if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;} - - $product = json_decode(json_encode($responses[0]), true); - - if ($update_allowed === 1){ - if (isset($_POST['file_upload'])){ - uploadProduct($_POST['productcode']); - } - if (isset($_POST['submit'])) { - //GET ALL POST DATA - $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); - //Secure data - $payload = generate_payload($data); - //API call - $responses = ioServer('/v1/products', $payload); - if ($responses === 'NOK'){ +//CALL TO API FOR General information +$api_url = '/v1/products/'.$GET_VALUES; +$responses = ioServer($api_url,''); +//Decode Payload +if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;} +$responses = $responses[0]; - } else { - header('Location: index.php?page=products&status=1&success_msg=2'); - exit; - - } - } +//CALL TO API FOR Product_versions +$api_url = '/v1/products_versions/productrowid='.$_GET['rowID']; +$product_versions = ioServer($api_url,''); +//Decode Payload +if (!empty($product_versions)){$product_versions = decode_payload($product_versions);}else{$product_versions = null;} + +//------------------------------ +//Variables +//------------------------------ +$status_text = 'prod_status_'.$responses->status ?? ''; +$product_category_text = 'product_category'.$responses->product_category ?? ''; +$parttype_text = 'part_type'.$responses->parttype ?? ''; + +// Handle success messages +if (isset($_GET['success_msg'])) { + if ($_GET['success_msg'] == 1) { + $success_msg = $message_pr_1; } - - if ($delete_allowed === 1){ - if (isset($_POST['delete'])) { - //GET ALL POST DATA - $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); - //Secure data - $payload = generate_payload($data); - //API call - $responses = ioServer('/v1/products', $payload); - if ($responses === 'NOK'){ - - } else { - // Redirect and delete product - header('Location: index.php?page=products&status=1&success_msg=3'); - exit; - } - } + if ($_GET['success_msg'] == 2) { + $success_msg = $message_pr_2; } - -} else { - // Create a new product - if (isset($_POST['submit']) && $create_allowed === 1) { - //GET ALL POST DATA - $data = json_encode($_POST , JSON_UNESCAPED_UNICODE); - //Secure data - $payload = generate_payload($data); - //API call - $responses = ioServer('/v1/products', $payload); - if ($responses === 'NOK'){ - - } - else { - header('Location: index.php?page=products&success_msg=1'); - exit; - } + if ($_GET['success_msg'] == 3) { + $success_msg = $message_pr_3; } } -template_header('Product', 'product', 'manage'); - -$view =' - +template_header('Product', 'product', 'view'); +$view = '
-

'.$product_h2.'

- '.$button_cancel.' +

'.$responses->productcode.' - '.$responses->productname.'

+ '.$button_cancel.' '; -if ($delete_allowed === 1){ - $view .= ''; + +//------------------------------------ +// +//------------------------------------ +if ($update_allowed_edit === 1){ + $view .= 'Edit'; } -if ($update_allowed === 1){ - $view .= ''; -} - + $view .= '
'; -$view .= ' - '; +if (isset($success_msg)){ + $view .= '
+ +

'.$success_msg.'

+ +
'; +} -$view .= '
-
- - - - - - - - - - - - - - - - - +$view .= '
'; + +$view .= '
+
+ '.($product_data ?? '').' +
+
+

'.$product_status.'

+

'.$$status_text.'

+
+
+

'.$product_category.'

+

'.$$product_category_text.'

+
+
+

'.$product_parttype.'

+

'.$$parttype_text.'

+
+
+

'.$product_code.'

+

'.$responses->productcode.'

+
+
+

'.$product_name.'

+

'.$responses->productname.'

+
'; + +$view .='
-
'; - - -$view .= '
-
- - - - - - -
-
'; - -$view .= '
-
- - - - - - - - -
-
'; -$view .= ''; - -$view .= '
- - - -
'; -//Output -echo $view; -template_footer()?> \ No newline at end of file +$view .='
+
+ +
'; + $picture = glob("./assets/images/products/".$responses->productcode.".{jpg,jpeg,png,gif}", GLOB_BRACE); + if (!empty($picture)){ + $view .=' +
+ +
+ '; + } +$view .=' +
+'; +$view .= '
'; +$view .= '
+
+ '.$product_description.' +
+
+ '.$responses->productdescription.' +
+
+ '; + + + +$view .= '
+
+ '.($product_version ?? '').' + + +
'; + if (!empty($product_versions)){ + $view .= ' +
+ + + + + + + + + + '; + foreach ($product_versions as $version){ + $view .= ' + + + + + '; + } + $view .= ' + +
'.$product_version_number.''.$product_version_version.''.$product_version_software .''.$general_actions.'
'.$version->rowID.''.$version->version.''.$version->software.''.$general_view.'
+
+ '; + } + +$view .= ' +
+'; + +$view .= '
+
+ '.$tab4.' +
+
+ + + + + + + + + + + + + +
'.$product_serialized.''.(($responses->sn == 1)? $enabled : $disabled).'
'.$product_sales.''.(($responses->salesflag == 1)? $enabled : $disabled).'
'.$product_build.''.(($responses->build == 1)? $enabled : $disabled).'
+
+
+'; + +$view .= '
+
+ '.$tab3.' +
+
+ + + + + + + + + + + + + + + + + +
'.$general_created.''.$responses->created.'
'.$general_createdby.''.$responses->createdby.'
'.$general_updated.''.$responses->updated.'
'.$general_updatedby.''.$responses->updatedby.'
+
+
+'; + +$view .='
'; + +//OUTPUT +echo $view; + +template_footer() + +?> \ No newline at end of file diff --git a/product_manage.php b/product_manage.php new file mode 100644 index 0000000..8ea1b2a --- /dev/null +++ b/product_manage.php @@ -0,0 +1,214 @@ + '', + 'productcode' => '', + 'productname' => '', + 'productdescription' => '', + 'softwareversion' => 'v1.0', + 'created' => '', + 'createdby' => $_SESSION['username'], + 'parttype' => 1, + 'price' => '0', + 'salesflag' => 0, + 'updated' => '', + 'updatedby' => $_SESSION['username'], + 'product_category' => '', + 'status' => 1, + 'build' => 1, + 'partnerhierarchy' => '', + 'sn' =>'' +]; + +if (isset($_GET['id'])) { + // ID param exists, edit an existing product + //CALL TO API + $api_url = '/v1/products/rowID='.$_GET['id']; + $responses = ioServer($api_url,''); + //Decode Payload + if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;} + + $product = json_decode(json_encode($responses[0]), true); + + if ($update_allowed === 1){ + if (isset($_POST['file_upload'])){ + uploadProduct($_POST['productcode']); + } + if (isset($_POST['submit'])) { + //GET ALL POST DATA + $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/products', $payload); + if ($responses === 'NOK'){ + + } else { + header('Location: index.php?page=product&rowID='.$_GET['id'].'&success_msg=2'); + exit; + + } + } + } + + if ($delete_allowed === 1){ + if (isset($_POST['delete'])) { + //GET ALL POST DATA + $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/products', $payload); + if ($responses === 'NOK'){ + + } else { + // Redirect and delete product + header('Location: index.php?page=products&success_msg=3'); + exit; + } + } + } + +} else { + // Create a new product + if (isset($_POST['submit']) && $create_allowed === 1) { + //GET ALL POST DATA + $data = json_encode($_POST , JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/products', $payload); + if ($responses === 'NOK'){ + + } + else { + header('Location: index.php?page=products&success_msg=1'); + exit; + } + } +} + +template_header('Product', 'product', 'manage'); + +$view =' +
+
+

'.$product_h2.'

+ '.$button_cancel.' +'; + +if ($delete_allowed === 1){ + $view .= ''; +} +if ($update_allowed === 1){ + $view .= ''; +} + +$view .= '
'; + +$view .= ' + '; + +$view .= '
+
+ + + + + + + + + + + + + + + + + +
+
'; + + +$view .= '
+
+ + + + + + +
+
'; + +$view .= '
+
+ + + + + + + + +
+
'; +$view .= '
'; + +$view .= '
+ + + +
+'; + +//Output +echo $view; +template_footer()?> \ No newline at end of file diff --git a/products.php b/products.php index ed7424a..8c72b16 100644 --- a/products.php +++ b/products.php @@ -8,8 +8,12 @@ defined(page_security_key) or exit; include_once './assets/functions.php'; include_once './settings/settings.php'; +//SET ORIGIN FOR NAVIGATION +$prev_page = $_SESSION['prev_origin'] ?? ''; +$page = $_SESSION['origin'] = 'products'; + //Check if allowed -if (isAllowed('products',$_SESSION['profile'],$_SESSION['permission'],'R') === 0){ +if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){ header('location: index.php'); exit; } @@ -69,7 +73,7 @@ $view .= '
} $view .= '
- '.$button_create_product.' + '.$button_create_product.'
@@ -130,7 +134,7 @@ $view .= ' '.(($picture)?'' : '').' '.$response->productname.' - '.$general_view .' + '.$general_view .' '; } diff --git a/products_versions.php b/products_versions.php new file mode 100644 index 0000000..6f1a69d --- /dev/null +++ b/products_versions.php @@ -0,0 +1,160 @@ + '', + 'productrowid' => '', + 'status' => '', + 'version' => '', + 'software' => '', + 'created' => '', + 'createdby' => $_SESSION['username'], + 'measurement' => '', +]; + +//productrowid is required by api +$productrowid = $_GET['productrowid'] ?? ''; + +if (isset($_GET['rowID'])) { + // ID param exists, edit an existing product + //CALL TO API + $api_url = '/v1/products_versions/rowID='.$_GET['rowID'].'&productrowid='.$productrowid; + $responses = ioServer($api_url,''); + + //Decode Payload + if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;} + + $products_versions = json_decode(json_encode($responses[0]), true); + + + if ($update_allowed === 1){ + if (isset($_POST['submit'])) { + //GET ALL POST DATA + $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/products_versions', $payload); + if ($responses === 'NOK'){ + + } else { + header('Location: index.php?page=product&rowID='.$productrowid.'&success_msg=2'); + exit; + + } + } + } + + if ($delete_allowed === 1){ + if (isset($_POST['delete'])) { + //GET ALL POST DATA + $data = json_encode($_POST, JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/products_versions', $payload); + if ($responses === 'NOK'){ + + } else { + // Redirect and delete product + header('Location: index.php?page=product&rowID='.$productrowid.'&success_msg=3'); + exit; + } + } + } + +} else { + // Create a new product + if (isset($_POST['submit']) && $create_allowed === 1) { + //GET ALL POST DATA + $data = json_encode($_POST , JSON_UNESCAPED_UNICODE); + //Secure data + $payload = generate_payload($data); + //API call + $responses = ioServer('/v1/products_versions', $payload); + if ($responses === 'NOK'){ + + } + else { + header('Location: index.php?page=product&rowID='.$productrowid.'&success_msg=1'); + exit; + } + } +} + +template_header('Products versions', 'products_versions', 'manage'); + +$view =' + +
+

'.$product_version_version.'

+ '.$button_cancel.' +'; + +if ($delete_allowed === 1){ + $view .= ''; +} +if ($update_allowed === 1){ + $view .= ''; +} + +$view .= '
'; + +$view .= ' + '; + +$view .= '
+
+ + + + + + + + '; + + if (isset($_GET['rowID']) && $_GET['rowID'] !=''){ + $view .= ' + + + '; + } +$view .= ' + + +
+
'; + +$view .= '
+
+ + + + +
+
'; +$view .= ''; + +//Output +echo $view; +template_footer() +?> \ No newline at end of file diff --git a/report_build.php b/report_build.php index c371e99..4b8420e 100644 --- a/report_build.php +++ b/report_build.php @@ -34,9 +34,9 @@ if (!empty($query_total_sfg)){$query_total_sfg = decode_payload($query_total_sfg //Return FINISH GOODS from API $api_url = '/v1/equipments/productrowid=0&status=2&totals='; -$query_total_sfg = ioServer($api_url,''); +$query_total_fg = ioServer($api_url,''); //Decode Payload -if (!empty($query_total_sfg)){$query_total_sfg = decode_payload($query_total_sfg);}else{$query_total_sfg = null;} +if (!empty($query_total_fg)){$query_total_fg = decode_payload($query_total_fg);}else{$query_total_fg = null;} //Return warranty from API $api_url = '/v1/equipments/status=2&totals='; @@ -46,7 +46,7 @@ if (!empty($query_total_onstock)){$query_total_onstock = decode_payload($query_t -$startdate = date("Y-m-d", strtotime("-900 days")); +$startdate = date("Y-m-d", strtotime("-7 days")); $enddate = date("Y-m-d"); //Return SFG from API - total @@ -56,13 +56,13 @@ $query_SFG_total = ioServer($api_url,''); if (!empty($query_SFG_total)){$query_SFG_total = decode_payload($query_SFG_total);}else{$query_SFG_total = null;} //Return SFG from API - details -$api_url = '/v1/changelog/object_field=status&object_value=2&reporttype=2&between='.$startdate.'||'.$enddate; +$api_url = '/v1/changelog/object_field=status&object_value=1&reporttype=2&between='.$startdate.'||'.$enddate; $query_SFG_details = ioServer($api_url,''); //Decode Payload if (!empty($query_SFG_details)){$query_SFG_details = decode_payload($query_SFG_details);}else{$query_SFG_details = null;} //Return FG from API - totals -$api_url = '/v1/changelog/object_field=status&object_value=1&reporttype=1&between='.$startdate.'||'.$enddate; +$api_url = '/v1/changelog/object_field=status&object_value=2&reporttype=1&between='.$startdate.'||'.$enddate; $query_FG_total = ioServer($api_url,''); //Decode Payload if (!empty($query_FG_total)){$query_FG_total = decode_payload($query_FG_total);}else{$query_FG_total = null;} @@ -111,7 +111,7 @@ $view .= '

'.$product_location_FG.'

-

'.$query_total_sfg.'

+

'.$query_total_fg.'