Пример #1
0
        public static void CalculateAvalaraTax(OpportunityMaint rg, CROpportunity order)
        {
            TaxSvc service = new TaxSvc();

            AvalaraMaint.SetupService(rg, service);

            AddressSvc addressService = new AddressSvc();

            AvalaraMaint.SetupService(rg, addressService);

            GetTaxRequest getRequest       = null;
            bool          isValidByDefault = true;

            if (order.IsTaxValid != true)
            {
                getRequest = BuildGetTaxRequest(rg, order);

                if (getRequest.Lines.Count > 0)
                {
                    isValidByDefault = false;
                }
                else
                {
                    getRequest = null;
                }
            }

            if (isValidByDefault)
            {
                PXDatabase.Update <CROpportunity>(
                    new PXDataFieldAssign("IsTaxValid", true),
                    new PXDataFieldRestrict("OpportunityID", PXDbType.NVarChar, CROpportunity.OpportunityIDLength, order.OpportunityID, PXComp.EQ)
                    );
                return;
            }

            GetTaxResult result = service.GetTax(getRequest);

            if (result.ResultCode == SeverityLevel.Success)
            {
                try
                {
                    ApplyAvalaraTax(rg, order, result);
                    PXDatabase.Update <CROpportunity>(
                        new PXDataFieldAssign("IsTaxValid", true),
                        new PXDataFieldRestrict("OpportunityID", PXDbType.NVarChar, CROpportunity.OpportunityIDLength, order.OpportunityID, PXComp.EQ)
                        );
                }
                catch (Exception ex)
                {
                    throw new PXException(ex, TX.Messages.FailedToApplyTaxes);
                }
            }
            else
            {
                LogMessages(result);

                throw new PXException(TX.Messages.FailedToGetTaxes);
            }
        }
Пример #2
0
        private GetTaxRequest BuildTaxRequest(Customer cust, Avalara.AvaTax.Adapter.AddressService.Address originAddress, DocumentType docType)
        {
            // Instantiate a new GetTaxRequest
            GetTaxRequest avalaraTaxRequest = new GetTaxRequest
            {
                OriginAddress = originAddress,
                CompanyCode   = CompanyCode,
                CustomerCode  = cust.CustomerID.ToString(),
                DetailLevel   = DetailLevel.Tax,
                CurrencyCode  = Localization.StoreCurrency(),
                DocCode       = ("DocDate" + System.DateTime.Now.ToString()),
                DocDate       = System.DateTime.Today,
                DocType       = docType,
                Discount      = System.Decimal.Zero,
            };

            avalaraTaxRequest.TaxOverride.TaxDate = System.DateTime.Today;

            if (cust.LevelHasNoTax)
            {
                avalaraTaxRequest.ExemptionNo = (cust.CustomerLevelName.Length > 25 ? cust.CustomerLevelName.Substring(0, 25) : cust.CustomerLevelName)
                                                ?? "Customer Level Tax Exempt"; //Avalara can't handle more than 25 chars here
            }
            return(avalaraTaxRequest);
        }
        public void PostTax(OriginAddress originAddress, CustomerOrder customerOrder)
        {
            if (!this.AvalaraSettings.PostTaxes)  // Added condition to check post taxes setting
            {
                return;
            }
            string str = string.Empty;

            if (ValidateOrderAddressForAvalara(customerOrder))
            {
                try
                {
                    GetTaxRequest  requestFromOrder1    = GetCalcTaxRequestFromOrder(originAddress, customerOrder, DocumentType.SalesInvoice);
                    PostTaxRequest requestFromOrder2    = GetPostTaxRequestFromOrder(customerOrder);
                    TaxSvc         configuredTaxService = GetConfiguredTaxService();
                    configuredTaxService.GetTax(requestFromOrder1);
                    str = this.ProcessAvalaraResponseMessage(configuredTaxService.PostTax(requestFromOrder2));
                }
                catch (Exception ex)
                {
                    LogHelper.For(this).Error("Error running Avalara PostTax method: " + ex.Message, "TaxCalculator_Avalara");
                    throw;
                }
            }
            else
            {
                LogHelper.For(this).Debug("The billto/shipto customer does not have an address specified. In order to calculate tax this must be set up.", "TaxCalculator_Avalara");
                return;
            }
            if (string.IsNullOrEmpty(str))
            {
                return;
            }
            LogHelper.For(this).Debug(str, "Avalara Result, PostTax: ");
        }
Пример #4
0
        private CalcResult InvoiceTax(GetTaxRequest request)
        {
            var context = request.ToCalcRequestContext();

            var graph             = new PXGraph();
            var repository        = new BqlRepository(graph, _logger);
            var invoiceTaxService = new OtherInvoiceTaxService(repository, _logger);

            var salesOrder = repository.RetrieveSalesOrderByInvoice(context.InvoiceType, context.InvoiceNbr);
            var transfer   = repository.RetrieveTaxTransfer(salesOrder.OrderType, salesOrder.OrderNbr);

            var otherInvoiceTaxes = invoiceTaxService.GetOtherTaxes(context.InvoiceType, context.InvoiceNbr);

            // *** TODO - get the Sales Order Shipments and count Shipped Qty therefrom
            //      ... as means to protect against multiple non-Invoiced Shipments causing OpenOrderQty == 0
            //
            if (salesOrder.OpenOrderQty == 0)
            {
                return(InvoiceFinalTax(transfer, otherInvoiceTaxes));
            }
            else
            {
                return(InvoiceSplitShipmentTax(request, transfer));
            }
        }
        public void Validate_WhenRequestIsInvalid_Fails(GetTaxRequest request)
        {
            var result = _validator.Validate(request);

            result.IsValid.Should().BeFalse();
            result.Errors.Should().NotBeEmpty();
        }
        public void Validate_WhenRequestIsValid_Passes(GetTaxRequest request)
        {
            var result = _validator.Validate(request);

            result.IsValid.Should().BeTrue();
            result.Errors.Should().BeEmpty();
        }
Пример #7
0
        public void LoadLineData(GetTaxRequest getTaxRequest)
        {
            //#######################################################
            //### ITERATE THROUGH LINES ON ORIGINAL GETTAXREQUEST ###
            //#######################################################
            DataRow row;

            foreach (Line line in getTaxRequest.Lines)
            {
                row = _dataLines.NewRow();
                row[LineColumns.No.ToString()]          = line.No;
                row[LineColumns.ItemCode.ToString()]    = line.ItemCode;
                row[LineColumns.Qty.ToString()]         = line.Qty.ToString();
                row[LineColumns.Amount.ToString()]      = line.Amount.ToString();
                row[LineColumns.Discounted.ToString()]  = line.Discounted.ToString();
                row[LineColumns.ExemptionNo.ToString()] = line.ExemptionNo;
                row[LineColumns.Reference1.ToString()]  = line.Ref1;
                row[LineColumns.Reference2.ToString()]  = line.Ref2;
                row[LineColumns.RevAcct.ToString()]     = line.RevAcct;
                row[LineColumns.TaxCode.ToString()]     = line.TaxCode;
                //Added for 5.0
//				row[LineColumns.IsTaxOverriden.ToString()] = line.IsTaxOverriden.ToString();
//				row[LineColumns.TaxOverride.ToString()] = line.TaxOverride;
                row[LineColumns.TaxOverrideType.ToString()] = line.TaxOverride.TaxOverrideType.ToString();
                row[LineColumns.TaxAmount.ToString()]       = line.TaxOverride.TaxAmount.ToString();
                row[LineColumns.TaxDate.ToString()]         = line.TaxOverride.TaxDate.ToString();
                row[LineColumns.Reason.ToString()]          = line.TaxOverride.Reason;

                _dataLines.Rows.Add(row);
            }
        }
