Skip to content

Commit

Permalink
Refactoring and clean-up of code
Browse files Browse the repository at this point in the history
  • Loading branch information
kFrolichs committed Apr 26, 2018
1 parent f98ac5d commit 1be5f1a
Showing 1 changed file with 120 additions and 103 deletions.
223 changes: 120 additions & 103 deletions includes/wcwuunder-create.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ public function __construct()
wp_enqueue_style('wuunder-admin', (dirname(plugin_dir_url(__FILE__)) . '/assets/css/wuunder-admin.css'));
}

/**
* Creates an error message for the admin order page
*/
public function sample_admin_notice__error()
{

Expand All @@ -44,7 +47,13 @@ public function sample_admin_notice__error()

}

private function buildWuunderData($orderId, $redirectUrl, $webhookUrl)
/**
* Sets the address and package data for the booking request
*
* @param $orderId
* @return $bookingConfig
*/
private function setBookingConfig($orderId)
{
$orderItems = $this->get_order_items($orderId);
$orderMeta = get_post_meta($orderId);
Expand All @@ -57,15 +66,9 @@ private function buildWuunderData($orderId, $redirectUrl, $webhookUrl)
}
}

$defLength = 80;
$defWidth = 50;
$defHeight = 35;
$defWeight = 5000;
$defValue = 25 * 100;

// Get WooCommerce Wuunder Address from options page
$company = $this->get_company_address($orderId, 0);
$customer = $this->get_customer_address($orderId, $orderMeta['_billing_phone'][0]);
$company = $this->get_company_address();
$customer = $this->get_customer_address($orderId);

$totalWeight = 0;
$dimensions = null;
Expand All @@ -79,26 +82,28 @@ private function buildWuunderData($orderId, $redirectUrl, $webhookUrl)
$description .= "- " . $item['quantity'] . "x " . $item['name'] . " \r\n";
}

if ($totalWeight === 0) {
$totalWeight = $defWeight;
}
if (count($dimensions) !== 3) {
$dimensions = array($defLength, $defWidth, $defHeight);
$dimensions = array(0, 0, 0);
}

$value = intval($order->get_subtotal() * 100);

$bookingToken = uniqid();
update_post_meta($orderId, '_wuunder_label_booking_token', $bookingToken);
$redirectUrl = get_site_url(null, "/wp-admin/edit.php?post_type=shop_order");
$webhookUrl = get_site_url(null, "/wuunder/webhook?order=" . $orderId . '&token=' . $bookingToken);

$bookingConfig = new Wuunder\Api\Config\BookingConfig();
$bookingConfig->setWebhookUrl($webhookUrl);
$bookingConfig->setRedirectUrl($redirectUrl);

$bookingConfig->setDescription($description);
$bookingConfig->setKind($totalWeight > 23000 ? "pallet" : "package");
$bookingConfig->setValue($value ? $value : $defValue);
$bookingConfig->setValue($value ? $value : 0);
$bookingConfig->setLength(round($dimensions[0]));
$bookingConfig->setWidth(round($dimensions[1]));
$bookingConfig->setHeight(round($dimensions[2]));
$bookingConfig->setWeight($totalWeight ? $totalWeight : $defWeight);
$bookingConfig->setWeight($totalWeight ? $totalWeight : 0);
$bookingConfig->setPreferredServiceLevel((count($order->get_items('shipping')) > 0) ? $this->get_filter_from_shippingmethod(reset($order->get_items('shipping'))->get_method_id()) : "");

$bookingConfig->setDeliveryAddress($customer);
Expand All @@ -107,59 +112,37 @@ private function buildWuunderData($orderId, $redirectUrl, $webhookUrl)
return $bookingConfig;
}

