예제 #1
0
 /**
  * Get the sales tax information regarding the passed billing & shipping details.
  *
  * @param mixed Either an integer with the billing address or an array of details about the address.
  * @param mixed Either an integer with the shipping address or an array of details about the address.
  * @return array Array of information containing the tax data. (name, rate, based on etc)
  */
 public function GetSalesTaxRate($billingAddress, $shippingAddress = 0)
 {
     // Setup the array which will be returned
     $taxData = array("tax_name" => "", "tax_rate" => 0, "tax_based_on" => "", "tax_id" => 0);
     // If tax is being applied globally, just return that
     if (GetConfig('TaxTypeSelected') == 2) {
         $basedOn = 'subtotal';
         if (GetConfig('DefaultTaxRateBasedOn')) {
             $basedOn = GetConfig('DefaultTaxRateBasedOn');
         }
         $taxData['tax_name'] = GetConfig('DefaultTaxRateName');
         $taxData['tax_rate'] = GetConfig('DefaultTaxRate');
         $taxData['tax_based_on'] = $basedOn;
         return $taxData;
     }
     $GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');
     $countryIds = array();
     $stateIds = array();
     if (!is_array($billingAddress)) {
         $billingAddress = $GLOBALS['ISC_CLASS_ACCOUNT']->GetShippingAddress($billingAddress);
     }
     if (!is_array($shippingAddress) && $shippingAddress > 0) {
         $shippingAddress = $GLOBALS['ISC_CLASS_ACCOUNT']->GetShippingAddress($shippingAddress);
     }
     // A billing address is required for every order. If we don't have one then there's no point in proceeding
     if (!is_array($billingAddress)) {
         return $taxData;
     }
     if (!isset($billingAddress['shipcountryid'])) {
         $billingAddress['shipcountryid'] = GetCountryIdByName($billingAddress['shipcountry']);
     }
     if (!isset($billingAddress['shipstateid'])) {
         $billingAddress['shipstateid'] = GetStateByName($billingAddress['shipstate'], $billingAddress['shipcountryid']);
     }
     if (is_array($shippingAddress)) {
         if (!isset($shippingAddress['shipcountryid'])) {
             $shippingAddress['shipcountryid'] = GetCountryIdByName($shippingAddress['shipcountry']);
         }
         if (!isset($shippingAddress['shipstateid'])) {
             $shippingAddress['shipstateid'] = GetStateByName($shippingAddress['shipstate'], $shippingAddress['shipcountryid']);
         }
     }
     // Do we have a matching state based tax rule?
     if ($billingAddress['shipstateid'] || is_array($shippingAddress) && $shippingAddress['shipstateid']) {
         $query = "\n\t\t\t\t\tSELECT *\n\t\t\t\t\tFROM [|PREFIX|]tax_rates\n\t\t\t\t\tWHERE (1=0\n\t\t\t\t";
         if ($billingAddress['shipstateid']) {
             $query .= " OR (taxaddress='billing' AND taxratecountry='" . (int) $billingAddress['shipcountryid'] . "' AND taxratestates LIKE '%%," . (int) $billingAddress['shipstateid'] . ",%%')";
         }
         if (is_array($shippingAddress) && $shippingAddress['shipstateid']) {
             $query .= " OR (taxaddress='shipping' AND taxratecountry='" . (int) $shippingAddress['shipcountryid'] . "' AND taxratestates LIKE '%%," . (int) $shippingAddress['shipstateid'] . ",%%')";
         }
         $query .= ") AND taxratestatus='1'";
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
         if (is_array($row)) {
             $taxData = array('tax_name' => $row['taxratename'], 'tax_rate' => $row['taxratepercent'], 'tax_based_on' => $row['taxratebasedon'], 'tax_id' => $row['taxrateid']);
             return $taxData;
         }
     }
     // Maybe we've got a matching country based rule
     $query = "\n\t\t\t\tSELECT *\n\t\t\t\tFROM [|PREFIX|]tax_rates\n\t\t\t\tWHERE (1=0 OR (taxratecountry='" . (int) $billingAddress['shipcountryid'] . "' AND taxaddress='billing')\n\t\t\t";
     if (is_array($shippingAddress) && $shippingAddress['shipcountryid']) {
         $query .= " OR (taxratecountry='" . (int) $shippingAddress['shipcountryid'] . "' AND taxaddress='shipping')";
     }
     $query .= ") AND taxratestatus='1' AND taxratestates = ',0,'";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
     if (is_array($row)) {
         $taxData = array('tax_name' => $row['taxratename'], 'tax_rate' => $row['taxratepercent'], 'tax_based_on' => $row['taxratebasedon'], 'tax_id' => $row['taxrateid']);
         return $taxData;
     }
     // Otherwise, if we still have nothing, perhaps we have a rule that applies to all countries
     $query = "\n\t\t\t\tSELECT *\n\t\t\t\tFROM [|PREFIX|]tax_rates\n\t\t\t\tWHERE taxratecountry='0' AND taxratestatus='1'\n\t\t\t";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
     if (is_array($row)) {
         $taxData = array('tax_name' => $row['taxratename'], 'tax_rate' => $row['taxratepercent'], 'tax_based_on' => $row['taxratebasedon'], 'tax_id' => $row['taxrateid']);
         return $taxData;
     }
     // Still here? Just return nothing!
     return $taxData;
 }