Пример #8
0
        public static AdjustTaxResult Execute(CustomerOrder refundOrder, out string summary)
        {
            summary = "";
            TaxServiceWrapper taxSvcWrapper = new TaxServiceWrapper();
            TaxSvc            taxSvc        = taxSvcWrapper.GetTaxSvcInstance(refundOrder.InProduction);

            AdjustTaxRequest adjustTaxRequest = new AdjustTaxRequest();

            GetTaxRequest getTaxRequest = GetTax.BuildGetTaxRequest(refundOrder);

            getTaxRequest.TaxOverride.TaxOverrideType = TaxOverrideType.TaxAmount;
            getTaxRequest.TaxOverride.Reason          = "Adjustment for router return";
            //getTaxRequest.TaxOverride.TaxDate = DateTime.Parse("2013-07-01");
            getTaxRequest.TaxOverride.TaxAmount = refundOrder.TotalTax;
            getTaxRequest.ServiceMode           = ServiceMode.Automatic;

            adjustTaxRequest.GetTaxRequest         = getTaxRequest;
            adjustTaxRequest.AdjustmentReason      = 5;
            adjustTaxRequest.AdjustmentDescription = "Tax adjusted based on router refund";

            AdjustTaxResult adjustTaxResult = taxSvc.AdjustTax(adjustTaxRequest);

            if (!adjustTaxResult.ResultCode.Equals(SeverityLevel.Success))
            {
                foreach (Message message in adjustTaxResult.Messages)
                {
                    summary = message.Summary;
                }
            }

            return(adjustTaxResult);
        }
Пример #9
0
        public async Task GetAsync_GivenValidRequestParameters_ReturnsResponseAsync(GetTaxRequest request)
        {
            GetTax actualQuery = null;

            var expectedQuery = new GetTax(request.Municipality, request.Date);

            var taxMock = new Tax
            {
                Municipality = request.Municipality,
                PeriodType   = Enums.PeriodType.Daily,
                PeriodStart  = DateTime.Parse(request.Date),
                PeriodEnd    = DateTime.Parse(request.Date),
                Result       = 0.4m
            };

            var expectedResponse = new GetTaxResponse
            {
                Municipality = request.Municipality,
                PeriodType   = Enums.PeriodType.Daily,
                PeriodStart  = DateTime.Parse(request.Date),
                PeriodEnd    = DateTime.Parse(request.Date),
                Result       = 0.5m
            };

            _mediatorMock
            .Setup(s => s.Send(It.IsAny <GetTax>(), It.IsAny <CancellationToken>()))
            .Callback <IRequest <Option <Tax> >, CancellationToken>((query, ct) => actualQuery = (GetTax)query)
            .ReturnsAsync(taxMock);

            var response = await _controller.GetAsync(request);

            response.Result.Should().BeOfType <OkObjectResult>();
            _mediatorMock.Verify(s => s.Send(It.IsAny <GetTax>(), It.IsAny <CancellationToken>()), Times.Once);
            actualQuery.Should().Be(expectedQuery);
        }
Пример #10
0
        public void OrderPlaced(Order order)
        {
            if (!Enabled)
            {
                throw new InvalidOperationException("AvalaraInactiveException");
            }

            var customer     = new Customer(order.CustomerID);
            var cartItems    = order.CartItems;
            var orderOptions = GetOrderOptions(order);

            // Create line items for all cart items and shipping selections
            var cartItemAddressGroups = GroupCartItemsByShippingAddress(cartItems, customer.PrimaryShippingAddressID);
            var lineItems             = CreateItemAndShippingLineItems(cartItemAddressGroups, (shipmentAddressId, shipmentAddress, shipmentCartItems) => CreateOrderShippingLineItem(shipmentAddress, shipmentCartItems, order, shipmentAddressId));

            // Create line items for order options using the first shipping address as the destination
            var firstShippingAddress = LoadAvalaraAddress(cartItemAddressGroups.First().Key);

            lineItems = lineItems.Concat(CreateOrderOptionLineItems(orderOptions, firstShippingAddress));

            // Calculate the discount from the promotion usages for this order
            decimal discountAmount;

            using (var promotionsDataContext = new AspDotNetStorefront.Promotions.Data.EntityContextDataContext())
            {
                discountAmount = promotionsDataContext.PromotionUsages
                                 .Where(pu => pu.OrderId == order.OrderNumber)
                                 .Where(pu => pu.Complete)
                                 .Sum(pu => - pu.OrderDiscountAmount)           // Avalara expects a positive number
                                 .GetValueOrDefault(0);
            }

            // Build and submit the tax request
            GetTaxRequest taxRequest = BuildTaxRequest(customer, GetOriginAddress(), DocumentType.SalesInvoice);

            taxRequest.Discount            = discountAmount;
            taxRequest.DocCode             = order.OrderNumber.ToString();
            taxRequest.TaxOverride.TaxDate = order.OrderDate;

            // Add each line to the request, setting the line number sequentially
            int lineItemIndex = 0;

            foreach (var line in lineItems)
            {
                line.No = (++lineItemIndex).ToString();
                taxRequest.Lines.Add(line);
            }

            TaxSvc       taxService = CreateTaxService();
            GetTaxResult taxResult  = taxService.GetTax(taxRequest);

            foreach (Message message in taxResult.Messages)
            {
                LogErrorMessage(message);                 //this throws an exception
            }
            //not used currently
            //decimal taxAmount = taxResult.TotalTax;
        }
Пример #11
0
        public async Task <GetTaxResult> GetTax(GetTaxRequest taxRequest)
        {
            _getTaxResult = await _taxSvc.GetTax(taxRequest);

            State.GetTaxResult = _getTaxResult;
            await State.WriteStateAsync();

            return(await Task.FromResult(_getTaxResult));
        }
        public GetTaxResult GetTax(GetTaxRequest request)
        {
            var json = JsonConvert.SerializeObject(request);

            _logger.Info($"GetTaxRequest ({request.DocCode}) - {json}");

            var response = _taxCalcService.Calculate(request);

            _logger.Info($"GetTaxRequest (output) - {JsonConvert.SerializeObject(response)}");

            return(response);
        }
Пример #13
0
        private void buttonGetTaxHistory_Click(object sender, EventArgs e)
        {
            try
            {             //#########################################################################
                //### 1st WE CREATE THE REQUEST OBJECT FOR THE DOCUMENT HISTORY WE WANT ###
                //#########################################################################
                GetTaxHistoryRequest getTaxHistoryRequest = new GetTaxHistoryRequest();

                //###########################################################
                //### 2nd WE LOAD THE REQUEST-LEVEL DATA INTO THE REQUEST ###
                //###########################################################
                getTaxHistoryRequest.CompanyCode = textCompanyCode.Text;
                getTaxHistoryRequest.DocCode     = textDocCode.Text;
                getTaxHistoryRequest.DocType     = (DocumentType)comboDocType.SelectedItem;
                getTaxHistoryRequest.DetailLevel = (DetailLevel)cboDetailLevel.SelectedItem;

                //##################################################################################################
                //### 3rd WE INVOKE THE GETTAXHISTORY() METHOD OF THE TAXSVC OBJECT AND GET BACK A RESULT OBJECT ###
                //##################################################################################################
                Util.PreMethodCall(this, lblStatus);

                TaxSvc taxSvc = new TaxSvc();
                ((formMain)this.Owner).SetConfig(taxSvc);                              //set the Url and Security configuration

                _getTaxHistoryResult = taxSvc.GetTaxHistory(getTaxHistoryRequest);

                Util.PostMethodCall(this, lblStatus);

                //#####################################
                //### 4th WE READ THE RESULT OBJECT ###
                //#####################################
                lblResultCode.Text = _getTaxHistoryResult.ResultCode.ToString();
                Util.SetMessageLabelText(lblResultMsg, _getTaxHistoryResult);
                _getTaxRequest = _getTaxHistoryResult.GetTaxRequest;
                _getTaxResult  = _getTaxHistoryResult.GetTaxResult;

                buttonGetTaxRequest.Enabled = (_getTaxRequest != null);
                buttonGetTaxResult.Enabled  = (_getTaxResult != null);

                getTaxHistoryRequest = null;
                taxSvc = null;
            }
            catch (Exception ex)
            {
                Util.ShowError(ex);
            }
            finally
            {
                Util.PostMethodCall(this, lblStatus);
            }
        }
Пример #14
0
        public void LoadAddressData(GetTaxRequest getTaxRequest)
        {
            //###########################################################
            //### ITERATE THROUGH ADDRESSES ON ORIGINAL GETTAXREQUEST ###
            //###########################################################
            FillAddressRow(getTaxRequest.OriginAddress, "Origin", "Request");
            FillAddressRow(getTaxRequest.DestinationAddress, "Destination", "Request");

            foreach (Line line in getTaxRequest.Lines)
            {
                FillAddressRow(line.OriginAddress, "Origin", string.Format("Line({0})", line.No));
                FillAddressRow(line.DestinationAddress, "Destination", string.Format("Line({0})", line.No));
            }
        }