/**
* Generates the booking url that takes the user to Wuunder.
* Returns the user to the original order page with the redirect.
*/
public function generateBookingUrl()
{
if (isset($_REQUEST['order']) && $_REQUEST['action'] === "bookorder") {
$order_id = $_REQUEST['order'];
if (true) {
$postData = array();
if (isset($_POST['data']))
$postData = stripslashes_deep($_POST['data']);

$bookingToken = uniqid();
update_post_meta($order_id, '_wuunder_label_booking_token', $bookingToken);
$postData = array();
if (isset($_POST['data']))
$postData = stripslashes_deep($_POST['data']);

$redirectUrl = get_site_url(null, "/wp-admin/edit.php?post_type=shop_order");
$webhookUrl = get_site_url(null, "/wuunder/webhook?order=" . $order_id . '&token=' . $bookingToken);
$apiKey = ($status == 'productie' ? get_option('wc_wuunder_api'): get_option('wc_wuunder_test_api'));

$status = get_option('wc_wuunder_api_status');
if ($status == 'productie') {
$apiUrl = 'https://api.wearewuunder.com/api/bookings?redirect_url=' . $redirectUrl . '&webhook_url=' . $webhookUrl;
$apiKey = get_option('wc_wuunder_api');
} else {
$apiUrl = 'https://api-staging.wearewuunder.com/api/bookings?redirect_url=' . $redirectUrl . '&webhook_url=' . $webhookUrl;
$apiKey = get_option('wc_wuunder_test_api');
}
$connector = new Wuunder\Connector($apiKey);
$booking = $connector->createBooking();
$bookingConfig = $this->setBookingConfig($order_id);

$connector = new Wuunder\Connector($apiKey);
$booking = $connector->createBooking();
$bookingConfig = $this->buildWuunderData($order_id, $redirectUrl, $webhookUrl);

if ($bookingConfig->validate()) {
$booking->setConfig($bookingConfig);
if ($booking->fire()) {
$url = $booking->getBookingResponse()->getBookingUrl();
} else {
var_dump($booking->getBookingResponse()->getError());
}
if ($bookingConfig->validate()) {
$booking->setConfig($bookingConfig);
if ($booking->fire()) {
$url = $booking->getBookingResponse()->getBookingUrl();
} else {
print("Bookingconfig not complete");
var_dump($booking->getBookingResponse()->getError());
}

update_post_meta($order_id, '_wuunder_label_booking_url', $url);
if (!(substr($url, 0, 5) === "http:" || substr($url, 0, 6) === "https:")) {
if ($status == 'productie') {
$url = 'https://api.wearewuunder.com' . $url;
} else {
$url = 'https://api-staging.wearewuunder.com' . $url;
}
}
wp_redirect($url);
exit;
} else {
// wp_redirect(get_site_url(null, " / wp - admin / edit . php ? post_type = shop_order"));
// exit;
print("Bookingconfig not complete");
}

wp_redirect($url);
exit;
} else {
// wp_redirect(get_site_url(null, " / wp - admin / edit . php ? post_type = shop_order"));
// exit;
Expand All @@ -168,14 +151,14 @@ public function generateBookingUrl()

public function test()
{
// $order_meta = get_post_meta(73);
//// var_dump($this->get_customer_address_part($order_meta, '_first_name'));
// $statuses = wc_get_order_statuses();
// echo "<pre>";
// var_dump($statuses);
// echo " </pre>";
}

/**
* Returns the filter (preferred service level) that is set in the Wuunder config
*
* @param $shipping_method
* @return
*/
private function get_filter_from_shippingmethod($shipping_method)
{
if (strpos($shipping_method, ':') !== false) {
Expand All @@ -194,48 +177,39 @@ private function get_filter_from_shippingmethod($shipping_method)
}
}

public function check_company_address()
{

if (get_option('wc_wuunder_company_name') && get_option('wc_wuunder_company_firstname') && get_option('wc_wuunder_company_lastname') && get_option('wc_wuunder_company_street') && get_option('wc_wuunder_company_housenumber') && get_option('wc_wuunder_company_postode') && get_option('wc_wuunder_company_city') && get_option('wc_wuunder_company_country') && get_option('wc_wuunder_company_email') && get_option('wc_wuunder_company_phone')) {
$check = true;
} else {
$check = false;
}

return $check;

}

public function get_company_address($orderid, $pickup_address)
/**
* Gets the company address set in the Wuunder config
*
* @return $pickupAddress
*/
public function get_company_address()
{
$pickupAddress = new \Wuunder\Api\Config\AddressConfig();
if ($pickup_address == 0) {
// Get Woocommerce Wuunder Settings
$pickupAddress->setEmailAddress(get_option('wc_wuunder_company_email'));
$pickupAddress->setFamilyName(get_option('wc_wuunder_company_lastname'));
$pickupAddress->setGivenName(get_option('wc_wuunder_company_firstname'));
$pickupAddress->setLocality(get_option('wc_wuunder_company_city'));
$pickupAddress->setStreetName(get_option('wc_wuunder_company_street'));
$pickupAddress->setHouseNumber(get_option('wc_wuunder_company_housenumber'));
$pickupAddress->setZipCode(get_option('wc_wuunder_company_postode'));
$pickupAddress->setPhoneNumber(get_option('wc_wuunder_company_phone'));
$pickupAddress->setCountry(get_option('wc_wuunder_company_country'));

$pickupAddress->setEmailAddress(get_option('wc_wuunder_company_email'));
$pickupAddress->setFamilyName(get_option('wc_wuunder_company_lastname'));
$pickupAddress->setGivenName(get_option('wc_wuunder_company_firstname'));
$pickupAddress->setLocality(get_option('wc_wuunder_company_city'));
$pickupAddress->setStreetName(get_option('wc_wuunder_company_street'));
$pickupAddress->setHouseNumber(get_option('wc_wuunder_company_housenumber'));
$pickupAddress->setZipCode(get_option('wc_wuunder_company_postode'));
$pickupAddress->setPhoneNumber(get_option('wc_wuunder_company_phone'));
$pickupAddress->setCountry(get_option('wc_wuunder_company_country'));
if($pickupAddress->validate())
{
return $pickupAddress;
} else {
// Get Woocommerce Wuunder Settings
$pickupAddress->setEmailAddress(get_option('wc_wuunder_company_email_' . $pickup_address));
$pickupAddress->setFamilyName(get_option('wc_wuunder_company_lastname_' . $pickup_address));
$pickupAddress->setGivenName(get_option('wc_wuunder_company_firstname_' . $pickup_address));
$pickupAddress->setLocality(get_option('wc_wuunder_company_city_' . $pickup_address));
$pickupAddress->setStreetName(get_option('wc_wuunder_company_street_' . $pickup_address));
$pickupAddress->setHouseNumber(get_option('wc_wuunder_company_housenumber_' . $pickup_address));
$pickupAddress->setZipCode(get_option('wc_wuunder_company_postode_' . $pickup_address));
$pickupAddress->setPhoneNumber(get_option('wc_wuunder_company_phone_' . $pickup_address));
$pickupAddress->setCountry(get_option('wc_wuunder_company_country_' . $pickup_address));
print("Invalid pickup address");
return $pickupAddress;
}
return $pickupAddress;
}

/**
* Seperates the street name and number when both are set on the same line
*
* @param $addressLine
* @return array containing 2 values: streetName and streetNumber
*/
private function separateAddressLine($addressLine)
{
if (preg_match('/^([^\d]*[^\d\s]) *(\d.*)$/', $addressLine, $result)) {
Expand All @@ -251,6 +225,12 @@ private function separateAddressLine($addressLine)
return array($addressLine, "");
}

/**
* Retrieves part of the customer address
*
* @param $order_meta, $suffix
* @return $order_meta
*/
private function get_customer_address_part($order_meta, $suffix)
{
if (isset($order_meta['_shipping' . $suffix]) && !empty($order_meta['_shipping' . $suffix][0])) {
Expand All @@ -262,6 +242,12 @@ private function get_customer_address_part($order_meta, $suffix)
}
}

/**
* Retrieves the customer address puts in function separateAddressLine
*
* @param $order_meta
* @return array containing 2 values: streetName and streetNumber
*/
private function get_customer_address_from_address_line($order_meta)
{
if (isset($order_meta['_shipping_address_1']) && !empty($order_meta['_shipping_address_1'])) {
Expand All @@ -273,7 +259,13 @@ private function get_customer_address_from_address_line($order_meta)
}
}

public function get_customer_address($orderid, $phone)
/**
* Fills the delivery address with the customers data
*
* @param $orderid
* @return $deliveryAddress
*/
public function get_customer_address($orderid)
{
// Get customer address from order
$order_meta = get_post_meta($orderid);
Expand All @@ -293,12 +285,24 @@ public function get_customer_address($orderid, $phone)
$deliveryAddress->setStreetName($street_name);
$deliveryAddress->setHouseNumber($house_number);
$deliveryAddress->setZipCode(str_replace(' ', '', $this->get_customer_address_part($order_meta, '_postcode')));
$deliveryAddress->setPhoneNumber("$phone");
$deliveryAddress->setPhoneNumber($order_meta['_billing_phone'][0]);
$deliveryAddress->setCountry($this->get_customer_address_part($order_meta, '_country'));

return $deliveryAddress;
if($deliveryAddress->validate())
{
return $deliveryAddress;
} else {
print("Invalid delivery address");
return $deliveryAddress;
}
}

/**
* Checks if the image is smaller than 2MB and base 64 encodes if it is
*
* @param $imagepath
* @return $image
*/
public function get_base64_image($imagepath)
{
try {
Expand All @@ -315,6 +319,12 @@ public function get_base64_image($imagepath)
}
}

/**
* Employed in get_base64_image to get the correct path
*
* @param $url
* @return string
*/
private function remote_filesize($url)
{
static $regex = '/^Content-Length: *+\K\d++$/im';
Expand All @@ -330,9 +340,12 @@ private function remote_filesize($url)
return strlen(stream_get_contents($fp));
}

/**
*
* @param $order
*/
public function add_listing_actions($order)
{

// do not show buttons for trashed orders
if ($order->get_status() == 'trash') {
return;
Expand Down Expand Up @@ -410,6 +423,10 @@ public function sidebar_box_content($post)
$this->add_listing_actions($order);
}

/**
*
*
*/
public function get_order_items($order_id)
{

Expand Down

0 comments on commit 1be5f1a

Please sign in to comment.