예제 #2
0
		/**
		 * Save the submitted shipping address form data
		 *
		 * Method will map and save all the shipping address data
		 *
		 * @access private
		 * @param array $fields The form fields to save
		 * @param int $customerId The customerId
		 * @param int $shippingId The optional shipping ID. Default is 0 (new record)
		 * @return mixed The new shipping ID on successful new record, TRUE if record successfully
		 *               updated, FALSE on error
		 */
		private function saveAddressFields($fields, $customerId, $shippingId=0)
		{
			if (!is_array($fields) || empty($fields) || !isId($customerId)) {
				return false;
			}

			$savedata = array(
				'shipcustomerid' => $customerId
			);

			if (isId($shippingId)) {
				$savedata['shipid'] = $shippingId;
			}

			/**
			 * Map the private data
			 */
			$country = $state = '';

			foreach (array_keys($fields) as $fieldId) {
				$privateId = $fields[$fieldId]->record['formfieldprivateid'];

				if ($privateId == '' || !array_key_exists($privateId, $this->shippingMap)) {
					continue;
				}

				$savedata[$this->shippingMap[$privateId]] = $fields[$fieldId]->getValue();

				if (strtolower($privateId) == 'country') {
					$country = $fields[$fieldId]->getValue();
				} else if (strtolower($privateId) == 'state') {
					$state = $fields[$fieldId]->getValue();
				}
			}

			/**
			 * Find the country and state ID if we can
			 */
			$countryId = $stateId = 0;

			if ($country !== '') {
				$countryId = GetCountryByName($country);
			}

			if ($state !== '' && isId($countryId)) {
				$stateId = GetStateByName($state, $countryId);
			}

			$savedata['shipcountryid'] = (int)$countryId;
			$savedata['shipstateid'] = (int)$stateId;

			/**
			 * Save our custom (non private) fields if we are allowed
			 */
			if (gzte11(ISC_MEDIUMPRINT)) {

				/**
				 * Do we already have a form session ID for this address?
				 */
				$formSessionId = 0;
				if (isId($shippingId)) {
					$address = $this->shippingEntity->get($shippingId);
					if (is_array($address) && isset($address['shipformsessionid']) && isId($address['shipformsessionid'])) {
						$formSessionId = $address['shipformsessionid'];
					}
				}

				if (isId($formSessionId)) {
					$GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ADDRESS, true, $formSessionId);
				} else {
					$formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ADDRESS);
					if (isId($formSessionId)) {
						$savedata['shipformsessionid'] = $formSessionId;
					}
				}
			}

			if (isId($shippingId)) {
				return $this->shippingEntity->edit($savedata);
			} else {
				return $this->shippingEntity->add($savedata);
			}
		}