Пример #15
0
        public static decimal GetTax(int orderId, bool UpdateOrderTax, bool CartTax, ClientCartContext clientData)
        {
            decimal taxAmount = 0M;

            try
            {
                XmlNode config = null;
                config = GetTax_AvalaraConfig();
                string accountNumber = config.Attributes["accountNumber"].Value;
                string licenseKey    = config.Attributes["licenseKey"].Value;
                string serviceURL    = config.Attributes["serviceURL"].Value;

                TaxSvc taxSvc = new TaxSvc(accountNumber, licenseKey, serviceURL);

                GetTaxRequest           getTaxRequest = GetTax_Request(orderId, UpdateOrderTax, CartTax, clientData);
                XmlSerializerNamespaces namesp        = new XmlSerializerNamespaces();
                namesp.Add(string.Empty, string.Empty);
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
                XmlSerializer x1 = new XmlSerializer(getTaxRequest.GetType());
                StringBuilder sb = new StringBuilder();
                x1.Serialize(XmlTextWriter.Create(sb, settings), getTaxRequest, namesp);
                string       req          = sb.ToString();
                int          timeout      = getTimeOutTax(); // This is for Request TimeOut
                GetTaxResult getTaxResult = taxSvc.GetTax(getTaxRequest, timeout);

                XmlSerializer x2  = new XmlSerializer(getTaxResult.GetType());
                StringBuilder sb2 = new StringBuilder();
                x2.Serialize(XmlTextWriter.Create(sb2, settings), getTaxResult, namesp);
                string res = sb2.ToString();

                if (getTaxResult.ResultCode.Equals(SeverityLevel.Success))
                {
                    taxAmount = getTaxResult.TotalTax;
                }

                if (UpdateOrderTax && orderId > 0)
                {
                    CSResolve.Resolve <IOrderService>().UpdateOrderTax(orderId, taxAmount);
                    Dictionary <string, AttributeValue> orderAttributes = new Dictionary <string, AttributeValue>();
                    orderAttributes.Add("TaxRequest", new CSBusiness.Attributes.AttributeValue(req));
                    orderAttributes.Add("TaxResponse", new CSBusiness.Attributes.AttributeValue(res));
                    CSResolve.Resolve <IOrderService>().UpdateOrderAttributes(orderId, orderAttributes, null);
                }
            }
            catch
            {
            }
            return(taxAmount);
        }
Пример #16
0
        public static CalcRequestContext ToCalcRequestContext(this GetTaxRequest request)
        {
            var parts = request.DocCode.Split('.').ToList();

            if (parts[0] == AcumaticaDocType.SalesOrder && parts[2] == AcumaticaDocType.Freight)
            {
                return(new CalcRequestContext
                {
                    Type = CalcRequestTypeEnum.SOFreight,
                    OrderType = parts[0],
                    OrderNbr = parts[1]
                });
            }

            if (parts[0] == AcumaticaDocType.SalesOrder && parts[2] == AcumaticaDocType.Open)
            {
                return(new CalcRequestContext
                {
                    Type = CalcRequestTypeEnum.SalesOrder,
                    OrderType = parts[0],
                    OrderNbr = parts[1]
                });
            }

            if (parts[0] == AcumaticaDocType.SalesOrder && parts[1] == AcumaticaDocType.SalesOrder)
            {
                return(new CalcRequestContext
                {
                    Type = CalcRequestTypeEnum.SalesOrder,
                    OrderType = parts[1],
                    OrderNbr = parts[2]
                });
            }

            if (parts[0] == AcumaticaModule.AR && parts[1] == AcumaticaDocType.Invoice)
            {
                return(new CalcRequestContext
                {
                    Type = CalcRequestTypeEnum.SOShipmentInvoice,
                    InvoiceType = parts[1],
                    InvoiceNbr = parts[2],
                });
            }

            return(new CalcRequestContext()
            {
                Type = CalcRequestTypeEnum.Undetermined
            });
        }
Пример #17
0
        public virtual bool IsSame(GetTaxRequest x, GetTaxRequest y)
        {
            if (x.CartItems.Count != y.CartItems.Count)
            {
                return(false);
            }

            for (int i = 0; i < x.CartItems.Count; i++)
            {
                if (x.CartItems[i].Amount != y.CartItems[i].Amount)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #18
0
        // This actually calls the service to perform the tax calculation, and returns the calculation result.
        public async Task <GetTaxResult> GetTax(GetTaxRequest req)
        {
            // Convert the request to XML
            XmlSerializerNamespaces namesp = new XmlSerializerNamespaces();

            namesp.Add(string.Empty, string.Empty);
            XmlWriterSettings settings = new XmlWriterSettings {
                OmitXmlDeclaration = true
            };
            XmlSerializer x  = new XmlSerializer(req.GetType());
            StringBuilder sb = new StringBuilder();

            x.Serialize(XmlWriter.Create(sb, settings), req, namesp);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(sb.ToString());

            // Call the service
            Uri address = new Uri(_svcUrl + "tax/get");
            var request = HttpHelper.CreateRequest(address, _accountNumber, _license);

            request.Method      = "POST";
            request.ContentType = "text/xml";
            //request.ContentLength = sb.Length;
            Stream newStream = await request.GetRequestStreamAsync();

            newStream.Write(Encoding.ASCII.GetBytes(sb.ToString()), 0, sb.Length);
            GetTaxResult result = new GetTaxResult();

            try
            {
                WebResponse response = await request.GetResponseAsync();

                XmlSerializer r = new XmlSerializer(result.GetType());
                result = (GetTaxResult)r.Deserialize(response.GetResponseStream());
            }
            catch (WebException ex)
            {
                XmlSerializer r = new XmlSerializer(result.GetType());
                result = (GetTaxResult)r.Deserialize(((HttpWebResponse)ex.Response).GetResponseStream());
            }

            return(result);
        }
Пример #19
0
        public formGetTaxRequest(GetTaxRequest getTaxRequest)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //#####################
            //### UI SETUP CODE ###
            //#####################
            SetupLineHeader();
            SetupAddressHeader();

            _getTaxRequest = getTaxRequest;

            gridLines.SetDataBinding(_dataLines, "");
            gridAddresses.SetDataBinding(_dataAddresses, "");

            LoadResultData();
        }
Пример #20
0
        public GetTaxResult Calculate(GetTaxRequest request)
        {
            var calcRequestType = request.ToCalcRequestContext();

            _logger.Info(
                $"TaxCalcService {CalcVersion} -> Calculate (Type) - " +
                $"{JsonConvert.SerializeObject(calcRequestType)}");

            if (calcRequestType.Type == CalcRequestTypeEnum.SalesOrder)
            {
                return(ProcessResults(SalesOrderTax(calcRequestType)));
            }

            if (calcRequestType.Type == CalcRequestTypeEnum.SOShipmentInvoice)
            {
                return(ProcessResults(InvoiceTax(request)));
            }

            return(ProcessResults(new CalcResult()));
        }
Пример #21
0
 public GetTaxResult GetTax(GetTaxRequest request)
 {
     if (!IsActive)
     {
         return(new GetTaxResult()
         {
             IsSuccess = false,
             Messages = new[] { Messages.ServiceIsNotActive }
         });
     }
     else
     {
         if (WriteTrace)
         {
             PXTrace.WriteInformation("GetTax Request: " + JsonConvert.SerializeObject(request, Formatting.Indented));
         }
         decimal amount    = request.CartItems.Sum(_ => _.Amount);
         decimal taxAmount = amount * TaxPercentage;
         string  taxName   = request.DestinationAddress.Region + "DummyTax";
         return(new GetTaxResult()
         {
             IsSuccess = true,
             Messages = new string[0],
             TaxLines = new TaxLine[] { new TaxLine()
                                        {
                                            Index = 1, Rate = TaxPercentage, TaxableAmount = amount, TaxAmount = taxAmount
                                        } },
             TaxSummary = new TaxDetail[]
             {
                 new TaxDetail()
                 {
                     Rate = TaxPercentage, TaxableAmount = amount, TaxAmount = taxAmount,
                     JurisCode = taxName, JurisName = taxName, TaxName = taxName
                 }
             },
             TotalAmount = amount + taxAmount,
             TotalTaxAmount = taxAmount
         });
     }
 }
Пример #22
0
        public static GetTaxResult Execute(CustomerOrder order, out string summary)
        {
            summary = "";
            TaxServiceWrapper taxSvcWrapper = new TaxServiceWrapper();
            TaxSvc            taxSvc        = taxSvcWrapper.GetTaxSvcInstance(order.InProduction);

            PostTaxRequest postTaxRequest = new PostTaxRequest();

            GetTaxRequest getTaxRequest = BuildGetTaxRequest(order);

            GetTaxResult getTaxResult = taxSvc.GetTax(getTaxRequest);

            if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success))
            {
                foreach (Message message in getTaxResult.Messages)
                {
                    summary = message.Summary;
                }
            }

            return(getTaxResult);
        }
