Example #1
0
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid']);
         $GLOBALS['CusFirstname'] = $billingDetails['shipfirstname'];
         # Baskaran
         /* Added the store credit as seperate as it may be disabled while add/edit order - vikas  */
         if (isset($data['custstorecredit'])) {
             $customerData['storecredit'] = DefaultPriceFormat($data['custstorecredit']);
         }
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     //2010-11-08 Ronnie add When calculating the ship infomation corresponding to no
     $GLOBALS['BCK_shipcountryid'] = $detailsVar['shipcountry'];
     $GLOBALS['BCK_shipstateid'] = $detailsVar['shipstate'];
     if ($GLOBALS['BCK_shipstateid'] == '') {
         $GLOBALS['BCK_shipcountryid'] = $billingDetails['shipcountry'];
         $GLOBALS['BCK_shipstateid'] = $billingDetails['shipstate'];
     }
     foreach ($this->GetCartApi()->GetProductsInCart() as $rowId => $product) {
         if (!isset($product['exists_order_coupon']) && isset($product['discount'])) {
             // Now workout the discount amount
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] - $product['discount'];
             } else {
                 // It's a percentage discount
                 $discount = $product['product_price'] / 100 * $product['discount'];
                 if ($discount == $product['product_price']) {
                     $newPrice = 0;
                 } else {
                     $newPrice = $product['product_price'] - $discount;
                 }
             }
             if ($newPrice < 0) {
                 $newPrice = 0;
             }
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $newPrice);
         } elseif (isset($product['exists_order_coupon']) && isset($product['discount'])) {
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $product['product_price']);
             $newPrice = 0;
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] + $product['discount'];
             } else {
                 // It's a percentage discount
                 $newPrice = $product['product_price'] / (1 - $product['discount'] / 100);
             }
             $this->GetCartApi()->SetItemValue($rowId, 'product_price', $newPrice);
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     //ronnie
     //$orderSummary['taxCost'];
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     /**********************************************************
     				Code added by Mayank Jaitly for getting the logged user
     				for adding his/her id as order owner.
     			************************************************************/
     $loggeduser = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUser();
     //////////  End of alteration
     $custid = $data['ordcustid'];
     $ordstatus = '';
     $query = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]customers c, [|PREFIX|]customer_groups cg WHERE c.customerid = '{$custid}' AND cg.customergroupid = c.custgroupid AND cg.groupname = 'Walk In' ");
     if ($GLOBALS['ISC_CLASS_DB']->CountResult($query) > 0) {
         $ordstatus = '10';
     } else {
         $ordstatus = $data['ordstatus'];
     }
     $billemail = $email;
     $shipemail = $email;
     if ($data['customerType'] == 'anonymous') {
         if (isset($data['anonymousemail']) && !empty($data['anonymousemail'])) {
             $billemail = $email;
             $shipemail = $email;
         } else {
             $billemail = $_POST['ordbillemail'];
             $shipemail = $_POST['ordshipemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $billemail, 'ordshipemail' => $shipemail, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'companygiftcertificateamount' => $orderSummary['companyGiftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno'], 'orderowner' => $loggeduser['pk_userid']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 } else {
                     if ($newOrder['paymentmethod'] == 'paypal_admin') {
                         // added new condition for paypal payment option - vikas
                         $newOrder['paymentmethodname'] = GetLang('PaypalPayment');
                     } else {
                         if ($newOrder['paymentmethod'] == 'googlecheckout_admin') {
                             $newOrder['paymentmethodname'] = GetLang('GooglePayment');
                         } else {
                             if ($newOrder['paymentmethod'] == 'creditcard') {
                                 $newOrder['paymentmethodname'] = GetLang('CreditCardPayment');
                             } else {
                                 if ($newOrder['paymentmethod'] == 'cash') {
                                     $newOrder['paymentmethodname'] = GetLang('CashPayment');
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         //Alandy_2011-14-20 debug credit amount error! recalculate the gatewayamount,fetch the gatewayamount from profer order is wrong!
         //$newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     // dada.wang 20120406 save cgc change
     $cgces = $this->GetCartApi()->Get('COMPANYGIFTCERTIFICATES');
     if (is_array($cgces) && !empty($cgces)) {
         $newOrder['companygiftcertificates'] = $cgces;
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         $newOrder['adminflag'] = 1;
         //dada.wang 2012-04-10 if has gc or cgc was remove then use this function to remove it
         $this->RemoveGCAndCGC($newOrder);
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $newOrder['adminflag'] = 1;
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
         $newOrder['orderid'] = $data['orderid'];
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     // Add by NI_20100827_Jack
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['companygiftcertificateamount'] > 0 && isset($newOrder['companygiftcertificates']) && !empty($newOrder['companygiftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES'] = GetClass('ISC_COMPANYGIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES']->ApplyCompanyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['companygiftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     /*************************************************************
     					Alterations done by Mayank Jaitly on 28 June 2010
     			**************************************************************/
     /*	
     // commented the below code as this is not needed.
     	$customerYMMdata=array(
     						   	'year' => $data['searchyear'],
     							'make' => $data['searchmake'],
     							'model' => MakeURLNormal($data['searchmodel']),
     							'bed_size' =>$data['bedsize'],
     							'cab_size' =>$data['cabsize']
     							
     						   );
     							   
     	$clarion_entity = new ISC_ADMIN_CLARION();
     	$ymmID=$clarion_entity->fnSaveUserYMM($customerYMMdata,$data['ordcustid'],$_REQUEST['customerType'],$data['orderid']);
     */
     /***********************	End of Alteration		*********/
     /***************************************************************
     				Code Added by Mayank Jaitly on 29 June 2010
     			****************************************************************/
     // commented the below code as this is not needed.
     //	$clarion_entity->fnUpdateOrderYMM($data['orderid'],$ymmID);
     /********************* End of code   **************************/
     return $data['orderid'];
 }
Example #2
0
		protected function editOrderSaveAction()
		{
			if (empty($_POST['quoteSession'])) {
				exit;
			}

			$quoteSession = $_POST['quoteSession'];

			/** @var ISC_QUOTE */
			$quote = getClass('ISC_ADMIN_ORDERS')->getQuoteSession($quoteSession);
			if(!$quote) {
				$this->sendEditOrderNoQuoteResponse('saveError');
			}

			try {
				$quote->setCustomerMessage(Interspire_Request::post('customerMessage'));
				$quote->setStaffNotes(Interspire_Request::post('staffNotes'));

				$entity = new ISC_ENTITY_ORDER;

				$currency = GetDefaultCurrency();
				$order = array(
					'ordcurrencyid' => $currency['currencyid'],
					'ordcurrencyexchangerate' => $currency['currencyexchangerate'],
					'ordipaddress' => getIp(),
					'extraInfo' => array(),
					'quote' => $quote,
				);

				$createAccount = false;

				// process customer details to see if an account should be made
				if (Interspire_Request::post('orderFor') == 'new') {
					// this really needs to be split off into another method because it's done both at the front end checkout, in save billing, and in here! -ge
					$password = '';
					$confirmedPassword = '';
					$email = '';
					$accountFormFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_ACCOUNT, true);
					$accountCustomFields = array();
					foreach($accountFormFields as $formFieldId => $formField) {
						$formFieldPrivateId = $formField->record['formfieldprivateid'];

						if (!$formFieldPrivateId) {
							$accountCustomFields[$formFieldId] = $formField->getValue();
						} else if($formFieldPrivateId == 'EmailAddress') {
							$email = $formField->getValue();
						} else if($formFieldPrivateId == 'Password') {
							$password = $formField->getValue();
						} else if($formFieldPrivateId == 'ConfirmPassword') {
							$confirmedPassword = $formField->getValue();
						}
					}

					// shouldn't reach this point with a valid email without all the details already being validated after step 1 > next, so go ahead and assign it to the order
					if ($email) {
						$createAccount = array(
							'addresses' => array(),
							'password' => $password,
							'customFormFields' => $accountCustomFields,
						);

						foreach ($quote->getAllAddresses() as /** @var ISC_QUOTE_ADDRESS */$address) {
							if (!$address->getSaveAddress()) {
								continue;
							}

							$customerAddress = $address->getAsArray();
							$customFields = $address->getCustomFields();
							if (!empty($customFields)) {
								$customerAddress['customFormFields'] = $customFields;

								// Shipping fields need to be mapped back to billing so they can be stored
								if ($address->getType() == ISC_QUOTE_ADDRESS::TYPE_SHIPPING) {
									$newCustomFields = array();
									$map = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, array_keys($customFields));
									foreach($map as $oldId => $newId) {
										$newCustomFields[$newId] = $customFields[$oldId];
									}
									$customerAddress['customFormFields'] = $newCustomFields;
								}
							}

							$createAccount['addresses'][] = $customerAddress;
						}
					}
				}

				if ($quote->getOrderId()) {
					$editing = true;
					$adding = false;

					$orderId = $quote->getOrderId();

					$existingOrder = $entity->get($orderId);
					if ($existingOrder['deleted']) {
						// don't allow saving changes for a deleted order
						$errors[] = GetLang('EditDeletedOrderError');
					} else {
						$order['orderid'] = $orderId;
						if (!$entity->edit($order)) {
							$errors[] = $entity->getError();
						}
					}
				} else {
					$editing = false;
					$adding = true;

					$order['orderpaymentmodule'] = '';

					$orderId = $entity->add($order);

					if ($orderId) {
						$quote->setOrderId($orderId);
					} else {
						$errors[] = $entity->getError();
					}
				}

				if (!empty($errors)) {
					$this->sendEditOrderResponse(array(
						'errors' => $errors,
						'stateTransition' => 'saveError',
					));
				}

				// retrieve the created/edited order record
				$order = GetOrder($orderId);

				if ($createAccount) {
					// this function doesn't return anything for error testing
					createOrderCustomerAccount($order, $createAccount);
				}

				// Process a payment
				$paymentMethod = Interspire_Request::post('paymentMethod');

				$providerSuccess = false;

				// Retrieve the payment method details
				$paymentFields = Interspire_Request::post('paymentField');
				if (!empty($paymentFields[$paymentMethod])) {
					$paymentFields = $paymentFields[$paymentMethod];
				}
				else {
					$paymentFields = array();
				}

				if ($quote->getGrandTotalWithStoreCredit() > 0 && ($adding || empty($order['ordpaymentstatus']) || empty($order['orderpaymentmodule'])) && !empty($paymentMethod)) {
					$gatewayAmount = $quote->getGrandTotalWithStoreCredit();

					$provider = null;

					// was a custom payment specified?
					if ($paymentMethod == 'custom') {
						$paymentMethodName = $paymentFields['custom_name'];
						$providerSuccess = true;
					}
					// actual payment module
					else {
						GetModuleById('checkout', $provider, $paymentMethod);
						if(is_object($provider)) {
							$paymentMethodName = $provider->GetDisplayName();

							if (method_exists($provider, 'ProcessManualPayment')) {
								// set the order token as required by various payment methods
								ISC_SetCookie('SHOP_ORDER_TOKEN', $order['ordtoken'], time() + (3600*24), true);
								// make the token immediately available
								$_COOKIE['SHOP_ORDER_TOKEN'] = $order['ordtoken'];

								// process the payment
								$result = $provider->ProcessManualPayment($order, $paymentFields);
								if ($result['result']) {
									$providerSuccess = true;
									$gatewayAmount = $result['amount'];

									FlashMessage(GetLang('OrderPaymentSuccess', array('amount' => FormatPrice($gatewayAmount), 'orderId' => $orderId, 'provider' => $paymentMethodName)), MSG_SUCCESS);
								}
								else {
									$errors[] = GetLang('OrderPaymentFail', array('orderId' => $orderId, 'provider' => $paymentMethodName, 'reason' => $result['message']));
								}
							}
							else {
								// all manual/offline methods will always be successfull
								$providerSuccess = true;
							}
						}
						else {
							// failed to get a payment module
						}
					}
				// if the grand total after minus the coupon,etc is 0 and it's adding order also the payment method is custom.
				} else if ($quote->getGrandTotalWithStoreCredit() == 0 && ($adding || empty($order['ordpaymentstatus']) || empty($order['orderpaymentmodule'])) && $paymentMethod == 'custom') {
					$paymentMethodName = $paymentFields['custom_name'];
					$providerSuccess = true;
				}

				// was payment successfull?
				if ($providerSuccess) {
					// record payment info for the order
					$updatedOrder = array(
						'orderpaymentmethod' 	=> $paymentMethodName,
						'orderpaymentmodule'	=> $paymentMethod,
					);

					$this->db->UpdateQuery("orders", $updatedOrder, "orderid = " . $orderId);

					// set appropriate status for the order
					if ($quote->isDigital()) {
						$newStatus = ORDER_STATUS_COMPLETED;
					}
					else {
						$newStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
					}
					UpdateOrderStatus($orderId, $newStatus, false);

					// email invoice
					if (Interspire_Request::post('emailInvoiceToCustomer')) {
						EmailInvoiceToCustomer($orderId);
					}
				}

				if (!empty($errors)) {
					$response = array(
						'errors' => $errors,
						'stateTransition' => 'saveError',
					);
				}
				else {
					if ($editing) {
						FlashMessage(GetLang('OrderUpdated', array('orderId' => $orderId)), MSG_SUCCESS);
					} else {
						FlashMessage(GetLang('OrderCreated', array('orderId' => $orderId)), MSG_SUCCESS);
					}

					$response = array(
						'stateTransition' => 'saveOk',
					);

					// remove quote object from session after successful save and successful payment
					getClass('ISC_ADMIN_ORDERS')->deleteQuoteSession($quoteSession);
				}

				if ($adding) {
					$response['updateOrderId'] = $orderId;
				}

				$this->sendEditOrderResponse($response);
			} catch (ISC_QUOTE_EXCEPTION $exception) {
				$this->sendEditOrderResponse(array(
					'stateTransition' => 'saveError',
					'errors' => array(
						$exception->getMessage(),
					),
				));
			}
		}
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid'], 'storecredit' => DefaultPriceFormat($data['custstorecredit']));
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $email, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         $newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     return $data['orderid'];
 }
Example #4
0
/**
 * Completes a pending order and marks it's status as whatever it should be next.
 * This function will process any payments, capture amounts from gateways, increase
 * # sold for each product in the order, etc.
 *
 * @param string The pending order token.
 * @param int The status to set the completed order to.
 * @return boolean True if successful, false on failure.
 */
function CompletePendingOrder($pendingOrderToken, $status, $sendInvoice=true)
{
	$orderData = LoadPendingOrdersByToken($pendingOrderToken, true);
	if($orderData === false) {
		return false;
	}

	$processedStoreCredit = false;
	$processedGiftCertificates = false;
	$orderStoreCredit = 0;
	$orderTotalAmount = 0;

	// Flag used to create the customer record but only if atleast one order was successful
	$createCustomer = false;

	// Sum up our total amount and store credit
	foreach ($orderData['orders'] as $order) {
		if ($order['ordstatus'] != 0) {
			continue;
		}

		$orderStoreCredit += $order['ordstorecreditamount'];
		$orderTotalAmount += $order['total_inc_tax'];
	}

	// flag to indicate if we should send notifications? only if the order was previously incomplete and the new status isn't declined/cancelled/refunded
	$sendNotifications = false;

	foreach($orderData['orders'] as $order) {
		$newStatus = $status;

		// Wait, was the order already complete? Then we don't do anything
		if($order['ordstatus'] != ORDER_STATUS_INCOMPLETE) {
			continue;
		}

		// If this order is digital, and the status is awaiting fulfillment, there's nothing
		// to actually fulfill, so set it to completed.
		if($order['ordisdigital'] && $newStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
			$newStatus = ORDER_STATUS_COMPLETED;
		}

		$extraInfo = @unserialize($order['extrainfo']);
		if(!is_array($extraInfo)) {
			$extraInfo = array();
		}

		// only email and update order data (coupons, certificates, store credit etc) if it's not a declined, cancelled or refunded order
		if($newStatus != ORDER_STATUS_DECLINED && $newStatus != ORDER_STATUS_CANCELLED && $newStatus != ORDER_STATUS_REFUNDED) {
			$createCustomer = true;
			$sendNotifications = true;

			if($sendInvoice && !EmailInvoiceToCustomer($order['orderid'], $newStatus)) {
				$GLOBALS['HideError'] = "";
				$GLOBALS['ErrorMessage'] = GetLang('ErroSendingInvoiceEmail');
				$GLOBALS['HideSuccess'] = "none";
			}

			// Are we updating the inventory levels when an order has been placed?
			if(GetConfig('UpdateInventoryLevels') == 1) {
				DecreaseInventoryFromOrder($order['orderid']);
			}

			// If this order now complete, we need to activate any gift certificates
			if(OrderIsComplete($newStatus)) {
				$GLOBALS['ISC_CLASS_GIFTCERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
				$GLOBALS['ISC_CLASS_GIFTCERTIFICATES']->ActivateGiftCertificates($order['orderid']);
			}

			// If we've had one or more coupons been applied to this order, we now need to increment the number of uses
			$couponIds = array();
			$query = "
				SELECT *
				FROM [|PREFIX|]order_coupons
				WHERE ordcouporderid='".(int)$order['orderid']."'
			";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			while($coupon = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$couponIds[] = $coupon['ordcouponid'];
			}
			if(!empty($couponIds)) {
				$couponsUsed = array_unique($couponIds);
				$couponList = implode(",", array_map("intval", $couponsUsed));
				$query = "
					UPDATE [|PREFIX|]coupons
					SET couponnumuses=couponnumuses+1
					WHERE couponid IN (".$couponList.")
				";
				$GLOBALS['ISC_CLASS_DB']->Query($query);

				foreach ($couponIds as $cid) {
					getclass('ISC_COUPON')->updatePerCustomerUsage($cid);
				}
			}

			// If we used store credit on this order, we now need to subtract it from the users account.
			if($order['ordstorecreditamount'] > 0 && $processedStoreCredit == false) {
				$GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
				$currentCredit = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerStoreCredit($order['ordcustid']);
				$newCredit = $currentCredit - $orderStoreCredit;
				if($newCredit < 0) {
					$newCredit = 0;
				}
				$updatedCustomer = array(
					'custstorecredit' => $newCredit,
				);
				$GLOBALS['ISC_CLASS_DB']->UpdateQuery('customers', $updatedCustomer, "customerid='".(int)$order['ordcustid']."'");
				$processedStoreCredit = true;
			}

			// If one or more gift certificates were used we need to apply them to this order and subtract the total
			if($order['ordgiftcertificateamount'] > 0 && isset($extraInfo['giftcertificates']) && !empty($extraInfo['giftcertificates']) && $processedGiftCertificates == false) {
				$usedCertificates = array();
				$GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
				$GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($order['orderid'], $orderTotalAmount + $order['ordgiftcertificateamount'], $extraInfo['giftcertificates'], $usedCertificates);
				unset($extraInfo['giftcertificates']);
				$processedGiftCertificates = true;
			}

			// If there are one or more digital products in this order then we need to create a record in the order_downloads table
			// for each of them and set the expiry dates
			$query = "
				SELECT ordprodid, ordprodqty
				FROM [|PREFIX|]order_products
				WHERE orderorderid='".$order['orderid']."' AND ordprodtype='digital'
			";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			$digitalProductIds = array();
			while($digitalProduct = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$digitalProductIds[$digitalProduct['ordprodid']] = $digitalProduct;
			}

			if(!empty($digitalProductIds)) {
				$query = "
					SELECT downloadid, productid, downexpiresafter, downmaxdownloads
					FROM [|PREFIX|]product_downloads
					WHERE productid IN (".implode(',', array_keys($digitalProductIds)).")
				";
				$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
				while($digitalDownload = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
					$expiryDate = 0;

					// If this download has an expiry date, set it to now + expiry time
					if($digitalDownload['downexpiresafter'] > 0) {
						$expiryDate = time() + $digitalDownload['downexpiresafter'];
					}

					// If they've purchased more than one, we need to give them max downloads X quantity downloads
					$quantity = $digitalProductIds[$digitalDownload['productid']]['ordprodqty'];

					$newDownload = array(
						'orderid' => $order['orderid'],
						'downloadid' => $digitalDownload['downloadid'],
						'numdownloads' => 0,
						'downloadexpires' => $expiryDate,
						'maxdownloads' => $digitalDownload['downmaxdownloads'] * $quantity
					);
					$GLOBALS['ISC_CLASS_DB']->InsertQuery('order_downloads', $newDownload);
				}
			}
		}

		// Does a customer account need to be created?
		if(!empty($extraInfo['createAccount'])) {
			createOrderCustomerAccount($order, $extraInfo['createAccount']);
			unset($extraInfo['createAccount']);
		}

		// Now update the order and set the status
		$updatedOrder = array(
			"ordstatus" => $newStatus,
			"extrainfo" => serialize($extraInfo)
		);
		$GLOBALS['ISC_CLASS_DB']->UpdateQuery("orders", $updatedOrder, "orderid='".$order['orderid']."'");
	}

	if($sendNotifications) {
		// Trigger all active new order notification methods
		SendOrderNotifications($pendingOrderToken);

		// Do we need to add them to a Interspire Email Marketer mailing list?
		SubscribeCustomerToLists($pendingOrderToken);

		// Update the current uses of each rule
		$quote = getCustomerQuote();
		$appliedRules = array_keys(getCustomerQuote()->getAppliedDiscountRules());
		if(!empty($appliedRules)) {
			require_once ISC_BASE_PATH.'/lib/rule.php';
			updateRuleUses($appliedRules);
		}
	}

	// Empty the users cart and kill the checkout process
	EmptyCartAndKillCheckout();

	return true;
}
Example #5
0
/**
 * Completes a pending order and marks it's status as whatever it should be next.
 * This function will process any payments, capture amounts from gateways, increase
 * # sold for each product in the order, etc.
 *
 * @param string The pending order token.
 * @param int The status to set the completed order to.
 * @return boolean True if successful, false on failure.
 */
function CompletePendingOrder($pendingOrderToken, $status, $sendInvoice = true)
{
    $orderData = LoadPendingOrdersByToken($pendingOrderToken, true);
    if ($orderData === false) {
        return false;
    }
    $processedStoreCredit = false;
    $processedGiftCertificates = false;
    $orderStoreCredit = 0;
    $orderTotalAmount = 0;
    // Sum up our total amount and store credit
    foreach ($orderData['orders'] as $order) {
        if ($order['ordstatus'] != 0) {
            continue;
        }
        $orderStoreCredit += $order['ordstorecreditamount'];
        $orderTotalAmount += $order['ordtotalamount'];
    }
    foreach ($orderData['orders'] as $order) {
        // Wait, was the order already complete? Then we don't do anything
        if ($order['ordstatus'] != 0) {
            continue;
        }
        // If this order is digital, and the status is awaiting fulfillment, there's nothing
        // to actually fulfill, so set it to completed.
        if ($order['ordisdigital'] && $status == ORDER_STATUS_AWAITING_FULFILLMENT) {
            $status = ORDER_STATUS_COMPLETED;
        }
        // Don't email the customer if this order was declined
        if ($status != ORDER_STATUS_DECLINED) {
            if ($sendInvoice && !EmailInvoiceToCustomer($order['orderid'], $status)) {
                $GLOBALS['HideError'] = "";
                $GLOBALS['ErrorMessage'] = GetLang('ErroSendingInvoiceEmail');
                $GLOBALS['HideSuccess'] = "none";
            }
            // Are we updating the inventory levels when an order has been placed?
            if (GetConfig('UpdateInventoryLevels') == 1) {
                DecreaseInventoryFromOrder($order['orderid']);
            }
        }
        // If this order now complete, we need to activate any gift certificates
        if (OrderIsComplete($status)) {
            $GLOBALS['ISC_CLASS_GIFTCERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
            $GLOBALS['ISC_CLASS_GIFTCERTIFICATES']->ActivateGiftCertificates($order['orderid']);
        }
        // If we've had one or more coupons been applied to this order, we now need to increment the number of uses
        $couponIds = array();
        $query = "\n\t\t\tSELECT *\n\t\t\tFROM [|PREFIX|]order_coupons\n\t\t\tWHERE ordcouporderid='" . (int) $order['orderid'] . "'\n\t\t";
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        while ($coupon = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            $couponIds[] = $coupon['ordcouponid'];
        }
        if (!empty($couponIds)) {
            $couponsUsed = array_unique($couponIds);
            $couponList = implode(",", array_map("intval", $couponsUsed));
            $query = "\n\t\t\t\tUPDATE [|PREFIX|]coupons\n\t\t\t\tSET couponnumuses=couponnumuses+1\n\t\t\t\tWHERE couponid IN (" . $couponList . ")\n\t\t\t";
            $GLOBALS['ISC_CLASS_DB']->Query($query);
        }
        // If we used store credit on this order, we now need to subtract it from the users account.
        if ($order['ordstorecreditamount'] > 0 && $processedStoreCredit == false) {
            $GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
            $currentCredit = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerStoreCredit($order['ordcustid']);
            $newCredit = $currentCredit - $orderStoreCredit;
            if ($newCredit < 0) {
                $newCredit = 0;
            }
            $updatedCustomer = array('custstorecredit' => $newCredit);
            $GLOBALS['ISC_CLASS_DB']->UpdateQuery('customers', $updatedCustomer, "customerid='" . (int) $order['ordcustid'] . "'");
            $processedStoreCredit = true;
        }
        $extraInfo = @unserialize($order['extrainfo']);
        if (!is_array($extraInfo)) {
            $extraInfo = array();
        }
        // If one or more gift certificates were used we need to apply them to this order and subtract the total
        if ($order['ordgiftcertificateamount'] > 0 && isset($extraInfo['giftcertificates']) && !empty($extraInfo['giftcertificates']) && $processedGiftCertificates == false) {
            $usedCertificates = array();
            $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
            $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($order['orderid'], $orderTotalAmount, $extraInfo['giftcertificates'], $usedCertificates);
            unset($extraInfo['giftcertificates']);
            $processedGiftCertificates = true;
        }
        // If there are one or more digital products in this order then we need to create a record in the order_downloads table
        // for each of them and set the expiry dates
        $query = "\n\t\t\tSELECT ordprodid, ordprodqty\n\t\t\tFROM [|PREFIX|]order_products\n\t\t\tWHERE orderorderid='" . $order['orderid'] . "' AND ordprodtype='digital'\n\t\t";
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        $digitalProductIds = array();
        while ($digitalProduct = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            $digitalProductIds[$digitalProduct['ordprodid']] = $digitalProduct;
        }
        if (!empty($digitalProductIds)) {
            $query = "\n\t\t\t\tSELECT downloadid, productid, downexpiresafter, downmaxdownloads\n\t\t\t\tFROM [|PREFIX|]product_downloads\n\t\t\t\tWHERE productid IN (" . implode(',', array_keys($digitalProductIds)) . ")\n\t\t\t";
            $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
            while ($digitalDownload = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
                $expiryDate = 0;
                // If this download has an expiry date, set it to now + expiry time
                if ($digitalDownload['downexpiresafter'] > 0) {
                    $expiryDate = time() + $digitalDownload['downexpiresafter'];
                }
                // If they've purchased more than one, we need to give them max downloads X quantity downloads
                $quantity = $digitalProductIds[$digitalDownload['productid']]['ordprodqty'];
                $newDownload = array('orderid' => $order['orderid'], 'downloadid' => $digitalDownload['downloadid'], 'numdownloads' => 0, 'downloadexpires' => $expiryDate, 'maxdownloads' => $digitalDownload['downmaxdownloads'] * $quantity);
                $GLOBALS['ISC_CLASS_DB']->InsertQuery('order_downloads', $newDownload);
            }
        }
        // Now update the order and set the status
        $updatedOrder = array("ordstatus" => $status, "extrainfo" => serialize($extraInfo));
        $GLOBALS['ISC_CLASS_DB']->UpdateQuery("orders", $updatedOrder, "orderid='" . $order['orderid'] . "'");
    }
    return true;
}
Example #6
0
<?php

include(dirname(__FILE__)."/init.php");
EmailInvoiceToCustomer(2);