Untitled

 avatar
unknown
plain_text
a year ago
6.9 kB
4
Indexable
function b2bking_save_price_import(){ 

		
		function error_handler( $errno, $errmsg, $filename, $linenum, $vars = array() ) {
		    // error was suppressed with the @-operator
		    if ( 0 === error_reporting() ){
		      return false;
		    }

		    if ( $errno !== E_ERROR ){
		      throw new \ErrorException( sprintf('%s: %s', $errno, $errmsg ), 0, $errno, $filename, $linenum );
		    }

		}
		set_error_handler( 'error_handler' );


	    status_header(200);

		// Nonce and capability checks
    	try {
	    	if (!wp_verify_nonce( $_POST['security'], 'b2bking_price_security' )){
	    		throw new Exception('Nonce check failed');
	    		return;
	    	}
	    	// Capability check
	    	if (!current_user_can( apply_filters('b2bking_backend_capability_needed', 'manage_woocommerce') )){
	    		throw new Exception('Capability check failed');
	    		return;

	    	}

	    } catch (Exception $e){
			esc_html_e('Sorry, something went wrong! ','b2bking')."\n";
			esc_html_e('Exception: ','b2bking')."\n";
			echo $e->getMessage();
			return;
		}


	    if ( ! empty( $_FILES['b2bking_price_import_file']['name'] ) ){

	    	try {
		    	$mimes = array('application/vnd.ms-excel','text/csv','text/tsv');
		    	if(in_array($_FILES['b2bking_price_import_file']['type'],$mimes)){
		    	  // continue
		    	} else {
		    	   throw new Exception(esc_html__('File not CSV!','b2bking'));
		    	}
		    } catch (Exception $e){
				esc_html_e('Sorry, something went wrong! ','b2bking')."\n";
				esc_html_e('Exception: ','b2bking')."\n";
				echo $e->getMessage();
				return;
			}

	    	try{

	    		$filearray = file($_FILES['b2bking_price_import_file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

	    		// Change to using only comma, as ; is not compatible with tiered prices
	    		/*
	    		if (isset($filearray[1])){
	    			$filedelimiter = substr($filearray[1], -1);
	    		} else {
	    			$filedelimiter = ',';
	    		}
	    		if ($filedelimiter !== ',' && $filedelimiter !== ';'){
	    			$filedelimiter = ',';	
	    		}
	    		*/	
	    		$filedelimiter = ',';	



	    		if($filedelimiter === ','){
	    			$csv = array_map(function($v){return str_getcsv($v, ',');}, $filearray);
	    		} else if ($filedelimiter === ';'){
	    			$csv = array_map(function($v){return str_getcsv($v, ';');}, $filearray);
	    		}
	    		

	    	    // parse header line
	    	    $groups_ids_array = array();
	    	    foreach ($csv[0] as $key => $headeritem){
	    	    	// skip "product/variation id" + regular and sale and tiered price
	    	    	if ($key !== 0 && $key !== 1 && $key !== 2 && $key !== 3){
	    	    		$idnamearray = explode(':',$headeritem);
	    	    		$groups_ids_array[trim($idnamearray[0])] = trim($idnamearray[0]);
	    	    	}
	    	    }

				$groups_ids_array_numerical = array();
				foreach ($groups_ids_array as $id){
					array_push ($groups_ids_array_numerical, $id);
				}

				// parse each line
				
				foreach ($csv as $linekey => $lineelementsarray){
					// skip header line, has already been parsed
					if (intval($linekey) !== 0){	
	    	    		$productvariationid = explode(':', $lineelementsarray[0]);
	    	    		$productvariationid = $productvariationid[0];
	    	    		$i=1;
	    	    		$k=0;
	    	    		foreach ($lineelementsarray as $newkey => $lineelement){

	    	    			// skip product variation id
	    	    			if (intval($newkey) !== 0 && intval($newkey)!==1 && intval($newkey)!== 2 && intval($newkey)!== 3){ // skip reg and sale and tier price	
	    	    				$current_group_id = $groups_ids_array_numerical[$k];
	    	    				if($i === 1) { 
	    	    					// regular price
	    	    					if (!is_array($groups_ids_array[$current_group_id])){
	    	    						$groups_ids_array[$current_group_id] = array();
	    	    					}
	    	    					$groups_ids_array[$current_group_id][$productvariationid]['regprice'] = $lineelement;

	    	    					$i++;
	    	    				} else if ($i === 2){ 
	    	    					// sale price
	    	    					$groups_ids_array[$current_group_id][$productvariationid]['saleprice'] = $lineelement;
	    	    					$i++;
	    	    				} else if ($i === 3){
	    	    					$groups_ids_array[$current_group_id][$productvariationid]['tierprice'] = $lineelement;
	    	    					$k++;
	    	    					$i = 1;
	    	    				}
	    	    			} else {

	    	    				$tempID = wc_get_product_id_by_sku($productvariationid);
	    	    				if ($tempID === 0){
	    	    					// does not have sku
	    	    					$tempID = $productvariationid;
	    	    				}

	    	    				$product = wc_get_product($tempID);

	    	    				if (is_a($product,'WC_Product') || is_a($product,'WC_Product_Variation')){
			    	    			// reg price
			    	    			if (intval($newkey) === 1){
			    	    				$regpricetemp = $lineelement;
			    	    				
			    	    				$product->set_regular_price($regpricetemp);
			    	    				$product->save();
			    	    			}
			    	    			// sale price
			    	    			if (intval($newkey) === 2){
			    	    				$salepricetemp = $lineelement;

			    	    				$product->set_sale_price($salepricetemp);
			    	    				$product->save();
			    	    			}
			    	    			// tiered price
			    	    			if (intval($newkey) === 3){
			    	    				$tieredpricetemp = $lineelement;
			    	    				update_post_meta($tempID, 'b2bking_product_pricetiers_group_b2c', $tieredpricetemp);
			    	    			}
			    	    		}
		    	    		}
	    	    		}
	    	    	}
				}

			} catch (Exception $e){
				esc_html_e('Sorry, something went wrong! ','b2bking')."\n";
				esc_html_e('Exception: ','b2bking')."\n";
				echo $e->getMessage();
				return;
			}

			try{
				// update post metas
				foreach ($groups_ids_array as $groupid => $grouparrayvalue){
					foreach ($grouparrayvalue as $product_variation_id => $pricesarray){

						// if user entered SKUs	
						$tempID = wc_get_product_id_by_sku($product_variation_id);
						if ($tempID !== 0){
							$product_variation_id = $tempID;
						}

						update_post_meta($product_variation_id, 'b2bking_regular_product_price_group_'.$groupid, sanitize_text_field($pricesarray['regprice']));
						update_post_meta($product_variation_id, 'b2bking_sale_product_price_group_'.$groupid, sanitize_text_field($pricesarray['saleprice']));
						update_post_meta($product_variation_id, 'b2bking_product_pricetiers_group_'.$groupid, sanitize_text_field($pricesarray['tierprice']));
					}
				}

				// clear caches
				
				b2bking()->clear_caches_transients();



			}	catch (Exception $e){
				esc_html_e('Sorry, something went wrong! ','b2bking')."\n";
				esc_html_e('Exception: ','b2bking')."\n";
				echo $e->getMessage();
				return;
			}

			esc_html_e('Import successful','b2bking');
			wp_redirect(admin_url('admin.php?page=b2bking_tools&message=importsuccess'));

	    } else {
	    	esc_html_e('No file uploaded. You must select a CSV file first!', 'b2bking');
	    }							
	}
Editor is loading...
Leave a Comment