Пример #23
0
        // Recreate Tax Calculation using the Tax Transfer
        //
        private CalcResult InvoiceSplitShipmentTax(GetTaxRequest request, TaxTransfer.v2.TaxTransfer snapshot)
        {
            var result = new CalcResult();

            foreach (var lineItem in request.CartItems)
            {
                // NULL ItemCode signals that this line item is freight
                //
                if (lineItem.ItemCode == null)
                {
                    if (lineItem.Amount > 0.00m)
                    {
                        result.AddTaxLine(lineItem.Description, 0m, lineItem.Amount, snapshot.NetFreightTax);
                    }

                    continue;
                }

                var correctedItemCode = lineItem.ItemCode.Trim();

                if (snapshot.LineItems.Any(x => x.ItemID == correctedItemCode) == false)
                {
                    result.AddError($"Unable to locate Inventory ID {correctedItemCode} in Tax Transfer");
                    continue;
                }

                // Compute Line Item Tax using Tax Lines from Transfer
                //
                var lineItemTaxCalc
                    = snapshot.CalculateTax(correctedItemCode, (decimal)lineItem.Amount, (int)lineItem.Quantity);

                result.AddTaxLine(lineItemTaxCalc.Name, 0m, lineItemTaxCalc.TaxableAmount, lineItemTaxCalc.TaxAmount);
            }

            return(result);
        }
Пример #24
0
        public static GetTaxRequest GetTax_Request(int orderId, bool UpdateOrderTax, bool CartTax, ClientCartContext clientData)
        {
            string ShippingStateProvinceAbbreviation = "";
            // string BillingStateProvinceAbbreviation = "";
            List <StateProvince> states = StateManager.GetAllStates(0);

            XmlNode config = null;

            config = GetTax_AvalaraConfig();

            GetTaxRequest getTaxRequest = new GetTaxRequest();
            List <Sku>    OrderSkuItems = null;

            CSWeb.AvaTax.Address address1 = new CSWeb.AvaTax.Address();
            address1.AddressCode = "01";
            address1.Line1       = config.Attributes["address1Line1"].Value;
            address1.City        = config.Attributes["City"].Value;
            address1.Region      = config.Attributes["Region"].Value;

            CSWeb.AvaTax.Address address2 = new CSWeb.AvaTax.Address();
            address2.AddressCode = "02";

            if (orderId > 0 && CartTax == false)
            {
                CSBusiness.OrderManagement.Order orderItem = new OrderManager().GetBatchProcessOrder(orderId);
                getTaxRequest.CustomerCode = orderItem.CustomerId.ToString();            // "ABC4335";
                //getTaxRequest.CompanyCode = config.Attributes["companyCode"].Value;
                getTaxRequest.DocDate = orderItem.CreatedDate.ToString("yyyy-MM-dd");    // "2014-07-23";
                address2.Line1        = orderItem.CustomerInfo.ShippingAddress.Address1; // "1999 Avenue of Stars"; // "118 N Clark St";
                address2.Line2        = orderItem.CustomerInfo.ShippingAddress.Address2; // "Suite 1830"; // "Suite 100";
                // address2.Line3 = "ATTN Accounts Payable";
                address2.City = orderItem.CustomerInfo.ShippingAddress.City;             // "Los Angeles"; // "Chicago";

                StateProvince itemShippingStateProvince = states.FirstOrDefault(x => x.StateProvinceId == Convert.ToInt32(orderItem.CustomerInfo.ShippingAddress.StateProvinceId));
                if (itemShippingStateProvince != null)
                {
                    ShippingStateProvinceAbbreviation = itemShippingStateProvince.Abbreviation.Trim();
                }
                //StateProvince itemBillingStateProvince = states.FirstOrDefault(x => x.StateProvinceId == Convert.ToInt32(orderItem.CustomerInfo.BillingAddress.StateProvinceId));
                //if (itemBillingStateProvince != null)
                //{
                //    BillingStateProvinceAbbreviation = itemBillingStateProvince.Abbreviation.Trim();
                //}
                address2.Region     = ShippingStateProvinceAbbreviation;                         // "IL";
                address2.Country    = orderItem.CustomerInfo.ShippingAddress.CountryCode.Trim(); // "US";
                address2.PostalCode = orderItem.CustomerInfo.ShippingAddress.ZipPostalCode;      //  "90067"; //  "60602";
                OrderSkuItems       = orderItem.SkuItems;
            }
            else if (CartTax)
            {
                StateProvince itemShippingStateProvince = states.FirstOrDefault(x => x.StateProvinceId == Convert.ToInt32(clientData.CustomerInfo.ShippingAddress.StateProvinceId));
                if (itemShippingStateProvince != null)
                {
                    ShippingStateProvinceAbbreviation = itemShippingStateProvince.Abbreviation.Trim();
                }
                getTaxRequest.CustomerCode = "1";                                         // "ABC4335";
                //getTaxRequest.CompanyCode = config.Attributes["companyCode"].Value;
                getTaxRequest.DocDate = DateTime.Now.ToString("yyyy-MM-dd");              // "2014-07-23";
                address2.Line1        = clientData.CustomerInfo.ShippingAddress.Address1; // "1999 Avenue of Stars"; // "118 N Clark St";
                address2.Line2        = clientData.CustomerInfo.ShippingAddress.Address2; // "Suite 1830"; // "Suite 100";
                // address2.Line3 = "ATTN Accounts Payable";
                address2.City   = clientData.CustomerInfo.ShippingAddress.City;           // "Los Angeles"; // "Chicago";
                address2.Region = ShippingStateProvinceAbbreviation;                      // "IL";
                List <Country> countries   = CountryManager.GetActiveCountry();
                Country        ShipCountry = countries.First(x => x.CountryId == clientData.CustomerInfo.ShippingAddress.CountryId);
                // address2.Country = "US"; // clientData.CustomerInfo.ShippingAddress.CountryCode.Trim(); // "US";
                if (itemShippingStateProvince != null)
                {
                    address2.Country = ShipCountry.Code.Trim();
                }
                else
                {
                    address2.Country = "US";
                }
                address2.PostalCode = clientData.CustomerInfo.ShippingAddress.ZipPostalCode; //  "90067"; //  "60602";
                OrderSkuItems       = clientData.CartInfo.CartItems;
            }

            CSWeb.AvaTax.Address[] addresses = { address1, address2 };
            getTaxRequest.Addresses = addresses;
            CSWeb.AvaTax.Line[] lines = new CSWeb.AvaTax.Line[OrderSkuItems.Count]; // orderItem.SkuItems.Count];
            int LineNo = 1;

            foreach (Sku Item in OrderSkuItems) // orderItem.SkuItems)
            {
                Item.LoadAttributeValues();
                CSWeb.AvaTax.Line line1 = new CSWeb.AvaTax.Line();
                if (LineNo < 10)
                {
                    line1.LineNo = "0" + LineNo.ToString();
                }
                else
                {
                    line1.LineNo = LineNo.ToString();
                }
                line1.ItemCode = Item.SkuCode;
                line1.Qty      = Item.Quantity;
                decimal SKUCost = Item.FullPrice * Item.Quantity; // 249.95M;

                //if (Item.AttributeValues.ContainsKey("isrushshipsku"))
                //{
                //    if (Item.AttributeValues["isrushshipsku"].Value.ToString().Equals("1"))
                //    {
                //        if (Item.AttributeValues.ContainsKey("shippingcost_display"))
                //        {
                //            SKUCost = Convert.ToDecimal(Item.AttributeValues["shippingcost_display"].Value.ToString().Trim());
                //        }
                //    }
                //}

                line1.Amount          = SKUCost;
                line1.OriginCode      = "01";
                line1.DestinationCode = "02";
                lines[LineNo - 1]     = line1; //  Add it Array of Lines
                LineNo = LineNo + 1;
            }
            getTaxRequest.Lines       = lines;
            getTaxRequest.CompanyCode = config.Attributes["companyCode"].Value;

            return(getTaxRequest);
        }