예제 #3
0
 /**
  * Display a list of states for a given country
  *
  * @return void
  **/
 private function GetCountryStates()
 {
     $country = $_REQUEST['c'];
     if (IsId($country)) {
         $countryId = $country;
     } else {
         $countryId = GetCountryIdByName($country);
     }
     if (isset($_REQUEST['s']) && GetStateByName($_REQUEST['s'], $countryId)) {
         $state = $_REQUEST['s'];
     } else {
         $state = '';
     }
     if (isset($_REQUEST['format']) && $_REQUEST['format'] == 'options') {
         echo GetStateListAsOptions($country, $state, false, '', '', false, true);
     } else {
         echo GetStateList((int) $country);
     }
 }
 /**
  * Imports an actual product record in to the database.
  *
  * @param array Array of record data
  */
 protected function _ImportRecord($record)
 {
     if (!$record['custconemail']) {
         $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportCustomersMissingEmail');
         return;
     }
     if (!is_email_address($record['custconemail'])) {
         $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportCustomersInvalidEmail');
         return;
     }
     $fillin = array('custconcompany', 'custconfirstname', 'custconlastname', 'custconphone');
     foreach ($fillin as $fillkey) {
         if (!isset($record[$fillkey])) {
             $record[$fillkey] = '';
         }
     }
     // Is there an existing customer with the same email?
     $customerId = 0;
     $existingFormSessionId = 0;
     $query = sprintf("select customerid from [|PREFIX|]customers where lower(custconemail)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['custconemail'])));
     $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
     if ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) {
         // Overriding existing products, set the product id
         if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
             $customerId = $row['customerid'];
             $this->ImportSession['Results']['Updates'][] = $record['custconfirstname'] . " " . $record['custconlastname'] . " (" . $record['custconemail'] . ")";
         } else {
             $this->ImportSession['Results']['Duplicates'][] = $record['custconfirstname'] . " " . $record['custconlastname'] . " (" . $record['custconemail'] . ")";
             return;
         }
         if (isId($row['custformsessionid'])) {
             $existingFormSessionId = $row['custformsessionid'];
         }
     }
     $customerData = array('company' => $record['custconcompany'], 'firstname' => $record['custconfirstname'], 'lastname' => $record['custconlastname'], 'email' => $record['custconemail'], 'phone' => $record['custconphone']);
     if (isset($record['custpassword']) && $record['custpassword'] !== '') {
         $customerData['password'] = $record['custpassword'];
     }
     if (isset($record['custstorecredit'])) {
         $customerData['storecredit'] = DefaultPriceFormat($record['custstorecredit']);
     }
     if (isId($customerId)) {
         $customerData['customerid'] = $customerId;
     }
     // Are we placing the customer in a customer group?
     $groupId = 0;
     if (!empty($record['custgroup'])) {
         static $customerGroups;
         $groupName = strtolower($record['custgroup']);
         if (isset($customerGroups[$groupName])) {
             $groupId = $customerGroups[$groupName];
         } else {
             $query = "\n\t\t\t\t\tSELECT customergroupid\n\t\t\t\t\tFROM [|PREFIX|]customer_groups\n\t\t\t\t\tWHERE LOWER(groupname)='" . $GLOBALS['ISC_CLASS_DB']->Quote($groupName) . "'\n\t\t\t\t";
             $groupId = $GLOBALS['ISC_CLASS_DB']->FetchOne($query, 'customergroupid');
             // Customer group doesn't exist, create it
             if (!$groupId) {
                 $newGroup = array('name' => $record['custgroup'], 'discount' => 0, 'isdefault' => 0, 'categoryaccesstype' => 'all');
                 $entity = new ISC_ENTITY_CUSTOMERGROUP();
                 $groupId = $entity->add($newGroup);
             }
             if ($groupId) {
                 $customerGroups[$groupName] = $groupId;
             }
         }
     }
     $customerData['customergroupid'] = $groupId;
     // Do we have a shipping address?
     $shippingData = array();
     if (isset($record['shipfullname']) || isset($record['shipfirstname']) || isset($record['shipaddress1']) || isset($record['shipaddress2']) || isset($record['shipcity']) || isset($record['shipstate']) || isset($record['shipzip']) || isset($record['shipcountry'])) {
         $fillin = array('shipaddress1', 'shipaddress2', 'shipcity', 'shipstate', 'shipzip', 'shipcountry');
         foreach ($fillin as $fillkey) {
             if (!isset($record[$fillkey])) {
                 $record[$fillkey] = '';
             }
         }
         $shippingData['shipfirstname'] = '';
         $shippingData['shiplastname'] = '';
         $shippingData['shipaddress1'] = $record['shipaddress1'];
         $shippingData['shipaddress2'] = $record['shipaddress2'];
         $shippingData['shipcity'] = $record['shipcity'];
         $shippingData['shipstate'] = $record['shipstate'];
         $shippingData['shipzip'] = $record['shipzip'];
         $shippingData['shipcountry'] = $record['shipcountry'];
         $shippingData['shipstateid'] = 0;
         $shippingData['shipcountryid'] = 0;
         $shippingData['shipdestination'] = '';
         // Find the country and state
         $shippingData['shipcountryid'] = (int) GetCountryByName($record['shipcountry']);
         if (!$shippingData['shipcountryid']) {
             $shippingData['shipcountryid'] = (int) GetCountryIdByISO2($record['shipcountry']);
         }
         // Still nothing? 0 for the shipping country ID
         if (!$shippingData['shipcountryid']) {
             $shippingData['shipcountryid'] = 0;
         }
         if (isset($record['shipstate'])) {
             $shippingData['shipstateid'] = GetStateByName($record['shipstate'], $shippingData['shipcountryid']);
         }
         // Still nothing? 0 for the shipping state ID
         if (!$shippingData['shipstateid']) {
             $shippingData['shipstateid'] = 0;
         }
         if (!isset($record['shipfullname']) || $record['shipfullname'] == "") {
             if (isset($record['shipfirstname']) && $record['shipfirstname'] != '') {
                 $shippingData['shipfirstname'] = $record['shipfirstname'];
             } else {
                 $shippingData['shipfirstname'] = $customerData['firstname'];
             }
             if (isset($record['shiplastname']) && $record['shiplastname'] != '') {
                 $shippingData['shiplastname'] = $record['shiplastname'];
             } else {
                 $shippingData['shiplastname'] = $customerData['lastname'];
             }
         }
         if (!isset($record['shipphone']) && isset($record['custconphone'])) {
             $shippingData['shipphone'] = $record['custconphone'];
         } else {
             $shippingData['shipphone'] = $record['shipphone'];
         }
         /**
          * Handle any of the address custom fields that we might have
          */
         if (!empty($this->customFields) && array_key_exists('custom', $record)) {
             $shippingData['shipformsessionid'] = $this->_importCustomFormfields(FORMFIELDS_FORM_ADDRESS, $record['custom']);
             if (!isId($shippingData['shipformsessionid'])) {
                 unset($shippingData['shipformsessionid']);
             }
         }
     }
     /**
      * Handle any of the customer custom fields that we might have
      */
     if (!empty($this->customFields) && array_key_exists('custom', $record)) {
         $formSessionId = $this->_importCustomFormfields(FORMFIELDS_FORM_ACCOUNT, $record['custom'], $existingFormSessionId);
         if (isId($formSessionId)) {
             $customerData['custformsessionid'] = $formSessionId;
         }
     }
     $customerData['is_import'] = true;
     $customerEntity = new ISC_ENTITY_CUSTOMER();
     // New customer, insert in to DB
     if ($customerId == 0) {
         // Set a temporary password, retrievable later via lost password function
         if (!isset($customerData['password']) || $customerData['password'] == '') {
             $customerData['password'] = isc_substr(uniqid(rand(), true), 0, 10);
         }
         $customerData['token'] = GenerateCustomerToken();
         $customerData['shipping_address'] = $shippingData;
         $rtn = $customerEntity->add($customerData);
         ++$this->ImportSession['Results']['SuccessCount'];
     } else {
         if (count($shippingData) > 0) {
             $query = sprintf("select shipid from [|PREFIX|]shipping_addresses where shipcustomerid='%d' and lower(shipaddress1)='%s' and lower(shipaddress2)='%s' and lower(shipcity)='%s' and lower(shipstate)='%s' and lower(shipcountry)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($customerId), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipaddress1']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipaddress2']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipcity']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipstate']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipcountry']));
             $Result = $GLOBALS['ISC_CLASS_DB']->Query($query);
             $row = $GLOBALS['ISC_CLASS_DB']->Fetch($Result);
             // Address doesn't exist, we insert it
             if (!$row['shipid']) {
                 $customerData['shipping_address'] = $shippingData;
             }
         }
         $rtn = $customerEntity->edit($customerData);
     }
 }
 /**
  * Calculate the shipping for an order that's being edited/created.
  */
 private function OrderCalculateShipping()
 {
     if (!isset($_REQUEST['orderSession'])) {
         exit;
     }
     $orderClass = GetClass('ISC_ADMIN_ORDERS');
     $orderClass->GetCartApi($_REQUEST['orderSession']);
     $cartProducts = $orderClass->GetCartApi()->GetProductsInCart();
     $cartClass = GetClass('ISC_CART');
     $address = array('shipzip' => @$_REQUEST['ordshipzip'], 'shipstate' => @$_REQUEST['ordshipstate'], 'shipcountry' => @$_REQUEST['ordshipcountry'], 'shipcountryid' => GetCountryIdByName(@$_REQUEST['ordshipcountry']));
     $address['shipstateid'] = GetStateByName($address['shipstate'], $address['shipcountryid']);
     $shippingMethods = $cartClass->GetAvailableShippingMethodsForProducts($address, $cartProducts, $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId());
     $orderClass->GetCartApi()->Set('SHIPPING_QUOTES', $shippingMethods);
     $existingShippingMethod = $orderClass->GetCartApi()->Get('SHIPPING_METHOD');
     $GLOBALS['ShippingMethods'] = '';
     foreach ($shippingMethods as $quoteId => $quote) {
         $checked = '';
         if (is_array($existingShippingMethod) && $quote['description'] == $existingShippingMethod['methodName']) {
             $hasChecked = true;
             $checked = 'checked="checked"';
         }
         $GLOBALS['MethodChecked'] = $checked;
         $GLOBALS['MethodName'] = isc_html_escape($quote['description']);
         $GLOBALS['MethodCost'] = FormatPrice($quote['price']);
         $GLOBALS['MethodId'] = $quoteId;
         $GLOBALS['ShippingMethods'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderShippingMethodChoice');
     }
     $GLOBALS['HideNoShipingMethods'] = 'display: none';
     if (!empty($shippingMethods)) {
         $GLOBALS['HideNoShippingMethods'] = '';
     }
     $existingOrder = $orderClass->GetCartApi()->Get('EXISTING_ORDER');
     $order = GetOrder($existingOrder);
     if ($existingOrder !== false && $order['ordshipmethod']) {
         $checked = '';
         if (!isset($hasChecked) && (!is_array($existingShippingMethod) || $order['ordshipmethod'] == $existingShippingMethod['methodName'])) {
             $checked = 'checked="checked"';
         }
         $GLOBALS['MethodChecked'] = $checked;
         $GLOBALS['MethodName'] = sprintf(GetLang('ExistingShippingMethod'), isc_html_escape($order['ordshipmethod']));
         $GLOBALS['MethodCost'] = FormatPrice($order['ordshipcost']);
         $GLOBALS['MethodId'] = 'existing';
         $GLOBALS['ShippingMethods'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderShippingMethodChoice') . $GLOBALS['ShippingMethods'];
     }
     $GLOBALS['CustomChecked'] = '';
     $GLOBALS['HideCustom'] = 'display: none';
     if (is_array($existingShippingMethod) && $existingShippingMethod['methodModule'] == 'custom') {
         $GLOBALS['CustomChecked'] = 'checked="checked"';
         $GLOBALS['CustomName'] = isc_html_escape($existingShippingMethod['methodName']);
         $GLOBALS['CustomPrice'] = FormatPrice($existingShippingMethod['methodCost'], false, false);
         $GLOBALS['HideCustom'] = '';
     }
     /* The below patch is added to check the custom shipping if no other shipping method exist - vikas - starts */
     if ($GLOBALS['ShippingMethods'] == "") {
         $GLOBALS['CustomChecked'] = 'checked="checked"';
         $GLOBALS['HideCustom'] = '';
     }
     // below custom name has been added as client told to make it readonly.
     if (!isset($GLOBALS['CustomName'])) {
         $GLOBALS['CustomName'] = "Custom";
     }
     /* - ends -*/
     echo $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderShippingMethodWindow');
     exit;
 }
예제 #6
0
	/**
	 * Get the state ID
	 *
	 * Method will return the state ID if found
	 *
	 * @access protected
	 * @param string $stateName The state name / abbrevation
	 * @param int $countryId The country ID
	 * @param string $properStateName The referenced variable to set the proper state name if the record exists
	 * @return int The state ID on success, FALSE if not found
	 */
	protected function getStateId($stateName, $countryId, &$properStateName=null)
	{
		if (trim($stateName) == '' || !isId($countryId)) {
			return false;
		}

		$stateId = GetStateByName($stateName, $countryId);

		if (!isId($stateId)) {
			$stateId = GetStateByAbbrev($stateName, $countryId);
		}

		if (!isId($stateId)) {
			return false;
		}

		$properStateName = GetStateById($stateId);

		return $stateId;
	}
예제 #7
0
		private function GetStateID($countryID, $stateName)
		{
			$stateID = GetStateByAbbrev($stateName, $countryID);

			if ($stateID) {
				return $stateID;
			}

			$stateID = GetStateByName($stateName, $countryID);
			if ($stateID) {
				return $stateID;
			}

			return 0;
		}
예제 #8
0
	private function ParseAddress($record, $customerId, $index = '')
	{
		$shippingData = array();

		$fillin = array('shipaddress1', 'shipaddress2', 'shipcity', 'shipstate', 'shipzip', 'shipcountry');
		foreach ($fillin as $fillkey) {
			if (!isset($record[$fillkey . $index])) {
				$record[$fillkey . $index] = '';
			}
		}

		if (isId($customerId)) {
			$shippingData["shipcustomerid"] = $customerId;
		}

		$shippingData['shipid'] = 0;
		if (!empty($record['shipid' . $index])) {
			$shippingData['shipid'] = $record['shipid' . $index];
		}

		$shippingData['shipfirstname'] = $record['shipfirstname' . $index];
		$shippingData['shiplastname'] = $record['shiplastname' . $index];
		$shippingData['shipaddress1'] = $record['shipaddress1' . $index];
		$shippingData['shipaddress2'] = $record['shipaddress2' . $index];
		$shippingData['shipcity'] = $record['shipcity' . $index];
		$shippingData['shipstate'] = $record['shipstate' . $index];
		$shippingData['shipzip'] = $record['shipzip' . $index];
		$shippingData['shipcountry'] = $record['shipcountry' . $index];
		$shippingData['shipstateid'] = 0;
		$shippingData['shipcountryid'] = 0;
		$shippingData['shipdestination'] = '';

		// Find the country and state
		$shippingData['shipcountryid'] = (int)GetCountryByName($record['shipcountry' . $index]);
		if(!$shippingData['shipcountryid']) {
			$shippingData['shipcountryid'] = (int)GetCountryIdByISO2($record['shipcountry' . $index]);
		}

		// Still nothing? 0 for the shipping country ID
		if(!$shippingData['shipcountryid']) {
			$shippingData['shipcountryid'] = 0;
		}

		if(isset($record['shipstate' . $index])) {
			$shippingData['shipstateid'] = GetStateByName($record['shipstate' . $index], $shippingData['shipcountryid']);
		}

		// Still nothing? 0 for the shipping state ID
		if(!$shippingData['shipstateid']) {
			$shippingData['shipstateid'] = 0;
		}

		if(!isset($record['shipphone' . $index]) && isset($record['custconphone' . $index])) {
			$shippingData['shipphone'] = $record['custconphone' . $index];
		}
		else {
			$shippingData['shipphone'] = $record['shipphone' . $index];
		}

		/**
		 * Handle any of the address custom fields that we might have
		 */
		if (!empty($this->customFields) && array_key_exists('custom', $record)) {
			$shippingData['shipformsessionid'] = $this->_importCustomFormfields(FORMFIELDS_FORM_ADDRESS, $record['custom' . $index]);

			if (!isId($shippingData['shipformsessionid'])) {
				unset($shippingData['shipformsessionid']);
			}
		}

		return $shippingData;
	}
	/**
	* Ebay: Sent to a seller when a buyer completes the checkout process for an item. Not sent when an auction ends without bids.
	*
	* My notes: Seems to be triggered when the buyer's payment process for an AUCTION item has completed, is not fired for fixed price items which fire 'FixedPrice...' notifications instead
	*
	* @param array $body
	*/
	protected function _handleAuctionCheckoutComplete($body)
	{
		// The data fields in the notification are the same as those returned by the GetItemTransactions call with the default detail level.
		if (!empty ($body['Item']['ItemID']) && ISC_ADMIN_EBAY::validEbayItemId($body['Item']['ItemID'])) {
			// variables init
			$order = array();
			$orderId = 1;
			$order['ShippingInsuranceCost'] = 0;
			$completedPaymentHoldStatus = array('None', 'Released');
			$orderStatus = ORDER_STATUS_AWAITING_PAYMENT;
			$existingOrderId = 0;

			// Determine if the buyer purchase multiple items from the same seller
			if (!empty($body['TransactionArray']['Transaction']['ContainingOrder'])) {
			 // Call the operation to get the order transaction.
				$orderId = $body['TransactionArray']['Transaction']['ContainingOrder']['OrderID'];

				// if the record already exist, check if we need to update existing orders, that the payment hasn't been cleared previously.
				$existingOrder = GetOrderByEbayOrderId($orderId);
				$orderTransaction = ISC_ADMIN_EBAY_OPERATIONS::getOrderTransactions($orderId);
				$transactions = $orderTransaction->OrderArray->Order->TransactionArray->Transaction;

				$order['SubTotal'] = (string) $orderTransaction->OrderArray->Order->Subtotal;
				$order['ShippingCost'] = (string) $orderTransaction->OrderArray->Order->ShippingServiceSelected->ShippingServiceCost;
				$order['ShippingInsuranceCost'] = 0;
				$order['GrandTotal'] = (string) $orderTransaction->OrderArray->Order->Total;
				$order['TotalQuantityPurchased'] = 0;
				foreach ($transactions as $transaction) {
					$convertedTransaction = (array) $transaction;
					$variationOptionsString = '';
					if (isset($convertedTransaction['Variation']->VariationSpecifics)) {
						$variationNameValueList = (array) $convertedTransaction['Variation']->VariationSpecifics->NameValueList;
						$variationOptions = array();
						$variationSpecifics = (array) $convertedTransaction['Variation']->VariationSpecifics;
						if (is_array($variationSpecifics['NameValueList'])) {
							foreach ($variationSpecifics['NameValueList'] as $option) {
								$variationOptions[(string) $option->Name] = (string) $option->Value;
							}
						} else {
							$variationOptions[(string) $variationSpecifics['NameValueList']->Name] = (string) $variationSpecifics['NameValueList']->Value;
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$quantityPurchased = $convertedTransaction['QuantityPurchased'];
					$transactionPrice = $convertedTransaction['TransactionPrice'];
					$itemId = (string) $convertedTransaction['Item']->ItemID;
					$transactionId = (string) $convertedTransaction['TransactionID'];
					$totalTransactionPrice = $transactionPrice * $quantityPurchased;
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $transactionPrice,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['TotalQuantityPurchased'] += $quantityPurchased;
					$order['Currency'] = GetCurrencyByCode($body['TransactionArray']['Transaction']['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $body['TransactionArray']['Transaction']['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $body['TransactionArray']['Transaction']['Buyer']['Email'];
				}

				if ($existingOrder) {
					$existingOrderId = $existingOrder['orderid'];
				}
			}
			else {
				$transactions = $body['TransactionArray'];
				foreach ($transactions as $transaction) {
					$itemId = $body['Item']['ItemID'];
					$transactionId = $transaction['TransactionID'];
					$query = "
						SELECT *
						FROM [|PREFIX|]order_products
						WHERE ebay_item_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($itemId)."'
							AND ebay_transaction_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($transactionId)."'
						LIMIT 1
					";
					$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
					$row = $GLOBALS['ISC_CLASS_DB']->Fetch($res);
					$eachItemPriceExTax = $transaction['TransactionPrice']['!'];
					$quantityPurchased = $transaction['QuantityPurchased'];
					$totalTransactionPrice = $quantityPurchased * $eachItemPriceExTax;
					$variationOptionsString = '';

					// do we have a variation for this product?
					if (isset($transaction['Variation']['VariationSpecifics'])) {
						$variationNameValueList = $transaction['Variation']['VariationSpecifics']['NameValueList'];
						$variationOptions = array();
						foreach ($variationNameValueList as $option) {
							$variationOptions[$option['Name']] = $option['Value'];
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$order['TotalQuantityPurchased'] = $quantityPurchased;
					$order['SubTotal'] = $eachItemPriceExTax * $order['TotalQuantityPurchased'];
					$order['ShippingCost'] = $transaction['ShippingServiceSelected']['ShippingServiceCost']['!'];
					if (isset ($transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'])) {
						$order['ShippingInsuranceCost'] = $transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'];
					}
					$order['GrandTotal'] = $transaction['AmountPaid']['!'];
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $eachItemPriceExTax,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['Currency'] = GetCurrencyByCode($transaction['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $transaction['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $transaction['Buyer']['Email'];

					if (!$row) {
						// only process the new transaction
						break;
					} else {
						$existingOrderId = $row['orderorderid'];
					}
				}
			}

			$paymentHoldStatus = $body['TransactionArray']['Transaction']['Status']['PaymentHoldStatus'];
			if (in_array(trim($paymentHoldStatus), $completedPaymentHoldStatus)) {
				$orderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
			}
			if ($existingOrderId != 0) {
				if (!isset ($existingOrder)) {
					$existingOrder = GetOrder($existingOrderId, false, true, true);
				}

				// check if there're any existing order need to be updated.
				// in the case, paypal release the hold payment of buyer
				if ($existingOrder['ordstatus'] == ORDER_STATUS_AWAITING_PAYMENT
				&& $orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the quantity for each transaction
					$GLOBALS["ISC_CLASS_DB"]->StartTransaction();
					foreach ($order['Transaction'] as $eachTransaction) {
						// Get product Id
						try {
							$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
							$productId = $itemObj->getProductId();
						} catch (Exception $e) {
							$this->log->LogSystemDebug('ebay', $e->getMessage());
							return false;
						}

						// update the item quantity in store
						$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
						if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
							$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
						if (!UpdateOrderStatus($existingOrderId, $orderStatus, true, true)) {
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
					}
					$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

					// update the store inventory if necessary
					if (GetConfig('UpdateInventoryLevels') == 1) {
						DecreaseInventoryFromOrder($existingOrderId);
					}
					$this->log->LogSystemDebug('ebay', 'The status of the store order ('. $existingOrderId .') has been updated to: Awaiting Fulfillment');
				}
				return true;
			}

			$order['ShippingTotalCost'] = $order['ShippingInsuranceCost'] + $order['ShippingCost'];

			// Buyer's address information
			$addressMap = array(
				'Name',
				'CompanyName',
				'Street1',
				'Street2',
				'CityName',
				'PostalCode',
				'Country',
				'CountryName',
				'Phone',
				'StateOrProvince',
			);

			// Initialize the value, make sure it's not empty
			foreach ($addressMap as $key) {
				if (!isset($buyerInfoShippingAddress[$key])) {
					$buyerInfoShippingAddress[$key] = '';
				}
			}
			$buyerCountryId = GetCountryIdByISO2($buyerInfoShippingAddress['Country']);
			$buyerStateId = GetStateByName($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
			$buyerStateName = $buyerInfoShippingAddress['StateOrProvince'];
			if (!$buyerStateId) {
				$buyerStateId = GetStateByAbbrev($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
				$stateInfo = GetStateInfoById($buyerStateId);
				$buyerStateName = $stateInfo['statename'];
			}

			// Tokenize buyer's first and last name
			$nameTokens = explode(' ', $buyerInfoShippingAddress['Name']);
			$buyerFirstName = $nameTokens[0];
			$buyerLastName = '';
			if (!empty($nameTokens[1])) {
				$buyerLastName = $nameTokens[1];
			}

			$orderToken = generateOrderToken();

			// Preparing data to be inserted to orders table
			$newOrder = array(
				'ordtoken' => $orderToken,
				'orderpaymentmodule' => '',
				'orderpaymentmethod' => '',
				'orderpaymentmodule' => '',
				'extraInfo' => serialize(array()),
				'orddefaultcurrencyid' => $order['Currency']['currencyid'],
				'orddate' => time(),
				'ordlastmodified' => time(),
				'ordcurrencyid' => $order['Currency']['currencyid'],
				'ordcurrencyexchangerate' => 1,
				'ordipaddress' => GetIP(),
				'ordcustmessage' => '',
				'ordstatus' => $orderStatus,
				'base_shipping_cost' => $order['ShippingTotalCost'],
				'base_handling_cost' => 0,
				'ordbillemail' => $buyerEmailAddress,
				'ordbillfirstname' => $buyerFirstName,
				'ordbilllastname' => $buyerLastName,
				'ordbillcompany' => $buyerInfoShippingAddress['CompanyName'],
				'ordbillstreet1' => $buyerInfoShippingAddress['Street1'],
				'ordbillstreet2' => $buyerInfoShippingAddress['Street2'],
				'ordbillsuburb' => $buyerInfoShippingAddress['CityName'],
				'ordbillzip' => $buyerInfoShippingAddress['PostalCode'],
				'ordbillcountrycode' => $buyerInfoShippingAddress['Country'],
				'ordbillphone' => $buyerInfoShippingAddress['Phone'],
				'ordbillstateid' => (int) $buyerStateId,
				'ordbillstate' => $buyerStateName,
				'ordbillcountry' => $buyerInfoShippingAddress['CountryName'],
				'ordbillcountryid' => (int) $buyerCountryId,
				'total_ex_tax' => $order['GrandTotal'],
				'total_inc_tax' => $order['GrandTotal'],
				'shipping_cost_ex_tax' => $order['ShippingTotalCost'],
				'shipping_cost_inc_tax' => $order['ShippingTotalCost'],
				'subtotal_inc_tax' => $order['SubTotal'],
				'subtotal_ex_tax' => $order['SubTotal'],
				'ebay_order_id' => $orderId,
			);
			ResetStartingOrderNumber();

			// Start the transaction
			$GLOBALS["ISC_CLASS_DB"]->StartTransaction();

			// Inserting order data
			$newOrderId = $GLOBALS["ISC_CLASS_DB"]->InsertQuery('orders', $newOrder);
			if (!$newOrderId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			$orderAddress = array(
				'first_name' => $buyerFirstName,
				'last_name' => $buyerLastName,
				'company' => $buyerInfoShippingAddress['CompanyName'],
				'address_1' => $buyerInfoShippingAddress['Street1'],
				'address_2' => $buyerInfoShippingAddress['Street2'],
				'city' => $buyerInfoShippingAddress['CityName'],
				'zip' => $buyerInfoShippingAddress['PostalCode'],
				'country_iso2' => $buyerInfoShippingAddress['Country'],
				'phone' => $buyerInfoShippingAddress['Phone'],
				'total_items' => $order['TotalQuantityPurchased'],
				'email' => $buyerEmailAddress,
				'country_id' => (int) $buyerCountryId,
				'country' => $buyerInfoShippingAddress['CountryName'],
				'state_id' => (int) $buyerStateId,
				'state' => $buyerStateName,
				'order_id' => $newOrderId,
			);

			$addressId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_addresses', $orderAddress);
			if (!$addressId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Inserting order shipping
			$orderShipping = array(
				'order_address_id' => $addressId,
				'order_id' => $newOrderId,
				'base_cost' => $order['ShippingTotalCost'],
				'cost_inc_tax' => $order['ShippingTotalCost'],
				'cost_ex_tax' => $order['ShippingTotalCost'],
				'method' => 'Available on eBay',
			);

			if (!$GLOBALS['ISC_CLASS_DB']->insertQuery('order_shipping', $orderShipping)) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Go thru each sold item in the order
			foreach ($order['Transaction'] as $eachTransaction) {
				// Get product Id
				try {
					$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
					$productId = $itemObj->getProductId();
				} catch (Exception $e) {
					$this->log->LogSystemDebug('ebay', $e->getMessage());
					return false;
				}

				// Inserting order product
				$productObj = new ISC_PRODUCT($productId);
				$newProduct = array(
					'orderorderid' => $newOrderId,
					'ordprodid' => $productId,
					'ordprodsku' => $productObj->GetSKU(),
					'ordprodname' => $productObj->GetProductName(),
					'ordprodtype' => $productObj->GetProductType(),
					'ordprodqty' => $eachTransaction['QuantityPurchased'],
					'base_price' => $eachTransaction['TransactionPrice'],
					'price_ex_tax' => $eachTransaction['TransactionPrice'],
					'price_inc_tax' => $eachTransaction['TransactionPrice'],
					'price_tax' => 0,
					'base_total' => $eachTransaction['TotalTransactionPrice'],
					'total_ex_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_inc_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_tax' => 0,
					'base_cost_price' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_tax' => 0,
					'ordprodweight' => $productObj->GetWeight(false),
					'ordprodoptions' => $eachTransaction['VariationOptionsString'],
					'ordprodvariationid' => $productObj->_prodvariationid,
					'ordprodwrapid' => 0,
					'ordprodwrapname' => '',
					'base_wrapping_cost' => 0,
					'wrapping_cost_ex_tax' => 0,
					'wrapping_cost_inc_tax' => 0,
					'wrapping_cost_tax' => 0,
					'ordprodwrapmessage' => '',
					'ordprodeventname' => '',
					'ordprodeventdate' => 0,
					'ordprodfixedshippingcost' => $productObj->GetFixedShippingCost(),
					'order_address_id' => $addressId,
					'ebay_item_id' => $eachTransaction['ItemId'],
					'ebay_transaction_id' => $eachTransaction['TransactionId'],
				);

				$orderProductId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_products', $newProduct);
				if (!$orderProductId) {
					$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
					$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
					return false;
				}

				if ($orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the item quantity in store
					$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
					if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
						$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
						$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
						return false;
					}
				}
			}
			$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

			// update the store inventory if necessary
			if (GetConfig('UpdateInventoryLevels') == 1) {
				DecreaseInventoryFromOrder($newOrderId);
			}

			// Trigger new order notifications
			SendOrderNotifications($orderToken);

			$this->log->LogSystemDebug('ebay', 'An Item ('. $body['Item']['ItemID'] .') has been paid by the buyer and added to the store order (' . $newOrderId. ').');
			return true;
		}
		return false;
	}
예제 #10
0
 /**
  * Parse the submitted field data into an associative array
  *
  * Method will parse the submitted field data and convert it into an associative array
  * that resembles the shipping_addresses table structure
  *
  * @access private
  * @param array $fields The field list to parse from
  * @param int $formSessionId The optional form session ID
  * @return array The parsed array on success, FALSE on failure
  */
 private function parseFieldData($fields, $formSessionId = '')
 {
     if (!is_array($fields)) {
         return false;
     }
     $fieldMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Country' => 'country', 'Zip' => 'zip', 'Phone' => 'phone');
     $savedata = array();
     $countryFieldId = '';
     $stateFieldId = '';
     foreach (array_keys($fields) as $fieldId) {
         if (!array_key_exists($fields[$fieldId]->record['formfieldprivateid'], $fieldMap)) {
             continue;
         }
         $key = 'ship' . $fieldMap[$fields[$fieldId]->record['formfieldprivateid']];
         $savedata[$key] = isc_html_escape($fields[$fieldId]->getValue());
         if ($key == 'shipcountry') {
             $countryFieldId = $fieldId;
         } else {
             if ($key == 'shipstate') {
                 $stateFieldId = $fieldId;
             }
         }
     }
     $savedata['shipcustomerid'] = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerId();
     /**
      * Fill in the country and state IDs
      */
     $savedata['shipcountryid'] = GetCountryByName($fields[$countryFieldId]->getValue());
     if (isId($savedata['shipcountryid'])) {
         $savedata['shipstateid'] = GetStateByName($fields[$stateFieldId]->getValue(), $savedata['shipcountryid']);
     } else {
         $savedata['shipstateid'] = 0;
     }
     /**
      * Now save the form session record
      */
     $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ADDRESS, true, $formSessionId);
     if (isId($formSessionId)) {
         $savedata['shipformsessionid'] = $formSessionId;
     }
     return $savedata;
 }
예제 #11
0
/**
 * Parse the submitted field data into an associative array
 *
 * Method will parse the submitted field data and convert it into an associative array
 * that resembles the shipping_addresses table structure
 *
 * @access private
 * @param array $fields The field list to parse from
 * @param int $formSessionId The optional form session ID
 * @return array The parsed array on success, FALSE on failure
 */
function parseFieldData($fields, $formSessionId='')
{
	if (!is_array($fields)) {
		return false;
	}

	$fieldMap = getAddressFormMapping();
	$savedata = array();
	$countryFieldId = '';
	$stateFieldId = '';

	foreach (array_keys($fields) as $fieldId) {
		if (!array_key_exists($fields[$fieldId]->record['formfieldprivateid'], $fieldMap)) {
			continue;
		}

		$key = 'ship' . $fieldMap[$fields[$fieldId]->record['formfieldprivateid']];
		$savedata[$key] = $fields[$fieldId]->getValue();

		if ($key == 'shipcountry') {
			$countryFieldId = $fieldId;
		} else if ($key == 'shipstate') {
			$stateFieldId = $fieldId;
		}
	}

	$savedata['shipcustomerid'] = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerId();

	/**
	 * Fill in the country and state IDs
	 */
	$savedata['shipcountryid'] = GetCountryByName($fields[$countryFieldId]->getValue());

	if (isId($savedata['shipcountryid'])) {
		$savedata['shipstateid'] = GetStateByName($fields[$stateFieldId]->getValue(), $savedata['shipcountryid']);
	} else {
		$savedata['shipstateid'] = 0;
	}

	/**
	 * Now save the form session record
	 */
	$formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ADDRESS, true, $formSessionId);

	if (isId($formSessionId)) {
		$savedata['shipformsessionid'] = $formSessionId;
	}

	return $savedata;
}