/** * 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']; }
/** * 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']; }
/** * Create an actual order. * * @param array An array of information about the order. * @param array An array of items in the order. * @return string The token of the pending order. */ function CreateOrder($orderData, $orderProducts) { $entity = new ISC_ENTITY_ORDER(); // Delete any orders that are incomplete and were placed more than a week ago. This helps keep the database clean $entity->DeleteOldOrders(); // Delete the old configurable product files uploaded by the customers. DeleteOldConfigProductFiles(); $pendingToken = GenerateOrderToken(); $orderData['pending_token'] = $pendingToken; $vendorInfo = $orderData['vendorinfo']; unset($orderData['vendorinfo']); foreach ($vendorInfo as $vendorId => $vendorData) { $products = array(); foreach ($vendorData['products'] as $productId => $quantity) { $productInfo = $orderProducts[$productId]; $productInfo['quantity'] = $quantity; $products[] = $productInfo; } list($vendorId, ) = explode('_', $vendorId, 2); $vendorOrder = array_merge($orderData, $vendorData); $vendorOrder['products'] = $products; $vendorOrder['vendorid'] = $vendorId; // If we failed to add the order, stop //if(!$entity->add($vendorOrder)) { //return false; //} if ($_SESSION['makeaoffer'] == "Yes") { if (!$entity->offeradd($vendorOrder)) { return false; } } else { if (!$entity->add($vendorOrder)) { return false; } } } return $pendingToken; }
/** * Create an actual order. * * @param array An array of information about the order. * @param array An array of items in the order. * @return string The token of the pending order. */ function CreateOrder($orderData, $orderProducts) { $entity = new ISC_ENTITY_ORDER(); // Delete the old configurable product files uploaded by the customers. DeleteOldConfigProductFiles(); $pendingToken = GenerateOrderToken(); $orderData['ordtoken'] = $pendingToken; $vendorInfo = $orderData['vendorinfo']; unset($orderData['vendorinfo']); foreach($vendorInfo as $vendorId => $vendorData) { $products = array(); foreach($vendorData['products'] as $productId => $quantity) { $productInfo = $orderProducts[$productId]; $productInfo['quantity'] = $quantity; $products[] = $productInfo; } list($vendorId,) = explode('_', $vendorId, 2); $vendorOrder = array_merge($orderData, $vendorData); $vendorOrder['products'] = $products; $vendorOrder['vendorid'] = $vendorId; // If we failed to add the order, stop if(!$entity->add($vendorOrder)) { return false; } } return $pendingToken; }
/** * Insert/Update the node with the response record * * Method will insert/update the node with the response record * * @access protected * @param array $responseData The reponse data from QB * @param array $nodeData The optional node data array. If set then update, else insert * @return int The new or updtaed node ID on success, FALSE on error */ protected function syncResponseRecord2Store($responseData, $nodeData=false) { if (!is_array($responseData)) { $xargs = func_get_args(); throw new QBException("Invalid arguments when syncing order record from QB", $xargs); } /** * Get our stored customer ID if we have one */ $customerId = $this->getCustomer4Order($responseData["TxnID"]); /** * Get the customer ListID and find the matching customer ID if we can. We need to have a customer ListID */ if (is_null($customerId)) { if (!isset($responseData["CustomerRef"]["ListID"])) { throw new QBException("Unable to find customer ListID when syncing orders", $responseData); } $customerRef = $this->accounting->getReference("customer", '', $responseData["CustomerRef"]["ListID"], '', false); /** * If we don't have a reference then use the existing customer ID if we have one */ if (!is_array($customerRef)) { if (is_array($nodeData) && array_key_exists("ordcustid", $nodeData) && isId($nodeData["ordcustid"])) { $customerId = $nodeData["ordcustid"]; /** * Else if we do have a nodeData but no customer ID then its a guest checkout */ } else if (is_array($nodeData) && (!array_key_exists("ordcustid", $nodeData) || !isId($nodeData["ordcustid"]))) { $customerId = ''; /** * Else it is a new customer which we do not have a record for */ } else { $lastKid = end($this->spool["children"]); if ($lastKid["nodeType"] == "customer" && $lastKid["service"] == "query") { /** * If we couldn't find the record then error out */ if ($lastKid["errNo"] > 0) { throw new QBException("Unable to find customer when syncing orders from QB", $responseData["CustomerRef"]["ListID"]); } /** * Check to see if this is an anonymous customer (guest checkout). If so then don't create a customer record */ if ($this->accounting->isCustomerGuestCheckout($lastKid["response"])) { $customerId = ''; /** * Else it is a real customer so create it */ } else { $customerId = $this->customerSyncAPI->syncResponseRecord2Store($lastKid["response"]); if (!isId($customerId)) { throw new QBException("Unable to create customer record when syncing orders from QB", $lastKid["response"]); } $referenceDataSetup = $this->customerSyncAPI->referenceDataSetup; $referenceDataExternalKey = $this->customerSyncAPI->referenceDataExternalKey; $referenceReturn = $this->setReferenceDataStatically("customer", $customerId, $lastKid["response"], '', $referenceDataSetup, $referenceDataExternalKey); if (isId($referenceReturn)) { $customerRef = $this->accounting->getReference("customer", $referenceReturn, '', '', false); } } } else { $childRequestData = array( "ListID" => $responseData["CustomerRef"]["ListID"] ); return $this->execChildService("customer", "query", $childRequestData); } } /** * Else we have the customer but not the order yet */ } else if (is_array($customerRef)) { $customerId = $customerRef["accountingrefnodeid"]; /** * Else we got no customer */ } else { $customerId = ''; } /** * Save the customer ID for this order */ $this->setCustomer2Order($responseData["TxnID"], $customerId); } /** * If we have a custom ID then get the customer record as we'll need it later on */ $customerNodeData = ''; if (isId($customerId)) { $customerNodeData = $this->customerAPI->get($customerId); } if ($this->accounting->getValue("orderoption") == "order") { $salesLineRetTag = "SalesOrderLineRet"; } else { $salesLineRetTag = "SalesReceiptLineRet"; } /** * OK, we got the customer, now we need to get all the products */ if (!isset($responseData[$salesLineRetTag]) || !is_array($responseData[$salesLineRetTag]) || empty($responseData[$salesLineRetTag])) { throw new QBException("Missing/Invalid product array when syncing orders", array("tag" => $salesLineRetTag, "response" => $responseData)); } /** * Set aside some vars for shipping costs and the tax component */ $productSubTotal = 0; $shippingCost = 0; $taxCost = 0; /** * Sanatize it */ if (!isset($responseData[$salesLineRetTag][0])) { $responseData[$salesLineRetTag] = array($responseData[$salesLineRetTag]); } foreach ($responseData[$salesLineRetTag] as $product) { /** * Check to see if we have already recorded this product */ if ($this->checkProductListId4Order($responseData["TxnID"], $product["ItemRef"]["ListID"])) { continue; } /** * OK, we haven't done this one yet so lets do it. If we have any kids then deal with them first */ $lastKid = end($this->spool["children"]); if ($lastKid["service"] == "query" && ($lastKid["nodeType"] == "product" || $lastKid["nodeType"] == "productvariation")) { /** * If we couldn't find the record then error out */ if ($lastKid["errNo"] > 0) { throw new QBException("Unable to find product when syncing orders from QB", $product["ItemRef"]["ListID"]); } /** * Else try to add in this product/variation */ if ($lastKid["nodeType"] == "productvariation") { $productFatcory =& $this->productVariationSyncAPI; } else { $productFatcory =& $this->productSyncAPI; } $productData = $productFatcory->searchNodeByDB($lastKid["response"]); $productId = $productFatcory->syncResponseRecord2Store($lastKid["response"], $productData); /** * Dam! We can't add it. Error out of here as we really needed that product for the order */ if (!isId($productId)) { throw new QBException("Unable to create product/variation record when syncing orders from QB", $lastKid["response"]); } /** * Set the reference for this product */ $referenceDataSetup = $productFatcory->referenceDataSetup; $referenceDataExternalKey = $productFatcory->referenceDataExternalKey; $this->setReferenceDataStatically($lastKid["nodeType"], $productId, $lastKid["response"], '', $referenceDataSetup, $referenceDataExternalKey); } /** * There aren't any query kids so try and find the reference for this product/variation/other product */ $checkTypes = array("product", "productvariation", "prerequisite"); $productRef = ""; $productType = ""; foreach ($checkTypes as $checkType) { $productRef = $this->accounting->getReference($checkType, '', $product["ItemRef"]["ListID"], '', false); if (is_array($productRef)) { $productType = $checkType; break; } } /** * Check to see if this is a prerequisite (shipping & tax costs) */ if ($productType == "prerequisite") { switch (isc_strtolower(trim($productRef["accountingrefvalue"]["Type"]))) { case "shipping": $cost = ($product["Quantity"] * $product["Rate"]); break; case "tax": $cost = ($product["Quantity"] * $product["Rate"]); break; } $productNodeData = array( "Type" => isc_strtolower(trim($productRef["accountingrefvalue"]["Type"])), "Cost" => $cost ); $this->setProductListId2Order($responseData["TxnID"], $product["ItemRef"]["ListID"], $productType, $productNodeData, $product); /** * We don't want to insert this in the order_products table */ continue; } /** * OK, prerequisites are done, now for the rest. If no reference then send out a query child */ if (!is_array($productRef)) { if ($this->accounting->isProductVariationShortName($product["ItemRef"]["FullName"])) { $productType = "productvariation"; } else { $productType = "product"; } $childRequestData = array( "ListID" => $product["ItemRef"]["ListID"] ); return $this->execChildService($productType, "query", $childRequestData); } /** * Must have a reference by now */ if (!is_array($productRef)) { throw new QBException("Unable to find product reference when syncing order ID: " . $this->spool["nodeId"], $responseData); } $prodNodeData = ''; if ($productType == "productvariation") { $prodNodeData = $this->productVariationAPI->get($productRef["accountingrefnodeid"]); } else { $prodNodeData = $this->productAPI->get($productRef["accountingrefnodeid"]); } /** * If no prodNodeData then no go */ if (!is_array($prodNodeData)) { throw new QBException("Unable to find " . $productType . " node data when syncing order ID: " . $this->spool["nodeId"], array("order" => $responseData, "prodNodeId" => $productRef["accountingrefnodeid"])); } /** * Lastly, save this product to our tmp cache */ $this->setProductListId2Order($responseData["TxnID"], $product["ItemRef"]["ListID"], $productType, $prodNodeData, $product); } /** * OK, now retrieve all our product from our tmp cache to build the products for this order */ $products = array(); $taxCost = $shippingCost = 0; $cacheProducts = $this->getProductListIds4Order($responseData["TxnID"]); if (!is_array($cacheProducts) || empty($cacheProducts)) { throw new QBException("Empty product cache array when syncing order ID: " . $this->spool["nodeId"], $responseData); } foreach ($cacheProducts as $productListId => $product) { /** * Add up our stored shipping and tax costs if we have any */ if ($product["productType"] == "prerequisite") { switch (isc_strtolower(trim($product["productNodeData"]["Type"]))) { case "shipping": $shippingCost = $product["productNodeData"]["Cost"]; break; case "tax": $taxCost = $product["productNodeData"]["Cost"]; break; } continue; } $prodCode = ''; $prodVariationId = 0; $prodOptions = array(); if ($product["productType"] == "productvariation") { $prodCode = $product["productNodeData"]["vcsku"]; $prodVariationId = $product["productNodeData"]["combinationid"]; $prodOptions = $product["productNodeData"]["prodvariationarray"]; } if (trim($prodCode) == '') { $prodCode = $product["productNodeData"]["prodcode"]; } $products[] = array( "product_id" => $product["productNodeData"]["productid"], "product_name" => $product["productNodeData"]["prodname"], "product_code" => $prodCode, "quantity" => max(1, $product["productResponse"]["Quantity"]), "product_price" => $product["productResponse"]["Rate"], "original_price" => $product["productResponse"]["Rate"], "variation_id" => $prodVariationId, "options" => $prodOptions ); /** * Check to see if this is an existing product in an already existing order */ if (is_array($nodeData) && isset($nodeData["products"]) && is_array($nodeData["products"])) { foreach ($nodeData["products"] as $existingProduct) { if ($existingProduct["productid"] == $product["productNodeData"]["productid"] && isset($existingProduct["prodorderid"])) { $products[count($products)-1]["existing_order_product"] = $existingProduct["prodorderid"]; } } } /** * Add up our sub total */ $productSubTotal += $product["productResponse"]["Amount"]; } /** * OK, we have all the products and the customer details. Now for the actual order details */ $savedata = array( "ordcustid" => $customerId, "subtotal_ex_tax" => $productSubTotal, "total_tax" => $taxCost, "shipping_cost_ex_tax" => $shippingCost, "total_inc_tax" => ($productSubTotal + $taxCost + $shippingCost), "products" => $products ); if (isset($responseData["Memo"])) { $savedata["ordnotes"] = $responseData["Memo"]; } /** * Add in the addresses */ $addressMap = array( "shipaddress1" => "Addr1", "shipaddress2" => "Addr2", "shipcity" => "City", "shipstate" => "State", "shipzip" => "PostalCode", "shipcountry" => "Country" ); foreach (array("BillAddress", "ShipAddress") as $addressType) { if (!array_key_exists($addressType, $responseData) || !is_array($responseData[$addressType])) { $responseData[$addressType] = array(); } if ($addressType == "BillAddress") { $addressKey = "billingaddress"; } else { $addressKey = "shippingaddress"; } $savedata[$addressKey] = array(); foreach ($addressMap as $columnName => $refKey) { if (!isset($responseData[$addressType][$refKey]) && !is_array($nodeData)) { $responseData[$addressType][$refKey] = ''; } if (isset($responseData[$addressType][$refKey])) { $savedata[$addressKey][$columnName] = $responseData[$addressType][$refKey]; } } /** * Find the country and state IDs */ $countryId = $this->getCountryId(@$savedata[$addressKey]["shipcountry"], $properCountryName); $stateId = ''; if (isId($countryId) && trim(@$savedata[$addressKey]["shipstate"]) !== '') { $savedata[$addressKey]["shipcountry"] = $properCountryName; $stateId = $this->getStateId($savedata[$addressKey]["shipstate"], $countryId, $properStateName); if (!isId($stateId)) { $stateId = ''; } else if (trim($properStateName) !== '') { $savedata[$addressKey]["shipstate"] = $properStateName; } } else { $countryId = ''; } if (is_array($nodeData) || !isId($stateId)) { $savedata[$addressKey]["shipstateid"] = $stateId; } if (is_array($nodeData) || !isId($countryId)) { $savedata[$addressKey]["shipcountryid"] = $countryId; } /** * Fill in the name. Use whatever QB gave us regardless */ $customerName = @$responseData["CustomerRef"]["FullName"]; if ($this->accounting->isCustomerShortName($customerName)) { $tmpName = $this->accounting->qbCustomerShortName2CustomerNameId($customerName); if (is_array($tmpName) && array_key_exists("customername", $tmpName)) { $customerName = $tmpName["customername"]; } } else if ($this->accounting->isCustomerGuestShortName($customerName)) { $tmpName = $this->accounting->qbCustomerGuestShortName2CustomerGuestNameId($customerName); if (is_array($tmpName) && array_key_exists("customerguestname", $tmpName)) { $customerName = $tmpName["customerguestname"]; } } $nameParts = explode(" ", $customerName); if (count($nameParts) > 2) { $firstName = implode(" ", array_slice($nameParts, 0, count($nameParts)-1)); $lastName = $nameParts[count($nameParts)-1]; } else if (count($nameParts) == 1) { $firstName = $nameParts[0]; $lastName = ""; } else { $firstName = $nameParts[0]; $lastName = $nameParts[1]; } $savedata[$addressKey]["shipfirstname"] = $firstName; $savedata[$addressKey]["shiplastname"] = $lastName; /** * Set something to each field if it is NULL as the database can't handle NULL values for this schema */ foreach ($savedata[$addressKey] as $addKey => $addVal) { if (is_null($addVal)) { $savedata[$addressKey][$addKey] = ''; } } } /** * If we don't have a $nodeData then we can still fill in some blanks */ if (!is_array($nodeData)) { $savedata["ordtoken"] = GenerateOrderToken(); $savedata["ordstatus"] = ORDER_STATUS_COMPLETED; $savedata["orderpaymentmodule"] = "manual"; $savedata["orderpaymentmethod"] = GetLang("QuickBooksDefaultPaymentName"); $savedata["total_inc_tax"] = $savedata["totalcost"]; $savedata["handling_cost_ex_tax"] = 0; $savedata["handling_cost_inc_tax"] = 0; if (isset($savedata["billingaddress"]["shipcountry"])) { $savedata["ordgeoipcountry"] = $savedata["billingaddress"]["shipcountry"]; $savedata["ordgeoipcountrycode"] = GetCountryISO2ByName($savedata["billingaddress"]["shipcountry"]); } if (is_array($customerNodeData)) { $savedata["ordbillemail"] = $customerNodeData["custconemail"]; $savedata["ordbillphone"] = $customerNodeData["custconphone"]; $savedata["ordshipemail"] = $customerNodeData["custconemail"]; $savedata["ordshipphone"] = $customerNodeData["custconphone"]; } } else { $savedata["orderid"] = $nodeData["orderid"]; } /** * Alright, we have EVERYTHING, now create/update EVERYTHING */ $orderId = false; if (is_array($nodeData)) { /** * Reset the inventory levels before we update it */ if ($this->accounting->getValue("invlevels") !== ACCOUNTING_QUICKBOOKS_TYPE_QUICKBOOKS) { UpdateInventoryOnReturn($savedata["orderid"]); /* /lib/orders.php */ } if ($this->entityAPI->edit($savedata) !== false) { $orderId = $savedata["orderid"]; } /** * Now sync back the inventory levels */ if ($this->accounting->getValue("invlevels") !== ACCOUNTING_QUICKBOOKS_TYPE_QUICKBOOKS) { DecreaseInventoryFromOrder($orderId); } } else { $orderId = $this->entityAPI->add($savedata); /** * Sync up the inventory levels as each order is marked as completed */ if ($this->accounting->getValue("invlevels") !== ACCOUNTING_QUICKBOOKS_TYPE_QUICKBOOKS) { DecreaseInventoryFromOrder($orderId); } } if (!isId($orderId)) { $this->accounting->logError("ORDER DATA", array("SaveData" => $savedata, "NodeData" => $nodeData, "DB" => $GLOBALS["ISC_CLASS_DB"]->GetError())); throw new QBException("Cannot save order record with data from QB", array("SaveData" => $savedata, "NodeData" => $nodeData, "DB" => $GLOBALS["ISC_CLASS_DB"]->GetError())); } return $orderId; }