Пример #25
0
        public static void Test()
        {
            string accountNumber = ConfigurationManager.AppSettings["AvaTax:AccountNumber"];
            string licenseKey = ConfigurationManager.AppSettings["AvaTax:LicenseKey"];
            string serviceURL = ConfigurationManager.AppSettings["AvaTax:ServiceUrl"];

            TaxSvc taxSvc = new TaxSvc();

            // Header Level Parameters
            // Required Header Parameters
            taxSvc.Configuration.Security.Account = accountNumber;
            taxSvc.Configuration.Security.License = licenseKey;
            taxSvc.Configuration.Url = serviceURL;
            taxSvc.Configuration.ViaUrl = serviceURL;
            taxSvc.Profile.Client = "AvaTaxSample";

            // Optional Header Parameters
            taxSvc.Profile.Name = "Development";

            GetTaxRequest getTaxRequest = new GetTaxRequest();

            // Document Level Parameters
            // Required Request Parameters
            getTaxRequest.CustomerCode = "ABC4335";
            getTaxRequest.DocDate = DateTime.Parse("2014-01-01");
            //// getTaxRequest.Lines is also required, and is presented later in this file.

            // Best Practice Request Parameters
            getTaxRequest.CompanyCode = "APITrialCompany";
            getTaxRequest.DocCode = "INV001";
            getTaxRequest.DetailLevel = DetailLevel.Tax;
            getTaxRequest.Commit = false;
            getTaxRequest.DocType = DocumentType.SalesInvoice;

            // Situational Request Parameters
            // getTaxRequest.BusinessIdentificationNo = "234243";
            // getTaxRequest.CustomerUsageType = "G";
            // getTaxRequest.ExemptionNo = "12345";
            // getTaxRequest.Discount = 50;
            // getTaxRequest.LocationCode = "01";
            // getTaxRequest.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
            // getTaxRequest.TaxOverride.Reason = "Adjustment for return";
            // getTaxRequest.TaxOverride.TaxDate = DateTime.Parse("2013-07-01");
            // getTaxRequest.TaxOverride.TaxAmount = 0;
            // getTaxRequest.ServiceMode = ServiceMode.Automatic;

            // Optional Request Parameters
            getTaxRequest.PurchaseOrderNo = "PO123456";
            getTaxRequest.ReferenceCode = "ref123456";
            getTaxRequest.PosLaneCode = "09";
            getTaxRequest.CurrencyCode = "USD";
            getTaxRequest.ExchangeRate = (decimal)1.0;
            getTaxRequest.ExchangeRateEffDate = DateTime.Parse("2013-01-01");
            getTaxRequest.SalespersonCode = "Bill Sales";

            // Address Data
            Address address1 = new Address();
            address1.Line1 = "45 Fremont Street";
            address1.City = "San Francisco";
            address1.Region = "CA";

            Address address2 = new Address();
            address2.Line1 = "118 N Clark St";
            address2.Line2 = "Suite 100";
            address2.Line3 = "ATTN Accounts Payable";
            address2.City = "Chicago";
            address2.Region = "IL";
            address2.Country = "US";
            address2.PostalCode = "60602";

            Address address3 = new Address();
            address3.Latitude = "47.627935";
            address3.Longitude = "-122.51702";

            // Line Data
            // Required Parameters
            Line line1 = new Line();
            line1.No = "01";
            line1.ItemCode = "N543";
            line1.Qty = 1;
            line1.Amount = 10;
            line1.OriginAddress = address1;
            line1.DestinationAddress = address2;

            // Best Practice Request Parameters
            line1.Description = "Red Size 7 Widget";
            line1.TaxCode = "NT";

            // Situational Request Parameters
            // line1.CustomerUsageType = "L";
            // line1.ExemptionNo = "12345";
            // line1.Discounted = true;
            // line1.TaxIncluded = true;
            // line1.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
            // line1.TaxOverride.Reason = "Adjustment for return";
            // line1.TaxOverride.TaxDate = DateTime.Parse("2013-07-01");
            // line1.TaxOverride.TaxAmount = 0;

            // Optional Request Parameters
            line1.Ref1 = "ref123";
            line1.Ref2 = "ref456";
            getTaxRequest.Lines.Add(line1);

            Line line2 = new Line();
            line2.No = "02";
            line2.ItemCode = "T345";
            line2.Qty = 3;
            line2.Amount = 150;
            line2.OriginAddress = address1;
            line2.DestinationAddress = address3;
            line2.Description = "Size 10 Green Running Shoe";
            line2.TaxCode = "PC030147";
            getTaxRequest.Lines.Add(line2);

            Line line3 = new Line();
            line3.No = "02-FR";
            line3.ItemCode = "FREIGHT";
            line3.Qty = 1;
            line3.Amount = 15;
            line3.OriginAddress = address1;
            line3.DestinationAddress = address3;
            line3.Description = "Shipping Charge";
            line3.TaxCode = "FR";
            getTaxRequest.Lines.Add(line3);

            GetTaxResult getTaxResult = taxSvc.GetTax(getTaxRequest);

            Console.WriteLine("GetTaxTest Result: " + getTaxResult.ResultCode.ToString());
            if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success))
            {
                foreach (Message message in getTaxResult.Messages)
                {
                    Console.WriteLine(message.Summary);
                }
            }
            else
            {
                Console.WriteLine("Document Code: " + getTaxResult.DocCode + " Total Tax: " + getTaxResult.TotalTax);
                foreach (TaxLine taxLine in getTaxResult.TaxLines)
                {
                    Console.WriteLine("    " + "Line Number: " + taxLine.No + " Line Tax: " + getTaxResult.TotalTax.ToString());
                    foreach (TaxDetail taxDetail in taxLine.TaxDetails)
                    {
                        Console.WriteLine("        " + "Jurisdiction: " + taxDetail.JurisName + " Tax: " + taxDetail.Tax.ToString());
                    }
                }
            }
        }
        public static GetTaxRequest ToAvaTaxRequest(this VirtoCommerce.Domain.Order.Model.CustomerOrder order, string companyCode, Contact contact, bool commit = false)
        {
            if (order.Addresses != null && order.Addresses.Any() && order.Items != null && order.Items.Any())
            {
                // Document Level Elements
                // Required Request Parameters
                var getTaxRequest = new GetTaxRequest
                {
                    CustomerCode = order.CustomerId,
                    DocDate      =
                        order.CreatedDate == DateTime.MinValue
                            ? DateTime.UtcNow.ToString("yyyy-MM-dd")
                            : order.CreatedDate.ToString("yyyy-MM-dd"),
                    CompanyCode  = companyCode,
                    Client       = "VirtoCommerce,2.x,VirtoCommerce",
                    DetailLevel  = DetailLevel.Tax,
                    Commit       = commit,
                    DocType      = DocType.SalesInvoice,
                    DocCode      = order.Number,
                    CurrencyCode = order.Currency.ToString()
                };

                // Best Practice Request Parameters

                // Situational Request Parameters
                // getTaxRequest.CustomerUsageType = "G";
                // getTaxRequest.ExemptionNo = "12345";
                // getTaxRequest.BusinessIdentificationNo = "234243";
                // getTaxRequest.Discount = 50;
                // getTaxRequest.TaxOverride = new TaxOverrideDef();
                // getTaxRequest.TaxOverride.TaxOverrideType = "TaxDate";
                // getTaxRequest.TaxOverride.Reason = "Adjustment for return";
                // getTaxRequest.TaxOverride.TaxDate = "2013-07-01";
                // getTaxRequest.TaxOverride.TaxAmount = "0";

                // Optional Request Parameters
                //getTaxRequest.PurchaseOrderNo = order.Number;
                //getTaxRequest.ReferenceCode = "ref123456";
                //getTaxRequest.PosLaneCode = "09";

                //add customer tax exemption code to cart if exists
                getTaxRequest.ExemptionNo = contact.GetDynamicPropertyValue("Tax exempt", string.Empty);

                string destinationAddressIndex = "0";

                // Address Data
                var addresses = new List <Address>();

                foreach (var address in order.Addresses.Select((x, i) => new { Value = x, Index = i }))
                {
                    addresses.Add(new Address
                    {
                        AddressCode = address.Index.ToString(CultureInfo.InvariantCulture),
                        Line1       = address.Value.Line1,
                        City        = address.Value.City,
                        Region      = address.Value.RegionName ?? address.Value.RegionId,
                        PostalCode  = address.Value.PostalCode,
                        Country     = address.Value.CountryName
                    });

                    if (address.Value.AddressType == AddressType.Shipping ||
                        address.Value.AddressType == AddressType.Shipping)
                    {
                        destinationAddressIndex = address.Index.ToString(CultureInfo.InvariantCulture);
                    }
                }

                getTaxRequest.Addresses = addresses.ToArray();

                // Line Data
                // Required Parameters

                getTaxRequest.Lines = order.Items.Select(li =>
                                                         new Line
                {
                    LineNo          = li.Id,
                    ItemCode        = li.ProductId,
                    Qty             = li.Quantity,
                    Amount          = li.Price * li.Quantity,
                    OriginCode      = destinationAddressIndex, //TODO set origin address (fulfillment?)
                    DestinationCode = destinationAddressIndex,
                    Description     = li.Name,
                    TaxCode         = li.TaxType
                }
                                                         ).ToList();

                //Add shipments as lines
                if (order.Shipments != null && order.Shipments.Any())
                {
                    order.Shipments.ForEach(sh =>
                                            getTaxRequest.Lines.Add(new Line
                    {
                        LineNo          = sh.Id ?? sh.ShipmentMethodCode,
                        ItemCode        = sh.ShipmentMethodCode,
                        Qty             = 1,
                        Amount          = sh.Sum,
                        OriginCode      = destinationAddressIndex, //TODO set origin address (fulfillment?)
                        DestinationCode = destinationAddressIndex,
                        Description     = sh.ShipmentMethodCode,
                        TaxCode         = sh.TaxType ?? "FR"
                    })
                                            );
                }

                return(getTaxRequest);
            }
            return(null);
        }
