/** * Init tax override object * * @param string $taxOverrideType * @param string $reason * @param float $taxAmount * @return TaxOverride */ protected function _getTaxOverrideObject($taxOverrideType, $reason, $taxAmount) { $taxOverride = new TaxOverride(); $taxOverride->setTaxOverrideType($taxOverrideType); $taxOverride->setReason($reason); $taxOverride->setTaxAmount($taxAmount); return $taxOverride; }
private function createTaxOverride($date, $orderStatus = 'R', $reason = '') { if (!class_exists('TaxOverride')) { require VMAVALARA_CLASS_PATH . DS . 'TaxOverride.class.php'; } if (!class_exists('TaxOverrideType')) { require VMAVALARA_CLASS_PATH . DS . 'TaxOverrideType.class.php'; } $taxOverride = new TaxOverride(); $taxOverride->setTaxOverrideType(TaxOverrideType::$TaxDate); //TaxOverrideType $None, $TaxAmount, $Exemption, $TaxDate ??? //$taxOverride->setTaxAmount($value); //decimal $taxOverride->setTaxDate($date); //date format? if (empty($reason)) { $user = JFactory::getUser(); $reason = 'Vm_' . $orderStatus . '_by_' . $user->name; } $taxOverride->setReason($reason); return $taxOverride; }
/** * Save order in AvaTax system * * @see OnePica_AvaTax_Model_Observer_SalesOrderCreditmemoSaveAfter::execute() * @param Mage_Sales_Model_Order_Creditmemo $creditmemo * @param OnePica_AvaTax_Model_Records_Queue $queue * @return OnePica_AvaTax_Model_Service_Result_Creditmemo */ public function creditmemo($creditmemo, $queue) { $this->_lines = array(); $order = $creditmemo->getOrder(); $storeId = $order->getStoreId(); $orderDate = $this->_convertGmtDate($order->getCreatedAt(), $storeId); $statusDate = $this->_convertGmtDate($queue->getUpdatedAt(), $storeId); $creditmemoDate = $this->_convertGmtDate($creditmemo->getCreatedAt(), $storeId); $shippingAddress = $order->getShippingAddress() ? $order->getShippingAddress() : $order->getBillingAddress(); $this->_request = new GetTaxRequest(); $this->_request->setDocCode($creditmemo->getIncrementId()); $this->_request->setDocType(DocumentType::$ReturnInvoice); $this->_addGeneralInfo($order); $this->_addShipping($creditmemo, true); $items = $creditmemo->getAllItems(); $this->_initProductCollection($items); $this->_initTaxClassCollection($creditmemo); //Added code for calculating tax for giftwrap items $this->_addGwOrderAmount($creditmemo, true); $this->_addGwItemsAmount($creditmemo, true); $this->_addGwPrintedCardAmount($creditmemo, true); $this->_addAdjustments($creditmemo->getBaseAdjustmentPositive(), $creditmemo->getBaseAdjustmentNegative(), $order->getStoreId()); $this->_setOriginAddress($order->getStoreId()); $this->_setDestinationAddress($shippingAddress); // Set the tax date for calculation. $override = new TaxOverride(); $override->setTaxDate($orderDate); $override->setTaxOverrideType(TaxOverrideType::$TaxDate); $override->setReason('Credit memo - refund'); $this->_request->setTaxOverride($override); $this->_request->setDocDate($creditmemoDate); $this->_request->setPaymentDate($creditmemoDate); $this->_request->setTaxDate($orderDate); $this->_request->setStatusDate($statusDate); $configAction = Mage::getStoreConfig('tax/avatax/action', $order->getStoreId()); $commitAction = OnePica_AvaTax_Model_Service_Abstract_Config::ACTION_CALC_SUBMIT_COMMIT; $this->_request->setCommit($configAction == $commitAction ? true : false); foreach ($items as $item) { /** @var Mage_Sales_Model_Order_Creditmemo_Item $item */ $this->_newLine($item, true); } $this->_request->setLines($this->_lines); //send to AvaTax $result = $this->_send($order->getStoreId()); /** @var OnePica_AvaTax_Model_Service_Result_Creditmemo $creditmemoResult */ $creditmemoResult = Mage::getModel('avatax/service_result_creditmemo'); $resultHasError = $result->getResultCode() != SeverityLevel::$Success; $creditmemoResult->setHasError($resultHasError); //if successful if (!$resultHasError) { $totalTax = $result->getTotalTax(); $creditmemoResult->setTotalTax($totalTax); $documentCode = $result->getDocCode(); $creditmemoResult->setDocumentCode($documentCode); //if not successful } else { $messages = array(); foreach ($result->getMessages() as $message) { $messages[] = $message->getSummary(); } $creditmemoResult->setErrors($messages); } return $creditmemoResult; }
/** * @brief Executes tax actions on documents * * @param Array $products Array of Product for which taxes need to be calculated * @param Array $params * type : (default SalesOrder) SalesOrder|SalesInvoice|ReturnInvoice * cart : (required for SalesOrder and SalesInvoice) Cart object * DocCode : (required in ReturnInvoice, and when 'cart' is not set) Specify the Document Code * */ public function getTax($products = array(), $params = array()) { $confValues = Configuration::getMultiple(array('AVALARATAX_COMPANY_CODE', 'AVALARATAX_ADDRESS_LINE1', 'AVALARATAX_ADDRESS_LINE2', 'AVALARATAX_CITY', 'AVALARATAX_STATE', 'AVALARATAX_ZIP_CODE')); if (!isset($params['type'])) { $params['type'] = 'SalesOrder'; } $this->_connectToAvalara(); $client = new TaxServiceSoap(Configuration::get('AVALARATAX_MODE')); $request = new GetTaxRequest(); if (isset($params['cart']) && (int) $params['cart']->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) { $address = new Address((int) $params['cart']->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } elseif (isset($this->context->cookie) && isset($this->contract->cookie->id_customer) && $this->context->cookie->id_customer) { $address = new Address((int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $this->context->cookie->id_customer . ' AND active = 1 AND deleted = 0')); } if (isset($address)) { if (!empty($address->id_state)) { $state = new State((int) $address->id_state); } $addressDest = array(); $addressDest['Line1'] = $address->address1; $addressDest['Line2'] = $address->address2; $addressDest['City'] = $address->city; $addressDest['Region'] = isset($state) ? $state->iso_code : ''; $addressDest['PostalCode'] = $address->postcode; $addressDest['Country'] = Country::getIsoById($address->id_country); // Try to normalize the address depending on option in the BO if (Configuration::get('AVALARATAX_ADDRESS_NORMALIZATION')) { $normalizedAddress = $this->validateAddress($address); } if (isset($normalizedAddress['Normalized'])) { $addressDest = $normalizedAddress['Normalized']; } // Add Destination address (Customer address) $destination = new AvalaraAddress(); $destination->setLine1($addressDest['Line1']); $destination->setLine2($addressDest['Line2']); $destination->setCity($addressDest['City']); $destination->setRegion($addressDest['Region']); $destination->setPostalCode($addressDest['PostalCode']); $destination->setCountry($addressDest['Country']); $request->setDestinationAddress($destination); } // Origin Address (Store Address or address setup in BO) $origin = new AvalaraAddress(); $origin->setLine1(isset($confValues['AVALARATAX_ADDRESS_LINE1']) ? $confValues['AVALARATAX_ADDRESS_LINE1'] : ''); $origin->setLine2(isset($confValues['AVALARATAX_ADDRESS_LINE2']) ? $confValues['AVALARATAX_ADDRESS_LINE2'] : ''); $origin->setCity(isset($confValues['AVALARATAX_CITY']) ? $confValues['AVALARATAX_CITY'] : ''); $origin->setRegion(isset($confValues['AVALARATAX_STATE']) ? $confValues['AVALARATAX_STATE'] : ''); $origin->setPostalCode(isset($confValues['AVALARATAX_ZIP_CODE']) ? $confValues['AVALARATAX_ZIP_CODE'] : ''); $request->setOriginAddress($origin); $request->setCompanyCode(isset($confValues['AVALARATAX_COMPANY_CODE']) ? $confValues['AVALARATAX_COMPANY_CODE'] : ''); $orderId = isset($params['cart']) ? (int) $params['cart']->id : (int) $params['DocCode']; $nowTime = date('mdHis'); // Type: Only supported types are SalesInvoice or SalesOrder if ($params['type'] == 'SalesOrder') { // SalesOrder: Occurs when customer adds product to the cart (generally to check how much the tax will be) $request->setDocType(DocumentType::$SalesOrder); } elseif ($params['type'] == 'SalesInvoice') { $request->setDocType(DocumentType::$SalesInvoice); $orderId = Db::getInstance()->getValue('SELECT `id_order` FROM ' . _DB_PREFIX_ . 'orders WHERE `id_cart` = ' . (int) $params['cart']->id); // Make sure we got the orderId, even if it was/wasn't passed in $params['DocCode'] } elseif ($params['type'] == 'ReturnInvoice') { $orderId = isset($params['type']) && $params['type'] == 'ReturnInvoice' ? $orderId . '.' . $nowTime : $orderId; $orderDate = Db::getInstance()->ExecuteS(' SELECT `id_order`, `date_add` FROM `' . _DB_PREFIX_ . 'orders` WHERE ' . (isset($params['cart']) ? '`id_cart` = ' . (int) $params['cart']->id : '`id_order` = ' . (int) $params['DocCode'])); $request->setDocType(DocumentType::$ReturnInvoice); $request->setCommit(true); $taxOverride = new TaxOverride(); $taxOverride->setTaxOverrideType(TaxOverrideType::$TaxDate); $taxOverride->setTaxDate(date('Y-m-d', strtotime($orderDate[0]['date_add']))); $taxOverride->setReason('Refund'); $request->setTaxOverride($taxOverride); } if (isset($this->context->cookie->id_customer)) { $customerCode = $this->context->cookie->id_customer; } else { if (isset($params['DocCode'])) { $id_order = (int) $params['DocCode']; } elseif (isset($_POST['id_order'])) { $id_order = (int) $_POST['id_order']; } elseif (isset($params['id_order'])) { $id_order = (int) $params['id_order']; } else { $id_order = 0; } $customerCode = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'orders` WHERE `id_order` = ' . (int) $id_order); } $request->setDocCode('Order ' . Tools::safeOutput($orderId)); // Order Id - has to be float due to the . and more numbers for returns $request->setDocDate(date('Y-m-d')); // date $request->setCustomerCode('CustomerID: ' . (int) $customerCode); // string Required $request->setCustomerUsageType(''); // string Entity Usage $request->setDiscount(0.0); // decimal $request->setDetailLevel(DetailLevel::$Tax); // Summary or Document or Line or Tax or Diagnostic // Add line $lines = array(); $i = 0; foreach ($products as $product) { // Retrieve the tax_code for the current product if not defined if (isset($params['taxable']) && !$params['taxable']) { $taxCode = 'NT'; } else { $taxCode = !isset($product['tax_code']) ? $this->getProductTaxCode((int) $product['id_product']) : $product['tax_code']; } if (isset($product['id_product'])) { $line = new Line(); $line->setNo($i++); // string line Number of invoice ($i) $line->setItemCode((int) $product['id_product'] . ' - ' . substr($product['name'], 0, 20)); $line->setDescription(substr(Tools::safeOutput($product['name'] . ' - ' . $product['description_short']), 0, 250)); $line->setTaxCode($taxCode); $line->setQty(isset($product['quantity']) ? (double) $product['quantity'] : 1); $line->setAmount($params['type'] == 'ReturnInvoice' && (double) $product['total'] > 0 ? (double) $product['total'] * -1 : (double) $product['total']); $line->setDiscounted(false); $lines[] = $line; } } // Send shipping as new line if (isset($params['cart'])) { $line = new Line(); $line->setNo('Shipping'); // string line Number of invoice ($i) $line->setItemCode('Shipping'); $line->setDescription('Shipping costs'); if (isset($params['taxable']) && !$params['taxable']) { $line->setTaxCode('NT'); } else { $line->setTaxCode('FR020100'); } // Default TaxCode for Shipping. Avalara will decide depending on the State if taxes should be charged or not $line->setQty(1); $line->setAmount((double) $params['cart']->getOrderTotal(false, Cart::ONLY_SHIPPING)); $line->setDiscounted(false); $lines[] = $line; } $request->setLines($lines); $buffer = array(); try { $result = $client->getTax($request); $buffer['ResultCode'] = Tools::safeOutput($result->getResultCode()); if ($result->getResultCode() == SeverityLevel::$Success) { $buffer['DocCode'] = Tools::safeOutput($request->getDocCode()); $buffer['TotalAmount'] = Tools::safeOutput($result->getTotalAmount()); $buffer['TotalTax'] = Tools::safeOutput($result->getTotalTax()); $buffer['NowTime'] = $nowTime; foreach ($result->getTaxLines() as $ctl) { $buffer['TaxLines'][$ctl->getNo()]['GetTax'] = Tools::safeOutput($ctl->getTax()); $buffer['TaxLines'][$ctl->getNo()]['TaxCode'] = Tools::safeOutput($ctl->getTaxCode()); foreach ($ctl->getTaxDetails() as $ctd) { $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['JurisType'] = Tools::safeOutput($ctd->getJurisType()); $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['JurisName'] = Tools::safeOutput($ctd->getJurisName()); $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Region'] = Tools::safeOutput($ctd->getRegion()); $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Rate'] = Tools::safeOutput($ctd->getRate()); $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Tax'] = Tools::safeOutput($ctd->getTax()); } } } else { foreach ($result->getMessages() as $msg) { $buffer['Messages']['Name'] = Tools::safeOutput($msg->getName()); $buffer['Messages']['Summary'] = Tools::safeOutput($msg->getSummary()); } } } catch (SoapFault $exception) { $buffer['Exception']['FaultString'] = Tools::safeOutput($exception->faultstring); $buffer['Exception']['LastRequest'] = Tools::safeOutput($client->__getLastRequest()); $buffer['Exception']['LastResponse'] = Tools::safeOutput($client->__getLastResponse()); } return $buffer; }
/** * Save order in AvaTax system * * @see OnePica_AvaTax_Model_Observer::salesOrderPlaceAfter() * @param Mage_Sales_Model_Order_Creditmemo $creditmemo * @param OnePica_AvaTax_Model_Records_Queue $queue * @return mixed * @throws OnePica_AvaTax_Exception * @throws OnePica_AvaTax_Model_Avatax_Exception_Commitfailure * @throws OnePica_AvaTax_Model_Avatax_Exception_Unbalanced */ public function creditmemo($creditmemo, $queue) { $order = $creditmemo->getOrder(); $storeId = $order->getStoreId(); $orderDate = $this->_convertGmtDate($order->getCreatedAt(), $storeId); $statusDate = $this->_convertGmtDate($queue->getUpdatedAt(), $storeId); $creditmemoDate = $this->_convertGmtDate($creditmemo->getCreatedAt(), $storeId); $shippingAddress = $order->getShippingAddress() ? $order->getShippingAddress() : $order->getBillingAddress(); if (!$shippingAddress) { throw new OnePica_AvaTax_Exception($this->__('There is no address attached to this order')); } $this->_request = new GetTaxRequest(); $this->_request->setDocCode($creditmemo->getIncrementId()); $this->_request->setDocType(DocumentType::$ReturnInvoice); $this->_addGeneralInfo($order); $this->_addShipping($creditmemo, true); $items = $creditmemo->getAllItems(); $this->_initProductCollection($items); $this->_initTaxClassCollection($creditmemo); //Added code for calculating tax for giftwrap items $this->_addGwOrderAmount($creditmemo, true); $this->_addGwItemsAmount($creditmemo, true); $this->_addGwPrintedCardAmount($creditmemo, true); $this->_addAdjustments($creditmemo->getAdjustmentPositive(), $creditmemo->getAdjustmentNegative(), $order->getStoreId()); $this->_setOriginAddress($order->getStoreId()); $this->_setDestinationAddress($shippingAddress); // Set the tax date for calculation. $override = new TaxOverride(); $override->setTaxDate($orderDate); $override->setTaxOverrideType(TaxOverrideType::$TaxDate); $override->setReason('Credit memo - refund'); $this->_request->setTaxOverride($override); $this->_request->setDocDate($creditmemoDate); $this->_request->setPaymentDate($creditmemoDate); $this->_request->setTaxDate($orderDate); $this->_request->setStatusDate($statusDate); $configAction = Mage::getStoreConfig('tax/avatax/action', $order->getStoreId()); $commitAction = OnePica_AvaTax_Model_Config::ACTION_CALC_SUBMIT_COMMIT; $this->_request->setCommit($configAction == $commitAction ? true : false); foreach ($items as $item) { /** @var Mage_Sales_Model_Order_Creditmemo_Item $item */ $this->_newLine($item, true); } $this->_request->setLines($this->_lines); //send to AvaTax $result = $this->_send($order->getStoreId()); //if successful if ($result->getResultCode() == SeverityLevel::$Success) { $message = Mage::helper('avatax')->__('Credit memo #%s was saved to AvaTax', $result->getDocCode()); $this->_addStatusHistoryComment($order, $message); if ($result->getTotalTax() != $creditmemo->getBaseTaxAmount() * -1) { throw new OnePica_AvaTax_Model_Avatax_Exception_Unbalanced('Collected: ' . $creditmemo->getTaxAmount() . ', Actual: ' . $result->getTotalTax()); } //if not successful } else { $messages = array(); foreach ($result->getMessages() as $message) { $messages[] = $message->getSummary(); } throw new OnePica_AvaTax_Model_Avatax_Exception_Commitfailure(implode(' // ', $messages)); } return $result; }
private function CreateTaxRequestForTaxOverrideType($docCode) { $request = new GetTaxRequest(); $request->setCompanyCode("DEFAULT"); $request->setDocCode($docCode); $request->setDocType(DocumentType::$PurchaseOrder); $dateTime = new DateTime(); $docDate = date_format($dateTime, "Y-m-d"); $request->setDocDate($docDate); $request->setCustomerCode("TaxSvcTest"); $request->setSalespersonCode(""); $request->setDetailLevel(DetailLevel::$Tax); $origin = new Address(); $origin->setAddressCode("Origin"); $origin->setCity("Denver"); $origin->setRegion("CO"); $origin->setPostalCode("80216-1022"); $origin->setCountry("USA"); $request->setOriginAddress($origin); $destination = new Address(); $destination->setAddressCode("Dest"); $destination->setLine1("11051 S Parker Rd"); $destination->setCity("Parker"); $destination->setRegion("CO"); $destination->setPostalCode("80134-7441"); $destination->setCountry("USA"); $request->setDestinationAddress($destination); $line = new Line(); $line->setNo("1"); $line->setQty(1); $line->setAmount(0); $taxOverride = new TaxOverride(); $taxOverride->setTaxOverrideType(TaxOverrideType::$AccruedTaxAmount); $taxOverride->setTaxAmount(21.1); $taxOverride->setReason("Accrued"); $line->setTaxOverride($taxOverride); $request->setLines(array($line)); return $request; }