private function cancelOrder($data, $old_order_status) { // vmdebug('my data on cancelOrder ',$data); // if(empty($data->invoice_number)) return false; $orderModel = VmModel::getModel('orders'); $orderDetails = $orderModel->getOrder($data->virtuemart_order_id); $calc = $this->getOrderCalc($orderDetails); if (!$calc) { return false; } $invoiceNumber = 'onr_' . $orderDetails['details']['BT']->order_number; $orderModel->createInvoiceNumber($orderDetails['details']['BT'], $invoiceNumber); if (!$invoiceNumber) { vmInfo('No invoice created, no reason to cancel at Avatax'); return false; } if (is_array($invoiceNumber)) { $invoiceNumber = $invoiceNumber[0]; } # if (!function_exists('EnsureIsArray')) { require VMAVALARA_PATH . DS . 'AvaTax.php'; } // include in all Avalara Scripts if (!class_exists('TaxServiceSoap')) { require VMAVALARA_CLASS_PATH . DS . 'TaxServiceSoap.class.php'; } if (!class_exists('CancelTaxRequest')) { require VMAVALARA_CLASS_PATH . DS . 'CancelTaxRequest.class.php'; } $this->newATConfig($calc); $client = new TaxServiceSoap($this->_connectionType); $request = new CancelTaxRequest(); $request->setDocCode($invoiceNumber); $request->setDocType(DocumentType::$SalesInvoice); $request->setCompanyCode($calc['company_code']); // Dashboard Company Code if ($calc['committ'] == 0) { return false; } //CancelCode: Enter D for DocDeleted, or P for PostFailed: [D] //I do not know the difference, I use always D (I assume this means order got deleted, cancelled, or refund) $code = CancelCode::$DocDeleted; $request->setCancelCode($code); try { avadebug('plgVmOnCancelPayment used request', $request); $result = $client->cancelTax($request); if ($result->getResultCode() != "Success") { $msg = ''; foreach ($result->getMessages() as $rmsg) { $msg .= $rmsg->getName() . ": " . $rmsg->getSummary() . "\n"; } vmError($msg); } else { vmInfo('CancelTax ResultCode is: ' . $result->getResultCode()); } } catch (SoapFault $exception) { $msg = "Exception: "; if ($exception) { $msg .= $exception->faultstring; } $msg .= "\n"; $msg .= $client->__getLastRequest() . "\n"; $msg .= $client->__getLastResponse() . "\n"; vmError($msg); } }
public function tax($type, $params = array()) { $this->_connectToAvalara(); $client = new TaxServiceSoap(Configuration::get('AVALARATAX_MODE')); if ($type == 'commit') { $request = new CommitTaxRequest(); } elseif ($type == 'post') { $request = new PostTaxRequest(); $request->setDocDate($params['DocDate']); $request->setTotalAmount($params['TotalAmount']); $request->setTotalTax($params['TotalTax']); } elseif ($type == 'cancel') { $request = new CancelTaxRequest(); if ($params['CancelCode'] == 'D') { $code = CancelCode::$DocDeleted; } elseif ($params['CancelCode'] == 'P') { $code = CancelCode::$PostFailed; } elseif ($params['CancelCode'] == 'V') { $code = CancelCode::$DocVoided; } else { die('Invalid cancel code.'); } $request->setCancelCode($code); } elseif ($type == 'history') { $request = new GetTaxHistoryRequest(); $request->setDetailLevel(DetailLevel::$Document); } if ($type != 'isAuthorized') { $request->setDocCode('Order ' . (int) $params['DocCode']); $request->setDocType(DocumentType::$SalesInvoice); $request->setCompanyCode(Configuration::get('AVALARATAX_COMPANY_CODE')); } $buffer = array(); try { if ($type == 'commit') { $result = $client->commitTax($request); } elseif ($type == 'post') { $result = $client->postTax($request); } elseif ($type == 'cancel') { $result = $client->cancelTax($request); } elseif ($type == 'isAuthorized') { $result = $client->isAuthorized('GetTax'); } elseif ($type == 'history') { $result = $client->getTaxHistory($request); $buffer['Invoice'] = $result->getGetTaxRequest()->getDocCode(); $buffer['Status'] = $result->getGetTaxResult()->getDocStatus(); } $buffer['ResultCode'] = $result->getResultCode(); if ($result->getResultCode() != SeverityLevel::$Success) { 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; }
$request->setDocType('SalesInvoice'); $input = "bogus"; while ($input != "D" && $input != "P") { echo "CancelCode: Enter D for DocDeleted, or P for PostFailed: [D]"; $input = strtoupper(rtrim(fgets($STDIN))); if ($input == '') { $input = 'D'; } } $code = CancelCode::$DocDeleted; if ($input == 'P') { $code = CancelCode::$PostFailed; } $request->setCancelCode($code); try { $result = $client->cancelTax($request); echo 'CancelTax ResultCode is: ' . $result->getResultCode() . "\n"; if ($result->getResultCode() != "Success") { foreach ($result->getMessages() as $msg) { echo $msg->getName() . ": " . $msg->getSummary() . "\n"; } } } catch (SoapFault $exception) { $msg = "Exception: "; if ($exception) { $msg .= $exception->faultstring; } echo $msg . "\n"; echo $client->__getLastRequest() . "\n"; echo $client->__getLastResponse() . "\n"; }
function getTax($calculationHelper, $calc, $price, $sale = false, $committ = false) { if ($calc->activated == 0) { return false; } $shopperData = $this->getShopperData(); if (!$shopperData) { return false; } //if(self::$stop) return self::$stop; if (!class_exists('TaxServiceSoap')) { require VMAVALARA_CLASS_PATH . DS . 'TaxServiceSoap.class.php'; } if (!class_exists('DocumentType')) { require VMAVALARA_CLASS_PATH . DS . 'DocumentType.class.php'; } if (!class_exists('DetailLevel')) { require VMAVALARA_CLASS_PATH . DS . 'DetailLevel.class.php'; } if (!class_exists('Line')) { require VMAVALARA_CLASS_PATH . DS . 'Line.class.php'; } if (!class_exists('ServiceMode')) { require VMAVALARA_CLASS_PATH . DS . 'ServiceMode.class.php'; } if (!class_exists('Line')) { require VMAVALARA_CLASS_PATH . DS . 'Line.class.php'; } if (!class_exists('GetTaxRequest')) { require VMAVALARA_CLASS_PATH . DS . 'GetTaxRequest.class.php'; } if (!class_exists('GetTaxResult')) { require VMAVALARA_CLASS_PATH . DS . 'GetTaxResult.class.php'; } $client = new TaxServiceSoap('Development'); $request = new GetTaxRequest(); $origin = new Address(); //$destination = $this->fillValidateAvalaraAddress($calc); //In Virtuemart we have not differenct warehouses, but we have a shipment address //So when the vendor has a shipment address, we assume that it is his warehouse //Later we can combine products with shipment addresses for different warehouse (yehye, future music) //But for now we just use the BT address if (!class_exists('VirtueMartModelVendor')) { require JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php'; } $userId = VirtueMartModelVendor::getUserIdByVendorId($calc->virtuemart_vendor_id); $userModel = VmModel::getModel('user'); $virtuemart_userinfo_id = $userModel->getBTuserinfo_id($userId); // this is needed to set the correct user id for the vendor when the user is logged $userModel->getVendor($calc->virtuemart_vendor_id); $vendorFieldsArray = $userModel->getUserInfoInUserFields('mail', 'BT', $virtuemart_userinfo_id, FALSE, TRUE); $vendorFields = $vendorFieldsArray[$virtuemart_userinfo_id]; //vmdebug('my vendor fields',$vendorFields); $origin->setLine1($vendorFields['fields']['address_1']['value']); $origin->setLine2($vendorFields['fields']['address_2']['value']); $origin->setCity($vendorFields['fields']['city']['value']); $origin->setCountry($vendorFields['fields']['virtuemart_country_id']['country_2_code']); $origin->setRegion($vendorFields['fields']['virtuemart_state_id']['state_2_code']); $origin->setPostalCode($vendorFields['fields']['zip']['value']); $request->setOriginAddress($origin); //Address if (isset($this->addresses[0])) { $destination = $this->addresses[0]; } else { return FALSE; } $request->setDestinationAddress($destination); //Address //vmdebug('The date',$origin,$destination); $request->setCompanyCode($calc->company_code); // Your Company Code From the Dashboard if ($calc->committ and $sale) { $request->setDocType(DocumentType::$SalesInvoice); // Only supported types are SalesInvoice or SalesOrder $request->setCommit(true); //invoice number, problem is that the invoice number is at this time not known, but the order_number may reachable $request->setDocCode($committ); vmdebug('Request as SalesInvoice with invoiceNumber ' . $committ); } else { $request->setDocType(DocumentType::$SalesOrder); $request->setCommit(false); //invoice number, problem is that the invoice number is at this time not known, neither the order_number $request->setDocCode('VM2.0.16_order_request'); vmdebug('Request as SalesOrder'); } $request->setDocDate(date('Y-m-d')); //date //$request->setSalespersonCode(""); // string Optional $request->setCustomerCode($shopperData['customer_id']); //string Required if (isset($shopperData['tax_usage_type'])) { $request->setCustomerUsageType($shopperData['tax_usage_type']); //string Entity Usage } $cartPrices = $calculationHelper->getCartPrices(); //vmdebug('$cartPrices',$cartPrices); $request->setDiscount($cartPrices['discountAmount']); //decimal //$request->setDiscount(0.0); // $request->setPurchaseOrderNo(""); //string Optional //If I understand correctly, we need to add for this an userfield, for example with the name //exemption_no, then user could enter their number. if (isset($shopperData['tax_exemption_number'])) { $request->setExemptionNo($shopperData['tax_exemption_number']); //string if not using ECMS which keys on customer code } $request->setDetailLevel('Tax'); //Summary or Document or Line or Tax or Diagnostic // $request->setReferenceCode1(""); //string Optional // $request->setReferenceCode2(""); //string Optional // $request->setLocationCode(""); //string Optional - aka outlet id for tax forms ///////////////////////////////////////// if (!class_exists('VirtueMartCart')) { require JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'; } $cart = VirtueMartCart::getCart(); $products = array(); if ($calculationHelper->inCart) { $products = $cart->products; $prices = $calculationHelper->getCartPrices(); foreach ($products as $k => $product) { if (!empty($prices[$k]['discountedPriceWithoutTax'])) { $price = $prices[$k]['discountedPriceWithoutTax']; } else { if (!empty($prices[$k]['basePriceVariant'])) { $price = $prices[$k]['basePriceVariant']; } else { vmdebug('There is no price in getTax for product ' . $k . ' ', $prices); $price = 0.0; } } $product->price = $price; if (!empty($price[$k]['discountAmount'])) { $product->discount = $price[$k]['discountAmount']; } else { $product->discount = FALSE; } } } else { $calculationHelper->_product->price = $price; $products[0] = $calculationHelper->_product; if (!isset($products[0]->amount)) { $products[0]->amount = 1; } if (isset($calculationHelper->productPrices['discountAmount'])) { $products[0]->discount = $calculationHelper->productPrices['discountAmount']; } else { $products[0]->discount = FALSE; } } $lines = array(); $n = 0; $lineNumbersToCartProductId = array(); foreach ($products as $k => $product) { $n++; $lineNumbersToCartProductId[$n] = $k; $line = new Line(); $line->setNo($n); //string // line Number of invoice $line->setItemCode($product->product_sku); //string $line->setDescription($product->product_name); //product description, like in cart, atm only the name, todo add customfields //$line->setTaxCode(""); //string $line->setQty($product->amount); //decimal $line->setAmount($product->price * $product->amount); //decimal // TotalAmmount $line->setDiscounted($product->discount * $product->amount); //boolean $line->setRevAcct(""); //string $line->setRef1(""); //string $line->setRef2(""); //string if (isset($shopperData['tax_exemption_number'])) { $line->setExemptionNo($shopperData['tax_exemption_number']); //string } if (isset($shopperData['tax_usage_type'])) { $line->setCustomerUsageType($shopperData['tax_usage_type']); //string } $lines[] = $line; } $line = new Line(); $line->setNo(++$n); //$lineNumbersToCartProductId[$n] = count($products)+1; $line->setItemCode($cart->virtuemart_shipmentmethod_id); $line->setDescription('Shipment'); $line->setQty(1); //$line->setTaxCode(); $cartPrices = $calculationHelper->getCartPrices(); //vmdebug('$calculationHelper $cartPrices',$cartPrices); $line->setAmount($cartPrices['shipmentValue']); if (isset($shopperData['tax_exemption_number'])) { $line->setExemptionNo($shopperData['tax_exemption_number']); //string } if (isset($shopperData['tax_usage_type'])) { $line->setCustomerUsageType($shopperData['tax_usage_type']); //string } $lines[] = $line; //vmdebug('avalaragetTax setLines',$lines); $request->setLines($lines); //vmdebug('My request',$request); $totalTax = 0.0; try { if (!class_exists('TaxLine')) { require VMAVALARA_CLASS_PATH . DS . 'TaxLine.class.php'; } if (!class_exists('TaxDetail')) { require VMAVALARA_CLASS_PATH . DS . 'TaxDetail.class.php'; } vmSetStartTime('avagetTax'); $getTaxResult = $client->getTax($request); vmTime('Avalara getTax', 'avagetTax'); /* * [0] => getDocCode [1] => getAdjustmentDescription [2] => getAdjustmentReason [3] => getDocDate [4] => getTaxDate [5] => getDocType [6] => getDocStatus [7] => getIsReconciled [8] => getLocked [9] => getTimestamp [10] => getTotalAmount [11] => getTotalDiscount [12] => getTotalExemption [13] => getTotalTaxable [14] => getTotalTax [15] => getHashCode [16] => getVersion [17] => getTaxLines [18] => getTotalTaxCalculated [19] => getTaxSummary [20] => getTaxLine [21] => getTransactionId [22] => getResultCode [23] => getMessages */ //vmdebug( 'GetTax is: '. $getTaxResult->getResultCode(),$getTaxResult); if ($getTaxResult->getResultCode() == SeverityLevel::$Success) { //vmdebug("DocCode: ".$request->getDocCode() ); //vmdebug("DocId: ".$getTaxResult->getDocId()."\n"); vmdebug("TotalAmount: " . $getTaxResult->getTotalAmount()); $totalTax = $getTaxResult->getTotalTax(); vmdebug("TotalTax: " . $totalTax); foreach ($getTaxResult->getTaxLines() as $ctl) { if ($calculationHelper->inCart) { $nr = $ctl->getNo(); if (isset($lineNumbersToCartProductId[$nr])) { $quantity = $products[$lineNumbersToCartProductId[$nr]]->amount; //on the long hand, the taxAmount must be replaced by taxAmountQuantity to avoid rounding errors $prices[$lineNumbersToCartProductId[$ctl->getNo()]]['taxAmount'] = $ctl->getTax() / $quantity; $prices[$lineNumbersToCartProductId[$ctl->getNo()]]['taxAmountQuantity'] = $ctl->getTax(); } else { //$this->_cartPrices['shipmentValue'] = 0; //could be automatically set to a default set in the globalconfig //$this->_cartPrices['shipmentTax'] = 0; //$this->_cartPrices['shipmentTotal'] = 0; //$prices = array('shipmentValue'=>$cartPrices['shipmentValue'],'shipmentTax'=> $ctl->getTax(), 'shipmentTotal' =>($cartPrices['shipmentValue'] +$ctl->getTax() )); //vmdebug('my $cartPrices',$cartPrices); $prices['shipmentTax'] = $ctl->getTax(); $prices['salesPriceShipment'] = $prices['shipmentValue'] + $ctl->getTax(); //$cartPrices = array_merge($prices,$cartPrices); //$calculationHelper->setCartPrices( $cartPrices ); $totalTax = $totalTax - $ctl->getTax(); //vmdebug('my $cartPrices danach',$cartPrices); } } //vmdebug('my lines ',$ctl); //vmdebug( " Line: ".$ctl->getNo()." Tax: ".$ctl->getTax()." TaxCode: ".$ctl->getTaxCode()); foreach ($ctl->getTaxDetails() as $ctd) { //vmdebug( " Juris Type: ".$ctd->getJurisType()."; Juris Name: ".$ctd->getJurisName()."; Rate: ".$ctd->getRate()."; Amt: ".$ctd->getTax() ); } } if ($calculationHelper->inCart) { $calculationHelper->setCartPrices($prices); } } else { foreach ($getTaxResult->getMessages() as $msg) { vmError($msg->getName() . ": " . $msg->getSummary()); } } } catch (SoapFault $exception) { $msg = "Exception: "; if ($exception) { $msg .= $exception->faultstring; } vmdebug($msg . '<br />' . $client->__getLastRequest() . '<br />' . $client->__getLastResponse()); } //self::$stop = $totalTax; return $totalTax; }