Пример #27
0
        /// <summary>
        /// Calculate taxes due on order items. Determined by a combination of
        /// TaxCode used, address information, and nexus/jurisdiction.
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static Order Calculate(Order order)
        {
            var taxDetail = new OrderTaxDetail();

            if (Ping())
            {
                var taxRequest = new GetTaxRequest
                {
                    CustomerCode = order.DistId.ToString(),
                    DocDate = DateTime.Now,
                    CompanyCode = ConfigService.CompanyCode(),
                    DocCode = order.Id.ToString(),
                    DetailLevel = DetailLevel.Tax,
                    Commit = false,
                    DocType = (DocumentType) order.DocType,
                    OriginAddress = ConvertAddress(order, AddressType.ShipFrom),
                    DestinationAddress = ConvertAddress(order, AddressType.ShipTo),
                    SalespersonCode = order.SalesPersonCode,

                };

                if (order.TaxOverride != null)
                {
                    taxRequest.TaxOverride.TaxOverrideType =
                        (Avalara.AvaTax.Adapter.TaxService.TaxOverrideType) order.TaxOverride.TaxOverrideType;
                    taxRequest.TaxOverride.Reason = order.TaxOverride.Reason;
                    taxRequest.TaxOverride.TaxAmount = order.TaxOverride.TaxAmount;
                    taxRequest.TaxOverride.TaxDate = order.TaxOverride.TaxDate;
                }

                // Ship from address
                var address1 = new Address
                {
                    Line1 = order.ShipFromAddress.Address1,
                    Line2 = order.ShipFromAddress.Address2,
                    City = order.ShipFromAddress.City,
                    Region = order.ShipFromAddress.State,
                    PostalCode = order.ShipFromAddress.PostalCode
                };

                // Ship to address
                var address2 = new Address
                {
                    Line1 = order.ShipToAddress.Address1,
                    Line2 = order.ShipToAddress.Address2,
                    City = order.ShipToAddress.City,
                    Region = order.ShipToAddress.State,
                    PostalCode = order.ShipToAddress.PostalCode
                };

                int lineCount = 1;

                foreach (var item in order.Items)
                {
                    // Line data
                    var line = new Line
                    {
                        No = lineCount.ToString("00000") + "-" + item.Id,
                        ItemCode = item.Sku,
                        Qty = item.Qty,
                        Amount = item.Price,
                        OriginAddress = address1,
                        DestinationAddress = address2,
                        Description = item.Description,
                        TaxCode = item.TaxCode
                    };

                    taxRequest.Lines.Add(line);

                    lineCount += 1;
                }

                GetTaxResult taxResult = null;

                try
                {
                    taxResult = SetupTaxSvc.Result().GetTax(taxRequest);
                }
                catch(Exception ex)
                {
                    order.Error = true;
                    order.ErrorException = ex;
                }

                if (!order.Error)
                {
                    if (taxResult != null)
                    {
                        taxDetail.DocCode = taxResult.DocCode;
                        taxDetail.TotalAmount = taxResult.TotalAmount;
                        taxDetail.TotalTax = taxResult.TotalTax;
                        taxDetail.TotalTaxable = taxResult.TotalTaxable;
                        taxDetail.TransactionId = taxResult.TransactionId;

                        var lines = new List<OrderTaxLine>();

                        foreach (TaxLine taxLine in taxResult.TaxLines)
                        {
                            var line = new OrderTaxLine
                            {
                                LineNo = taxLine.No,
                                Rate = taxLine.Rate,
                                Tax = taxLine.Tax,
                                TaxCalculated = taxLine.TaxCalculated,
                                AccountingMethod = taxLine.AccountingMethod.ToString(),
                                BoundaryLevel = taxLine.BoundaryLevel.ToString(),
                                TaxCode = taxLine.TaxCode
                            };
                            lines.Add(line);
                        }

                        taxDetail.OrderTaxLines = lines;
                        taxDetail.OrderTotal = taxResult.TotalAmount + taxResult.TotalTax;
                    }

                    order.OrderTaxDetail = taxDetail;
                }
            }

            return order;
        }
        protected virtual GetTaxRequest BuildGetTaxRequestUnbilled(POOrder order)
        {
            if (order == null)
            {
                throw new PXArgumentException(nameof(order));
            }

            Vendor   vend = (Vendor)Base.vendor.View.SelectSingleBound(new object[] { order });
            Location loc  = (Location)Base.location.View.SelectSingleBound(new object[] { order });

            IAddressBase fromAddress = GetFromAddress(order);
            IAddressBase toAddress   = GetToAddress(order);

            if (fromAddress == null)
            {
                throw new PXException(Messages.FailedGetFromAddressSO);
            }

            if (toAddress == null)
            {
                throw new PXException(Messages.FailedGetToAddressSO);
            }

            GetTaxRequest request = new GetTaxRequest();

            request.CompanyCode        = CompanyCodeFromBranch(order.TaxZoneID, order.BranchID);
            request.CurrencyCode       = order.CuryID;
            request.CustomerCode       = vend.AcctCD;
            request.OriginAddress      = AddressConverter.ConvertTaxAddress(fromAddress);
            request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
            request.DocCode            = string.Format("PO.{0}.{1}", order.OrderType, order.OrderNbr);
            request.DocDate            = order.OrderDate.GetValueOrDefault();
            request.LocationCode       = GetExternalTaxProviderLocationCode(order);

            int mult = 1;

            request.CustomerUsageType = loc.CAvalaraCustomerUsageType;
            if (!string.IsNullOrEmpty(loc.CAvalaraExemptionNumber))
            {
                request.ExemptionNo = loc.CAvalaraExemptionNumber;
            }


            request.DocType = TaxDocumentType.PurchaseOrder;

            PXSelectBase <POLine> select = new PXSelectJoin <POLine,
                                                             LeftJoin <InventoryItem, On <POLine.FK.InventoryItem>,
                                                                       LeftJoin <Account, On <Account.accountID, Equal <InventoryItem.salesAcctID> > > >,
                                                             Where <POLine.orderType, Equal <Current <POOrder.orderType> >, And <POLine.orderNbr, Equal <Current <POOrder.orderNbr> > > >,
                                                             OrderBy <Asc <POLine.lineNbr> > >(Base);


            foreach (PXResult <POLine, InventoryItem, Account> res in select.View.SelectMultiBound(new object[] { order }))
            {
                POLine        tran         = (POLine)res;
                InventoryItem item         = (InventoryItem)res;
                Account       salesAccount = (Account)res;

                if (tran.UnbilledAmt > 0)
                {
                    var line = new TaxCartItem();
                    line.Index              = tran.LineNbr ?? 0;
                    line.Amount             = mult * tran.CuryUnbilledAmt.GetValueOrDefault();
                    line.Description        = tran.TranDesc;
                    line.OriginAddress      = AddressConverter.ConvertTaxAddress(GetFromAddress(order, tran));
                    line.DestinationAddress = AddressConverter.ConvertTaxAddress(GetToAddress(order, tran));
                    line.ItemCode           = item.InventoryCD;
                    line.Quantity           = tran.BaseUnbilledQty.GetValueOrDefault();
                    line.Discounted         = request.Discount > 0;
                    line.RevAcct            = salesAccount.AccountCD;

                    line.TaxCode = tran.TaxCategoryID;

                    request.CartItems.Add(line);
                }
            }

            return(request);
        }
        public override POOrder CalculateExternalTax(POOrder order)
        {
            var  toAddress    = GetToAddress(order);
            bool isNonTaxable = IsNonTaxable(toAddress);

            if (isNonTaxable)
            {
                order.IsTaxValid         = true;
                order.IsUnbilledTaxValid = true;
                ApplyTax(order, GetTaxResult.Empty, GetTaxResult.Empty);

                return(order);
            }

            var service = TaxProviderFactory(Base, order.TaxZoneID);

            GetTaxRequest getRequest         = null;
            GetTaxRequest getRequestUnbilled = null;

            bool isValidByDefault = true;

            if (order.IsTaxValid != true)
            {
                getRequest = BuildGetTaxRequest(order);

                if (getRequest.CartItems.Count > 0)
                {
                    isValidByDefault = false;
                }
                else
                {
                    getRequest = null;
                }
            }

            if (order.IsUnbilledTaxValid != true)
            {
                getRequestUnbilled = BuildGetTaxRequestUnbilled(order);
                if (getRequestUnbilled.CartItems.Count > 0)
                {
                    isValidByDefault = false;
                }
                else
                {
                    getRequestUnbilled = null;
                }
            }

            if (isValidByDefault)
            {
                PXDatabase.Update <POOrder>(
                    new PXDataFieldAssign(nameof(POOrder.IsTaxValid), true),
                    new PXDataFieldAssign(nameof(POOrder.IsUnbilledTaxValid), true),
                    new PXDataFieldRestrict(nameof(POOrder.OrderType), PXDbType.VarChar, 2, order.OrderType, PXComp.EQ),
                    new PXDataFieldRestrict(nameof(POOrder.OrderNbr), PXDbType.NVarChar, 15, order.OrderNbr, PXComp.EQ)
                    );
                order.IsTaxValid         = true;
                order.IsUnbilledTaxValid = true;
                PXTimeStampScope.PutPersisted(Base.Document.Cache, order, PXDatabase.SelectTimeStamp());
                return(order);
            }

            GetTaxResult result         = null;
            GetTaxResult resultUnbilled = null;

            bool getTaxFailed = false;

            if (getRequest != null)
            {
                result = service.GetTax(getRequest);
                if (!result.IsSuccess)
                {
                    getTaxFailed = true;
                }
            }
            if (getRequestUnbilled != null)
            {
                resultUnbilled = service.GetTax(getRequestUnbilled);
                if (!resultUnbilled.IsSuccess)
                {
                    getTaxFailed = true;
                }
            }

            if (!getTaxFailed)
            {
                try
                {
                    ApplyTax(order, result, resultUnbilled);
                    PXDatabase.Update <POOrder>(
                        new PXDataFieldAssign(nameof(POOrder.IsTaxValid), true),
                        new PXDataFieldAssign(nameof(POOrder.IsUnbilledTaxValid), true),
                        new PXDataFieldRestrict(nameof(POOrder.OrderType), PXDbType.VarChar, 2, order.OrderType, PXComp.EQ),
                        new PXDataFieldRestrict(nameof(POOrder.OrderNbr), PXDbType.NVarChar, 15, order.OrderNbr, PXComp.EQ)
                        );
                    order.IsTaxValid         = true;
                    order.IsUnbilledTaxValid = true;
                    PXTimeStampScope.PutPersisted(Base.Document.Cache, order, PXDatabase.SelectTimeStamp());
                }
                catch (PXOuterException ex)
                {
                    string msg = TX.Messages.FailedToApplyTaxes;
                    foreach (string err in ex.InnerMessages)
                    {
                        msg += Environment.NewLine + err;
                    }

                    throw new PXException(ex, msg);
                }
                catch (Exception ex)
                {
                    string msg = TX.Messages.FailedToApplyTaxes;
                    msg += Environment.NewLine + ex.Message;

                    throw new PXException(ex, msg);
                }
            }
            else
            {
                ResultBase taxResult = result ?? resultUnbilled;
                if (taxResult != null)
                {
                    LogMessages(taxResult);
                }

                throw new PXException(TX.Messages.FailedToGetTaxes);
            }

            return(order);
        }
Пример #30
0
        public static GetTaxRequest ToAvaTaxAdjustmentRequest(this VirtoCommerce.Domain.Order.Model.CustomerOrder modifiedOrder, string companyCode, Contact contact, VirtoCommerce.Domain.Order.Model.CustomerOrder originalOrder, bool commit = false)
        {
            if (modifiedOrder.Addresses != null && modifiedOrder.Addresses.Any() && originalOrder.Items != null && originalOrder.Items.Any())
            {
                // Document Level Elements
                // Required Request Parameters
                var getTaxRequest = new GetTaxRequest
                {
                    CustomerCode = modifiedOrder.CustomerId,
                    DocDate      = DateTime.UtcNow.ToString("yyyy-MM-dd"),
                    CompanyCode  = companyCode,
                    Client       = "VirtoCommerce,2.x,VirtoCommerce",
                    DocCode      = string.Format("{0}.{1}", originalOrder.Number, DateTime.UtcNow.ToString("yy-MM-dd-hh-mm")),
                    DetailLevel  = DetailLevel.Tax,
                    Commit       = commit,
                    DocType      = DocType.ReturnInvoice,
                    TaxOverride  = new TaxOverrideDef
                    {
                        TaxOverrideType = "TaxDate",
                        Reason          = "Adjustment for return",
                        TaxDate         = originalOrder.CreatedDate == DateTime.MinValue
                            ? DateTime.UtcNow.ToString("yyyy-MM-dd")
                            : originalOrder.CreatedDate.ToString("yyyy-MM-dd"),
                        TaxAmount = "0"
                    }
                };

                // Best Practice Request Parameters

                // Situational Request Parameters
                // getTaxRequest.CustomerUsageType = "G";
                // getTaxRequest.ExemptionNo = "12345";
                // getTaxRequest.BusinessIdentificationNo = "234243"; //for VAT tax calculations
                // getTaxRequest.Discount = 50;

                // Optional Request Parameters
                //getTaxRequest.PurchaseOrderNo = order.Number;
                getTaxRequest.ReferenceCode = originalOrder.Number;
                //getTaxRequest.PosLaneCode = "09";
                getTaxRequest.CurrencyCode = modifiedOrder.Currency.ToString();

                //add customer tax exemption code to cart if exists
                getTaxRequest.ExemptionNo = contact.GetDynamicPropertyValue("Tax exempt", string.Empty);

                string destinationAddressIndex = "0";

                // Address Data
                var addresses = new List <Address>();

                foreach (var address in modifiedOrder.Addresses.Select((x, i) => new { Value = x, Index = i }))
                {
                    addresses.Add(new Address
                    {
                        AddressCode = address.Index.ToString(CultureInfo.InvariantCulture),
                        Line1       = address.Value.Line1,
                        City        = address.Value.City,
                        Region      = address.Value.RegionName ?? address.Value.RegionId,
                        PostalCode  = address.Value.PostalCode,
                        Country     = address.Value.CountryName
                    });

                    if (address.Value.AddressType == AddressType.Shipping ||
                        address.Value.AddressType == AddressType.Shipping)
                    {
                        destinationAddressIndex = address.Index.ToString(CultureInfo.InvariantCulture);
                    }
                }

                getTaxRequest.Addresses = addresses.ToArray();

                // Line Data
                // Required Parameters

                getTaxRequest.Lines = originalOrder.Items.Where(i => !modifiedOrder.Items.Any(mli => mli.Id.Equals(i.Id)) || i.Quantity > (modifiedOrder.Items.Single(oi => oi.Id.Equals(i.Id)).Quantity)).Select(li =>
                                                                                                                                                                                                                  new Line
                {
                    LineNo          = li.Id,
                    ItemCode        = li.ProductId,
                    Qty             = modifiedOrder.Items.Any(mli => mli.Id.Equals(li.Id)) ? Math.Abs(li.Quantity - modifiedOrder.Items.Single(oi => oi.Id.Equals(li.Id)).Quantity) : li.Quantity,
                    Amount          = modifiedOrder.Items.Any(mli => mli.Id.Equals(li.Id)) ? -(li.Price * li.Quantity - modifiedOrder.Items.Single(oi => oi.Id.Equals(li.Id)).Price *modifiedOrder.Items.Single(mli => mli.Id.Equals(li.Id)).Quantity) : -li.Price * li.Quantity,
                    OriginCode      = destinationAddressIndex, //TODO set origin address (fulfillment?)
                    DestinationCode = destinationAddressIndex,
                    Description     = li.Name,
                    TaxCode         = li.TaxType
                }
                                                                                                                                                                                                                  ).ToList();

                return(getTaxRequest);
            }
            return(null);
        }
Пример #31
0
        public static GetTaxRequest BuildGetTaxRequest(CustomerOrder order)
        {
            GetTaxRequest getTaxRequest = new GetTaxRequest();

            // Document Level Parameters
            // Required Request Parameters
            getTaxRequest.CustomerCode = Properties.Settings.Default.Client;
            getTaxRequest.DocDate      = DateTime.Now;
            //// getTaxRequest.Lines is also required, and is presented later in this file.

            // Best Practice Request Parameters
            //getTaxRequest.CompanyCode = Properties.Settings.Default.Client;
            getTaxRequest.DocCode = order.OCN;
            //getTaxRequest.DetailLevel = DetailLevel.Tax;
            //getTaxRequest.Commit = false;
            getTaxRequest.DocType = DocumentType.SalesInvoice;

            // Situational Request Parameters
            // getTaxRequest.BusinessIdentificationNo = "234243";
            // getTaxRequest.CustomerUsageType = "G";
            // getTaxRequest.ExemptionNo = "12345";
            // getTaxRequest.Discount = 50;
            // getTaxRequest.LocationCode = "01";

            // Optional Request Parameters
            //getTaxRequest.PurchaseOrderNo = "PO123456";
            //getTaxRequest.ReferenceCode = "ref123456";
            //getTaxRequest.PosLaneCode = "09";
            //getTaxRequest.CurrencyCode = "USD";
            //getTaxRequest.ExchangeRate = (decimal)1.0;
            //getTaxRequest.ExchangeRateEffDate = DateTime.Parse("2013-01-01");
            //getTaxRequest.SalespersonCode = "Bill Sales";


            // Address Data
            Address address1 = new Address();

            address1.Line1 = Properties.Settings.Default.CompanyAddressLine1;
            //address2.line2 = "suite 100";
            //address2.line3 = "attn accounts payable";
            address1.City       = Properties.Settings.Default.CompanyCity;
            address1.Region     = Properties.Settings.Default.CompanyState;
            address1.Country    = Properties.Settings.Default.CompanyCountry;
            address1.PostalCode = Properties.Settings.Default.CompanyPostalCode;

            Address address2 = new Address();

            //address1.AddressCode = "01";
            address2.Line1      = order.AddressLine1;
            address2.Line2      = order.AddressLine2;
            address2.City       = order.City;
            address2.Region     = order.State;
            address2.PostalCode = order.PostalCode;
            address2.Country    = order.Country;
            //address1.Latitude = Convert.ToDecimal(40.601567);
            //address1.Longitude = Convert.ToDecimal(-105.066062);

            //Address address3 = new Address();
            //address3.Latitude = "47.627935";
            //address3.Longitude = "-122.51702";

            // Line Data
            // Required Parameters
            Line line1 = new Line();

            line1.No = "01";
            //line1.ItemCode = "N543";
            line1.Qty                = order.Quantity;
            line1.Amount             = order.TotalAmount;
            line1.OriginAddress      = address1;
            line1.DestinationAddress = address2;

            // Best Practice Request Parameters
            //line1.Description = "Red Size 7 Widget";
            //line1.TaxCode = "NT";

            // Situational Request Parameters
            // line1.CustomerUsageType = "L";
            // line1.ExemptionNo = "12345";
            // line1.Discounted = true;
            // line1.TaxIncluded = true;
            // line1.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
            // line1.TaxOverride.Reason = "Adjustment for return";
            // line1.TaxOverride.TaxDate = DateTime.Parse("2013-07-01");
            // line1.TaxOverride.TaxAmount = 0;

            // Optional Request Parameters
            //line1.Ref1 = "ref123";
            //line1.Ref2 = "ref456";
            getTaxRequest.Lines.Add(line1);

            //Line line2 = new Line();
            //line2.No = "02";
            //line2.ItemCode = "T345";
            //line2.Qty = 3;
            //line2.Amount = 150;
            //line2.OriginAddress = address1;
            //line2.DestinationAddress = address3;
            //line2.Description = "Size 10 Green Running Shoe";
            //line2.TaxCode = "PC030147";
            //getTaxRequest.Lines.Add(line2);

            //Line line3 = new Line();
            //line3.No = "02-FR";
            //line3.ItemCode = "FREIGHT";
            //line3.Qty = 1;
            //line3.Amount = 15;
            //line3.OriginAddress = address1;
            //line3.DestinationAddress = address3;
            //line3.Description = "Shipping Charge";
            //line3.TaxCode = "FR";
            //getTaxRequest.Lines.Add(line3);

            return(getTaxRequest);
        }
Пример #32
0
        public AvaTaxResult GetTax(DocumentType docType, string companyCode, string docCode,
                                   BaseAddress originationAddress, BaseAddress destinationAddress, List <Line> items, decimal orderDiscount,
                                   string customerCode, string currencyCode,
                                   bool taxExempt, string taxExemptionNumber, bool applyVATRules)
        {
            var result = new AvaTaxResult();

            var gtr = new GetTaxRequest
            {
                OriginAddress      = ConvertBaseAddress(originationAddress),
                DestinationAddress = ConvertBaseAddress(destinationAddress),
                CurrencyCode       = currencyCode
            };

            if (taxExempt)
            {
                if (!applyVATRules)
                {
                    gtr.ExemptionNo = taxExemptionNumber;
                }
                else
                {
                    gtr.BusinessIdentificationNo = taxExemptionNumber;
                }
            }

            gtr.CompanyCode  = companyCode;
            gtr.CustomerCode = customerCode;
            gtr.DetailLevel  = DetailLevel.Line;
            gtr.DocCode      = docCode;
            gtr.DocType      = ConvertDocType(docType);
            gtr.DocDate      = DateTime.UtcNow;

            gtr.Discount = -1 * orderDiscount;
            foreach (var l in items)
            {
                var nl = ConvertLine(l);
                gtr.Lines.Add(nl);
            }

            var svc   = GetTaxServiceProxy();
            var gtres = svc.GetTax(gtr);

            if (gtres.ResultCode != avt.SeverityLevel.Success)
            {
                result.Success = false;
                result.Messages.Add("GetTax Failed");
                ApplyMessagesToResult(result, gtres.Messages);
            }
            else
            {
                result.Success = true;

                result.DocCode     = gtres.DocCode;
                result.TotalAmount = gtres.TotalAmount;
                result.TotalTax    = gtres.TotalTax;

                // shipping line is always present ( even if 0 )
                // so the last item is shipping
                for (var i = 0; i < gtres.TaxLines.Count; i++)
                {
                    var line = gtres.TaxLines[i];
                    if (i < gtres.TaxLines.Count - 1)
                    {
                        var lineResult = new AvaTaxLineResult
                        {
                            No       = line.No,
                            TaxRate  = (decimal)line.Rate,
                            TaxValue = line.Tax
                        };
                        result.Items.Add(lineResult);
                    }
                    else
                    {
                        result.ShippingTax     = line.Tax;
                        result.ShippingTaxRate = (decimal)line.Rate;
                    }
                }
                result.ItemsTax = result.TotalTax - result.ShippingTax;
            }

            return(result);
        }