private void butLoadResult_Click(object sender, EventArgs e)
        {
            getTaxRequest.Lines.Clear();
            ReturnValue_Line = SetLineDetails();

            getTaxResult = _taxService.GetTax(getTaxRequest);
            bool FinalResultValue;

            if (ReturnValue_Company == false || ReturnValue_Line == false || ReturnValue_Address == false)
            {
                FinalResultValue = false;
            }
            else
            {
                txtResultCode.Text       = Convert.ToString(getTaxResult.ResultCode);
                txtResultDocCode.Text    = getTaxResult.DocCode;
                txtResultDocDate.Text    = Convert.ToString(getTaxResult.DocDate);
                txtResultTotTaxable.Text = Convert.ToString(getTaxResult.TotalTaxable);
                txtResultTotAmt.Text     = Convert.ToString(getTaxResult.TotalAmount);
                txtTotalTax.Text         = Convert.ToString(getTaxResult.TotalTax);
                txtResultTotDisc.Text    = Convert.ToString(getTaxResult.TotalDiscount);
                txtResultTransId.Text    = getTaxResult.TransactionId;
                FinalResultValue         = true;
            }
            if (FinalResultValue == false)
            {
                MessageBox.Show(getTaxResult.Messages[0].Summary.ToString());
            }
        }
        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);
            }
        }
Exemple #3
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;
        }
Exemple #4
0
        public static void Main()
        {
            try
            {
                string summary;
                #region Report Tax
                CustomerOrder order = new CustomerOrder();
                order.AddressLine1 = "631 LUPINE DR";
                order.City         = "FORT COLLINS";
                order.Country      = "US";
                order.State        = "CO";
                order.PostalCode   = "80524";
                order.InProduction = false;
                order.IsCommit     = false;
                order.OCN          = "041025304MS";
                order.Quantity     = 1;
                order.TotalAmount  = 66.98m;
                order.TotalTax     = 4.96m;

                GetTaxResult  getTaxResult  = GetTax.Execute(order, out summary);
                PostTaxResult postTaxResult = PostTax.Execute(order, getTaxResult, out summary);
                #endregion

                #region same day cancellation or when shipment charges is filed
                CustomerOrder cancel = new CustomerOrder();
                cancel.InProduction = false;
                cancel.OCN          = "041025304MS";
                CancelTaxResult cancelTaxResult = CancelTax.Execute(cancel.InProduction, cancel.OCN, out summary);
                #endregion

                #region harware refund
                CustomerOrder refund = new CustomerOrder();
                refund.AddressLine1 = "631 LUPINE DR";
                refund.City         = "FORT COLLINS";
                refund.Country      = "US";
                refund.State        = "CO";
                refund.PostalCode   = "80524";
                refund.InProduction = false;
                refund.IsCommit     = false;
                refund.OCN          = "041025304MS";
                refund.Quantity     = 1;
                refund.TotalAmount  = 54.99m; // hardware cost
                refund.TotalTax     = 4.06m;  // tax portion of hardware cost

                AdjustTaxResult adjustTaxResult = AdjustTaxTest.Execute(refund, out summary);
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine("An Exception Occured: " + ex.Message);
            }
            finally
            {
                Console.WriteLine("Done");
                Console.ReadLine();
            }
        }
Exemple #5
0
 private void buttonViewGetTaxResult_Click(object sender, EventArgs e)
 {
     if (gridResults.CurrentRowIndex >= 0)
     {
         GetTaxResult     getTaxResult = _reconcileTaxHistoryResult.GetTaxResults[gridResults.CurrentRowIndex];
         formGetTaxResult frm          = new formGetTaxResult(getTaxResult);
         frm.Owner = this;
         frm.ShowDialog();
     }
 }
Exemple #6
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);
            }
        }
        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);
        }
Exemple #8
0
        public override void SetAll(System.Collections.Generic.IDictionary <string, object> values)
        {
            object value;

            if (values == null)
            {
                InitStateFields(); return;
            }
            if (values.TryGetValue("GetTaxRequest", out value))
            {
                @GetTaxRequest = (GetTaxRequest)value;
            }
            if (values.TryGetValue("GetTaxResult", out value))
            {
                @GetTaxResult = (GetTaxResult)value;
            }
        }
Exemple #9
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);
        }
        public formGetTaxResult(GetTaxResult getTaxResult)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //#####################
            //### UI SETUP CODE ###
            //#####################
            SetupTaxLineHeader();
            SetupTaxDetailHeader();

            _getTaxResult = getTaxResult;

            gridTaxLines.SetDataBinding(_dataLines, "");
            gridTaxDetails.SetDataBinding(_dataDetails, "");

            LoadResultData();
        }
Exemple #11
0
        public GetTaxResult ToGetTaxResult(string taxId)
        {
            var       output   = new GetTaxResult();
            var       taxLines = new List <TaxLine>();
            TaxDetail details  = null;

            if (!Empty)
            {
                details = new TaxDetail()
                {
                    TaxName             = taxId,
                    Rate                = 0.00m,
                    TaxableAmount       = TotalTaxableAmount,
                    TaxAmount           = TotalTaxAmount,
                    TaxCalculationLevel = TaxCalculationLevel.CalcOnItemAmt,
                };

                taxLines.Add(new TaxLine()
                {
                    Index         = 1,
                    Rate          = 0.00m,
                    TaxableAmount = TotalTaxableAmount,
                    TaxAmount     = TotalTaxAmount,
                    TaxDetails    = new[] { details },
                });

                output.TaxSummary = new TaxDetail[] { details };
                output.TaxLines   = taxLines.ToArray();
            }
            else
            {
                output.TaxSummary = new TaxDetail[] {};
                output.TaxLines   = new TaxLine[] {};
            }

            output.TotalAmount    = TotalTaxableAmount;
            output.TotalTaxAmount = TotalTaxAmount;
            output.IsSuccess      = true;

            return(output);
        }
Exemple #12
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);
        }
        protected virtual void ApplyTax(CROpportunity order, GetTaxResult result)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;

            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)PXSetup <TaxZone, Where <TaxZone.taxZoneID, Equal <Required <CROpportunity.taxZoneID> > > > .Select(Base, order.TaxZoneID);

                vendor = (AP.Vendor) PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(Messages.ExternalTaxVendorNotFound);
                }
            }

            //Clear all existing Tax transactions:
            foreach (PXResult <CRTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { order }))
            {
                CRTaxTran taxTran = (CRTaxTran)res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = result.TaxSummary[i].TaxName;
                if (string.IsNullOrEmpty(taxID))
                {
                    taxID = result.TaxSummary[i].JurisCode;
                }

                if (string.IsNullOrEmpty(taxID))
                {
                    PXTrace.WriteInformation(Messages.EmptyValuesFromExternalTaxProvider);
                    continue;
                }

                CreateTax(Base, taxZone, vendor, result.TaxSummary[i], taxID);

                CRTaxTran tax = new CRTaxTran();
                tax.QuoteID        = order.QuoteNoteID;
                tax.TaxID          = taxID;
                tax.CuryTaxAmt     = Math.Abs(result.TaxSummary[i].TaxAmount);
                tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].TaxableAmount);
                tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100;

                Base.Taxes.Insert(tax);
            }

            Base.Opportunity.SetValueExt <CROpportunity.curyTaxTotal>(order, Math.Abs(result.TotalTaxAmount));

            decimal?СuryProductsAmount =
                order.ManualTotalEntry == true
                                ? order.CuryAmount - order.CuryDiscTot
                                : order.CuryLineTotal - order.CuryDiscTot + order.CuryTaxTotal;

            CalcCuryProductsAmount(order, ref СuryProductsAmount);

            Base.Opportunity.SetValueExt <CROpportunity.curyProductsAmount>(order, СuryProductsAmount ?? 0m);
        }
        protected void ApplyTax(PMQuote quote, GetTaxResult result)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;

            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)PXSetup <TaxZone> .Where <TaxZone.taxZoneID.IsEqual <@P.AsString> > .Select(Base, quote.TaxZoneID);

                vendor = (VendorMaster)PXSelectReadonly <VendorMaster, Where <VendorMaster.bAccountID, Equal <Required <VendorMaster.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(CR.Messages.ExternalTaxVendorNotFound);
                }
            }

            //Clear all existing Tax transactions:
            foreach (PXResult <CRTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { quote }))
            {
                CRTaxTran taxTran = (CRTaxTran)res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = result.TaxSummary[i].TaxName;
                if (string.IsNullOrEmpty(taxID))
                {
                    taxID = result.TaxSummary[i].JurisCode;
                }

                if (string.IsNullOrEmpty(taxID))
                {
                    PXTrace.WriteInformation(Messages.EmptyValuesFromExternalTaxProvider);
                    continue;
                }

                CreateTax(Base, taxZone, vendor, result.TaxSummary[i], taxID);

                CRTaxTran tax = new CRTaxTran();
                tax.QuoteID        = quote.QuoteID;
                tax.TaxID          = taxID;
                tax.CuryTaxAmt     = result.TaxSummary[i].TaxAmount;
                tax.CuryTaxableAmt = result.TaxSummary[i].TaxableAmount;
                tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100;

                Base.Taxes.Insert(tax);
            }

            Base.Quote.SetValueExt <PMQuote.curyTaxTotal>(quote, result.TotalTaxAmount);

            decimal?СuryProductsAmount =
                quote.ManualTotalEntry == true
                                ? quote.CuryAmount - quote.CuryDiscTot
                                : quote.CuryLineTotal - quote.CuryDiscTot + quote.CuryTaxTotal;

            Base.Quote.SetValueExt <PMQuote.curyProductsAmount>(quote, СuryProductsAmount ?? 0m);
        }
        protected virtual void ApplyTax(CAAdj invoice, GetTaxResult result)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;
            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)Base.taxzone.View.SelectSingleBound(new object[] { invoice });
                vendor  = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(Messages.ExternalTaxVendorNotFound);
                }
            }
            //Clear all existing Tax transactions:
            foreach (PXResult <CATaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { invoice }))
            {
                CATaxTran taxTran = (CATaxTran)res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = result.TaxSummary[i].TaxName;
                if (string.IsNullOrEmpty(taxID))
                {
                    taxID = result.TaxSummary[i].JurisCode;
                }

                if (string.IsNullOrEmpty(taxID))
                {
                    PXTrace.WriteInformation(Messages.EmptyValuesFromExternalTaxProvider);
                    continue;
                }

                //Insert Tax if not exists - just for the selectors sake
                Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(Base, taxID);

                if (tx == null)
                {
                    tx = new Tax
                    {
                        TaxID             = taxID,
                        Descr             = PXMessages.LocalizeFormatNoPrefixNLA(TX.Messages.ExternalTaxProviderTaxId, taxID),
                        TaxType           = CSTaxType.Sales,
                        TaxCalcType       = CSTaxCalcType.Doc,
                        TaxCalcLevel      = result.TaxSummary[i].TaxCalculationLevel.ToCSTaxCalcLevel(),
                        TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount,
                        SalesTaxAcctID    = vendor.SalesTaxAcctID,
                        SalesTaxSubID     = vendor.SalesTaxSubID,
                        ExpenseAccountID  = vendor.TaxExpenseAcctID,
                        ExpenseSubID      = vendor.TaxExpenseSubID,
                        TaxVendorID       = taxZone.TaxVendorID,
                        IsExternal        = true
                    };

                    Base.Caches[typeof(Tax)].Insert(tx);
                }

                CATaxTran tax = new CATaxTran
                {
                    Module         = BatchModule.CA,
                    TranType       = invoice.DocType,
                    RefNbr         = invoice.RefNbr,
                    TaxID          = taxID,
                    CuryTaxAmt     = Math.Abs(result.TaxSummary[i].TaxAmount),
                    CuryTaxableAmt = Math.Abs(result.TaxSummary[i].TaxableAmount),
                    TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100,
                    TaxType        = "S",
                    TaxBucketID    = 0,
                    AccountID      = vendor.SalesTaxAcctID,
                    SubID          = vendor.SalesTaxSubID,
                    JurisType      = result.TaxSummary[i].JurisType,
                    JurisName      = result.TaxSummary[i].JurisName
                };

                Base.Taxes.Insert(tax);
            }

            bool requireControlTotal = Base.casetup.Current.RequireControlTotal == true;

            if (invoice.Hold != true)
            {
                Base.casetup.Current.RequireControlTotal = false;
            }

            try
            {
                invoice.CuryTaxTotal = Math.Abs(result.TotalTaxAmount);
                Base.CAAdjRecords.Cache.SetValueExt <CAAdj.isTaxSaved>(invoice, true);
                Base.CAAdjRecords.Update(invoice);
            }
            finally
            {
                Base.casetup.Current.RequireControlTotal = requireControlTotal;
            }
        }
        public override CROpportunity CalculateExternalTax(CROpportunity order)
        {
            var  toAddress    = GetToAddress(order);
            bool isNonTaxable = IsNonTaxable(toAddress);

            if (isNonTaxable || order.BAccountID == null)
            {
                ApplyTax(order, GetTaxResult.Empty);
                order.IsTaxValid = true;
                order            = Base.Opportunity.Update(order);

                SkipTaxCalcAndSave();

                return(order);
            }

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

            GetTaxRequest getRequest       = null;
            bool          isValidByDefault = true;

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

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

            if (isValidByDefault)
            {
                order.IsTaxValid = true;
                order            = Base.Opportunity.Update(order);
                SkipTaxCalcAndSave();

                return(order);
            }

            GetTaxResult result = service.GetTax(getRequest);

            if (result.IsSuccess)
            {
                try
                {
                    ApplyTax(order, result);

                    order.IsTaxValid = true;
                    order            = Base.Opportunity.Update(order);
                    SkipTaxCalcAndSave();
                }
                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)
                {
                    throw new PXException(ex, TX.Messages.FailedToApplyTaxes);
                }
            }
            else
            {
                LogMessages(result);

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

            return(order);
        }
Exemple #17
0
        public virtual PMProforma CalculateExternalTax(PMProforma doc, bool forceRecalculate)
        {
            var toAddress = GetToAddress(doc);

            GetTaxRequest getRequest       = null;
            bool          isValidByDefault = true;

            if ((doc.IsTaxValid != true || forceRecalculate) && !IsNonTaxable(toAddress))
            {
                getRequest = BuildGetTaxRequest(doc);

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

            if (isValidByDefault)
            {
                doc.CuryTaxTotal = 0;
                doc.IsTaxValid   = true;
                Base.Document.Update(doc);

                foreach (PMTaxTran item in Base.Taxes.Select())
                {
                    Base.Taxes.Delete(item);
                }

                using (var ts = new PXTransactionScope())
                {
                    Base.Persist(typeof(PMTaxTran), PXDBOperation.Delete);
                    Base.Persist(typeof(PMProforma), PXDBOperation.Update);
                    PXTimeStampScope.PutPersisted(Base.Document.Cache, doc, PXDatabase.SelectTimeStamp());
                    ts.Complete();
                }
                return(doc);
            }

            GetTaxResult result       = null;
            var          service      = TaxProviderFactory(Base, doc.TaxZoneID);
            bool         getTaxFailed = false;

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

            if (!getTaxFailed)
            {
                try
                {
                    ApplyTax(doc, result);
                    using (var ts = new PXTransactionScope())
                    {
                        doc.IsTaxValid = true;
                        Base.Document.Update(doc);
                        Base.Persist(typeof(PMProforma), PXDBOperation.Update);
                        PXTimeStampScope.PutPersisted(Base.Document.Cache, doc, PXDatabase.SelectTimeStamp());
                        ts.Complete();
                    }
                }
                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
            {
                LogMessages(result);

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

            return(doc);
        }
        public override CAAdj CalculateExternalTax(CAAdj invoice)
        {
            var  toAddress    = GetToAddress(invoice);
            bool isNonTaxable = IsNonTaxable(toAddress);

            if (isNonTaxable)
            {
                ApplyTax(invoice, GetTaxResult.Empty);
                invoice.IsTaxValid = true;
                invoice.NonTaxable = true;
                invoice            = Base.CAAdjRecords.Update(invoice);

                SkipTaxCalcAndSave();

                return(invoice);
            }
            else if (invoice.NonTaxable == true)
            {
                Base.CurrentDocument.SetValueExt <CAAdj.nonTaxable>(invoice, false);
            }

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

            GetTaxRequest getRequest = BuildGetTaxRequest(invoice);

            if (getRequest.CartItems.Count == 0)
            {
                invoice.IsTaxValid = true;
                invoice.IsTaxSaved = false;
                invoice            = Base.CAAdjRecords.Update(invoice);
                SkipTaxCalcAndSave();
            }

            GetTaxResult result = service.GetTax(getRequest);

            if (result.IsSuccess)
            {
                try
                {
                    ApplyTax(invoice, result);
                    SkipTaxCalcAndSave();
                }
                catch (PXOuterException ex)
                {
                    try
                    {
                        CancelTax(invoice, VoidReasonCode.Unspecified);
                    }
                    catch (Exception)
                    {
                        throw new PXException(new PXException(ex, TX.Messages.FailedToApplyTaxes), TX.Messages.FailedToCancelTaxes);
                    }

                    string msg = TX.Messages.FailedToApplyTaxes;
                    foreach (string err in ex.InnerMessages)
                    {
                        msg += Environment.NewLine + err;
                    }

                    throw new PXException(ex, msg);
                }
                catch (Exception ex)
                {
                    try
                    {
                        CancelTax(invoice, VoidReasonCode.Unspecified);
                    }
                    catch (Exception)
                    {
                        throw new PXException(new PXException(ex, TX.Messages.FailedToApplyTaxes), TX.Messages.FailedToCancelTaxes);
                    }

                    string msg = TX.Messages.FailedToApplyTaxes;
                    msg += Environment.NewLine + ex.Message;

                    throw new PXException(ex, msg);
                }

                PostTaxRequest request = new PostTaxRequest();
                request.CompanyCode    = getRequest.CompanyCode;
                request.DocCode        = getRequest.DocCode;
                request.DocDate        = getRequest.DocDate;
                request.DocType        = getRequest.DocType;
                request.TotalAmount    = result.TotalAmount;
                request.TotalTaxAmount = result.TotalTaxAmount;
                PostTaxResult postResult = service.PostTax(request);

                if (postResult.IsSuccess)
                {
                    invoice.IsTaxValid = true;
                    invoice            = Base.CAAdjRecords.Update(invoice);
                    SkipTaxCalcAndSave();
                }
            }
            else
            {
                LogMessages(result);

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

            return(invoice);
        }
        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);
        }
Exemple #20
0
        public virtual void ApplyTax(PMProforma doc, GetTaxResult result)
        {
            TaxZone taxZone = (TaxZone)Base.taxzone.View.SelectSingleBound(new object[] { doc });

            if (taxZone == null)
            {
                throw new PXException(SO.Messages.TaxZoneIsNotSet);
            }

            AP.Vendor vendor = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

            if (vendor == null)
            {
                throw new PXException(TX.Messages.ExternalTaxVendorNotFound);
            }

            if (result != null)
            {
                //Clear all existing Tax transactions:
                PXSelectBase <PMTaxTran> TaxesSelect =
                    new PXSelectJoin <PMTaxTran, InnerJoin <Tax, On <Tax.taxID, Equal <PMTaxTran.taxID> > >,
                                      Where <PMTaxTran.refNbr, Equal <Current <PMProforma.refNbr> > > >(Base);
                foreach (PXResult <PMTaxTran, Tax> res in TaxesSelect.View.SelectMultiBound(new object[] { doc }))
                {
                    PMTaxTran taxTran = (PMTaxTran)res;
                    Base.Taxes.Delete(taxTran);
                }

                Base.Views.Caches.Add(typeof(Tax));

                var taxDetails = new List <PX.TaxProvider.TaxDetail>();
                for (int i = 0; i < result.TaxSummary.Length; i++)
                {
                    taxDetails.Add(result.TaxSummary[i]);
                }

                foreach (var taxDetail in taxDetails)
                {
                    string taxID = taxDetail.TaxName;
                    if (string.IsNullOrEmpty(taxID))
                    {
                        taxID = taxDetail.JurisCode;
                    }

                    if (string.IsNullOrEmpty(taxID))
                    {
                        PXTrace.WriteInformation(SO.Messages.EmptyValuesFromExternalTaxProvider);
                        continue;
                    }

                    //Insert Tax if not exists - just for the selectors sake
                    Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(Base, taxID);

                    if (tx == null)
                    {
                        tx                   = new Tax();
                        tx.TaxID             = taxID;
                        tx.Descr             = PXMessages.LocalizeFormatNoPrefixNLA(TX.Messages.ExternalTaxProviderTaxFor, taxDetail.JurisType, taxDetail.JurisName);
                        tx.TaxType           = CSTaxType.Sales;
                        tx.TaxCalcType       = CSTaxCalcType.Doc;
                        tx.TaxCalcLevel      = CSTaxCalcLevel.CalcOnItemAmt;
                        tx.TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount;
                        tx.SalesTaxAcctID    = vendor.SalesTaxAcctID;
                        tx.SalesTaxSubID     = vendor.SalesTaxSubID;
                        tx.ExpenseAccountID  = vendor.TaxExpenseAcctID;
                        tx.ExpenseSubID      = vendor.TaxExpenseSubID;
                        tx.TaxVendorID       = taxZone.TaxVendorID;
                        tx.IsExternal        = true;

                        Base.Caches[typeof(Tax)].Insert(tx);
                    }

                    PMTaxTran tax = new PMTaxTran();
                    tax.RefNbr         = doc.RefNbr;
                    tax.TaxID          = taxID;
                    tax.CuryTaxAmt     = taxDetail.TaxAmount;
                    tax.CuryTaxableAmt = taxDetail.TaxableAmount;
                    tax.TaxRate        = Convert.ToDecimal(taxDetail.Rate) * 100;
                    tax.JurisType      = taxDetail.JurisType;
                    tax.JurisName      = taxDetail.JurisName;

                    Base.Taxes.Insert(tax);
                }

                Base.Document.SetValueExt <PMProforma.curyTaxTotal>(doc, result.TotalTaxAmount);
            }

            Base.Document.Update(doc);
            SkipTaxCalcAndSave();
        }
        public async Task GeoTaxTest()
        {
            // Header Level Elements
            // Required Header Level Elements
            var    configSection = ConfigurationHelper.GetConfiguration();
            string accountNumber = configSection["accountNumber"];
            string licenseKey    = configSection["licenseKey"];
            string serviceUrl    = configSection["serviceUrl"];

            ITaxService taxSvc = new TaxService(accountNumber, licenseKey, serviceUrl);

            GetTaxRequest getTaxRequest = new GetTaxRequest
            {
                CustomerCode    = "ABC4335",
                DocDate         = "2014-01-01",
                CompanyCode     = "APITrialCompany",
                Client          = "AvaTaxSample",
                DocCode         = "INV001",
                DetailLevel     = DetailLevel.Tax,
                Commit          = false,
                DocType         = DocType.SalesInvoice,
                PurchaseOrderNo = "PO123456",
                ReferenceCode   = "ref123456",
                PosLaneCode     = "09",
                CurrencyCode    = "USD"
            };

            // Document Level Elements
            // Required Request Parameters

            // 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

            // Address Data
            Address address1 = new Address
            {
                AddressCode = "01",
                Line1       = "45 Fremont Street",
                City        = "San Francisco",
                Region      = "CA"
            };

            Address address2 = new Address
            {
                AddressCode = "02",
                Line1       = "118 N Clark St",
                Line2       = "Suite 100",
                Line3       = "ATTN Accounts Payable",
                City        = "Chicago",
                Region      = "IL",
                Country     = "US",
                PostalCode  = "60602"
            };

            Address address3 = new Address
            {
                AddressCode = "03",
                Latitude    = (decimal)47.627935,
                Longitude   = (decimal) - 122.51702
            };

            Address[] addresses = { address1, address2, address3 };
            getTaxRequest.Addresses = addresses;

            // Line Data
            // Required Parameters
            Line line1 = new Line
            {
                LineNo          = "01",
                ItemCode        = "N543",
                Qty             = 1,
                Amount          = 10,
                OriginCode      = "01",
                DestinationCode = "02",
                Description     = "Red Size 7 Widget",
                TaxCode         = "NT",
                Ref1            = "ref123",
                Ref2            = "ref456"
            };

            // Best Practice Request Parameters

            // Situational Request Parameters
            // line1.CustomerUsageType = "L";
            // line1.Discounted = true;
            // line1.TaxIncluded = true;
            // line1.BusinessIdentificationNo = "234243";
            // line1.TaxOverride = new TaxOverrideDef();
            // line1.TaxOverride.TaxOverrideType = "TaxDate";
            // line1.TaxOverride.Reason = "Adjustment for return";
            // line1.TaxOverride.TaxDate = "2013-07-01";
            // line1.TaxOverride.TaxAmount = "0";

            // Optional Request Parameters

            Line line2 = new Line
            {
                LineNo          = "02",
                ItemCode        = "T345",
                Qty             = 3,
                Amount          = 150,
                OriginCode      = "01",
                DestinationCode = "03",
                Description     = "Size 10 Green Running Shoe",
                TaxCode         = "PC030147"
            };

            Line line3 = new Line
            {
                LineNo          = "02-FR",
                ItemCode        = "FREIGHT",
                Qty             = 1,
                Amount          = 15,
                OriginCode      = "01",
                DestinationCode = "03",
                Description     = "Shipping Charge",
                TaxCode         = "FR"
            };

            Line[] lines = { line1, line2, line3 };
            getTaxRequest.Lines = lines;

            GetTaxResult getTaxResult = await taxSvc.GetTax(getTaxRequest);

            // Print results
            Console.WriteLine("GetTaxTest Result: {0}", getTaxResult.ResultCode);
            if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success))
            {
                foreach (Message message in getTaxResult.Messages)
                {
                    Console.WriteLine(message.Summary);
                }
            }
            else
            {
                Console.WriteLine("Document Code: {0} Total Tax: {1}", getTaxResult.DocCode, getTaxResult.TotalTax);
                foreach (TaxLine taxLine in getTaxResult.TaxLines ?? Enumerable.Empty <TaxLine>())
                {
                    Console.WriteLine("    Line Number: {0} Line Tax: {1}", taxLine.LineNo,
                                      taxLine.Tax.ToString(CultureInfo.CurrentCulture));
                    foreach (TaxDetail taxDetail in taxLine.TaxDetails ?? Enumerable.Empty <TaxDetail>())
                    {
                        Console.WriteLine("        Jurisdiction: {0}Tax: {1}", taxDetail.JurisName,
                                          taxDetail.Tax.ToString(CultureInfo.CurrentCulture));
                    }
                }
            }
        }
        public virtual void ApplyTax(ARInvoice invoice, GetTaxResult result)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;
            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)Base.taxzone.View.SelectSingleBound(new object[] { invoice });
                vendor  = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(TX.Messages.ExternalTaxVendorNotFound);
                }

                if (vendor.SalesTaxAcctID == null)
                {
                    throw new PXException(TX.Messages.TaxPayableAccountNotSpecified, vendor.AcctCD);
                }

                if (vendor.SalesTaxSubID == null)
                {
                    throw new PXException(TX.Messages.TaxPayableSubNotSpecified, vendor.AcctCD);
                }
            }
            Sign sign = invoice.DocType == ARDocType.CreditMemo ? Sign.Minus : Sign.Plus;

            //Clear all existing Tax transactions:
            foreach (PXResult <ARTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { invoice }))
            {
                ARTaxTran taxTran = res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = result.TaxSummary[i].TaxName;
                if (string.IsNullOrEmpty(taxID))
                {
                    taxID = result.TaxSummary[i].JurisCode;
                }

                if (string.IsNullOrEmpty(taxID))
                {
                    PXTrace.WriteInformation(Messages.EmptyValuesFromExternalTaxProvider);
                    continue;
                }

                //Insert Tax if not exists - just for the selectors sake
                Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(Base, taxID);

                if (tx == null)
                {
                    tx = new Tax
                    {
                        TaxID             = taxID,
                        Descr             = PXMessages.LocalizeFormatNoPrefixNLA(TX.Messages.ExternalTaxProviderTaxId, taxID),
                        TaxType           = CSTaxType.Sales,
                        TaxCalcType       = CSTaxCalcType.Doc,
                        TaxCalcLevel      = result.TaxSummary[i].TaxCalculationLevel.ToCSTaxCalcLevel(),
                        TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount,
                        SalesTaxAcctID    = vendor.SalesTaxAcctID,
                        SalesTaxSubID     = vendor.SalesTaxSubID,
                        ExpenseAccountID  = vendor.TaxExpenseAcctID,
                        ExpenseSubID      = vendor.TaxExpenseSubID,
                        TaxVendorID       = taxZone.TaxVendorID,
                        IsExternal        = true
                    };

                    Base.Caches[typeof(Tax)].Insert(tx);
                }

                var tax = new ARTaxTran
                {
                    Module         = BatchModule.AR,
                    TranType       = invoice.DocType,
                    RefNbr         = invoice.RefNbr,
                    TaxID          = taxID,
                    CuryTaxAmt     = sign * result.TaxSummary[i].TaxAmount,
                    CuryTaxableAmt = sign * result.TaxSummary[i].TaxableAmount,
                    TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100,
                    JurisType      = result.TaxSummary[i].JurisType,
                    JurisName      = result.TaxSummary[i].JurisName,
                    TaxType        = CSTaxType.Sales,
                    TaxBucketID    = 0,
                    AccountID      = vendor.SalesTaxAcctID,
                    SubID          = vendor.SalesTaxSubID
                };

                Base.Taxes.Insert(tax);
            }

            bool requireControlTotal = Base.ARSetup.Current.RequireControlTotal == true;

            if (invoice.Hold != true)
            {
                Base.ARSetup.Current.RequireControlTotal = false;
            }

            try
            {
                invoice.CuryTaxTotal = sign * result.TotalTaxAmount;
                Base.Document.Cache.SetValueExt <ARInvoice.isTaxSaved>(invoice, true);
            }
            finally
            {
                Base.ARSetup.Current.RequireControlTotal = requireControlTotal;
            }

            if (invoice.ApplyPaymentWhenTaxAvailable == true)
            {
                PXSelectBase <ARAdjust2> select = new PXSelectJoin <ARAdjust2,
                                                                    InnerJoin <ARPayment, On <ARAdjust2.adjgDocType, Equal <ARPayment.docType>,
                                                                                              And <ARAdjust2.adjgRefNbr, Equal <ARPayment.refNbr> > > >,
                                                                    Where <ARAdjust2.adjdDocType, Equal <Required <ARInvoice.docType> >,
                                                                           And <ARAdjust2.adjdRefNbr, Equal <Required <ARInvoice.refNbr> > > > >(Base);

                decimal amountApplied = 0m;
                foreach (PXResult <ARAdjust2, ARPayment> res in select.Select(invoice.DocType, invoice.RefNbr))
                {
                    ARAdjust2 row     = (ARAdjust2)res;
                    ARPayment payment = (ARPayment)res;

                    ARAdjust2 copy = PXCache <ARAdjust2> .CreateCopy(row);

                    amountApplied += (copy.CuryAdjdAmt ?? 0m);

                    if (amountApplied > (invoice.CuryDocBal ?? 0m))
                    {
                        decimal newAdjdAmt = (copy.CuryAdjdAmt ?? 0m) - (amountApplied - (invoice.CuryDocBal ?? 0m));
                        copy.CuryAdjdAmt = newAdjdAmt > 0m ? newAdjdAmt : 0m;
                    }
                    Base.Adjustments.Update(copy);
                }
            }
        }
Exemple #23
0
        protected static void ApplyAvalaraTax(OpportunityMaint rg, CROpportunity order, GetTaxResult result)
        {
            var avalaraSetup = (TXAvalaraSetup)PXSetupOptional <TXAvalaraSetup> .Select(rg);

            TaxZone taxZone = (TaxZone)PXSetup <TaxZone, Where <TaxZone.taxZoneID, Equal <Required <CROpportunity.taxZoneID> > > > .Select(rg, order.TaxZoneID);

            AP.Vendor vendor = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(rg, taxZone.TaxVendorID);

            if (vendor == null)
            {
                throw new PXException(Messages.ExternalTaxVendorNotFound);
            }

            //Clear all existing Tax transactions:
            foreach (PXResult <CRTaxTran, Tax> res in rg.Taxes.View.SelectMultiBound(new object[] { order }))
            {
                CRTaxTran taxTran = (CRTaxTran)res;
                rg.Taxes.Delete(taxTran);
            }

            rg.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Count; i++)
            {
                string taxID = AvalaraMaint.GetTaxID(result.TaxSummary[i]);

                //Insert Tax if not exists - just for the selectors sake
                Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(rg, taxID);

                if (tx == null)
                {
                    tx       = new Tax();
                    tx.TaxID = taxID;
                    //tx.Descr = string.Format("Avalara {0} {1}%", taxID, Convert.ToDecimal(result.TaxSummary[i].Rate)*100);
                    tx.Descr             = PXMessages.LocalizeFormatNoPrefixNLA(TX.Messages.AvalaraTaxId, taxID);
                    tx.TaxType           = CSTaxType.Sales;
                    tx.TaxCalcType       = CSTaxCalcType.Doc;
                    tx.TaxCalcLevel      = avalaraSetup.IsInclusiveTax == true ? CSTaxCalcLevel.Inclusive : CSTaxCalcLevel.CalcOnItemAmt;
                    tx.TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount;
                    tx.SalesTaxAcctID    = vendor.SalesTaxAcctID;
                    tx.SalesTaxSubID     = vendor.SalesTaxSubID;
                    tx.ExpenseAccountID  = vendor.TaxExpenseAcctID;
                    tx.ExpenseSubID      = vendor.TaxExpenseSubID;
                    tx.TaxVendorID       = taxZone.TaxVendorID;
                    tx.IsExternal        = true;

                    rg.Caches[typeof(Tax)].Insert(tx);
                }

                CRTaxTran tax = new CRTaxTran();
                tax.OpportunityID  = order.OpportunityID;
                tax.TaxID          = taxID;
                tax.CuryTaxAmt     = Math.Abs(result.TaxSummary[i].Tax);
                tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
                tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100;

                rg.Taxes.Insert(tax);
            }

            rg.Opportunity.SetValueExt <CROpportunity.curyTaxTotal>(order, Math.Abs(result.TotalTax));

            try
            {
                rg.SkipAvalaraTaxProcessing = true;
                rg.Save.Press();
            }
            finally
            {
                rg.SkipAvalaraTaxProcessing = false;
            }
        }
		protected override void ApplyAvalaraTax(ARInvoice invoice, GetTaxResult result)
		{
			TaxZone taxZone = (TaxZone)taxzone.View.SelectSingleBound(new object[] { invoice });
			AP.Vendor vendor = PXSelect<AP.Vendor, Where<AP.Vendor.bAccountID, Equal<Required<AP.Vendor.bAccountID>>>>.Select(this, taxZone.TaxVendorID);

			if (vendor == null)
				throw new PXException("Tax Vendor is required but not found for the External TaxZone.");

			Dictionary<string, ARTaxTran> existingRows = new Dictionary<string, ARTaxTran>();
			foreach (PXResult<ARTaxTran, Tax> res in Taxes.View.SelectMultiBound(new object[] { invoice }))
			{
				ARTaxTran taxTran = (ARTaxTran)res;
				existingRows.Add(taxTran.TaxID.Trim().ToUpperInvariant(), taxTran);
			}

			this.Views.Caches.Add(typeof(Tax));

			bool requireControlTotal = ARSetup.Current.RequireControlTotal == true;

			if (invoice.Hold != true)
				ARSetup.Current.RequireControlTotal = false;

			try
			{

				for (int i = 0; i < result.TaxSummary.Count; i++)
				{
					string taxID = result.TaxSummary[i].TaxName.ToUpperInvariant();

					//Insert Tax if not exists - just for the selectors sake
					Tax tx = PXSelect<Tax, Where<Tax.taxID, Equal<Required<Tax.taxID>>>>.Select(this, taxID);
					if (tx == null)
					{
						tx = new Tax();
						tx.TaxID = taxID;
						//tx.Descr = string.Format("Avalara {0} {1}%", taxID, Convert.ToDecimal(result.TaxSummary[i].Rate)*100);
						tx.Descr = string.Format("Avalara {0}", taxID);
						tx.TaxType = CSTaxType.Sales;
						tx.TaxCalcType = CSTaxCalcType.Doc;
						tx.TaxCalcLevel = CSTaxCalcLevel.CalcOnItemAmt;
						tx.TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount;
						tx.SalesTaxAcctID = vendor.SalesTaxAcctID;
						tx.SalesTaxSubID = vendor.SalesTaxSubID;
						tx.ExpenseAccountID = vendor.TaxExpenseAcctID;
						tx.ExpenseSubID = vendor.TaxExpenseSubID;
						tx.TaxVendorID = taxZone.TaxVendorID;

						this.Caches[typeof(Tax)].Insert(tx);
					}

					ARTaxTran existing = null;
					existingRows.TryGetValue(taxID, out existing);

					if (existing != null)
					{
						existing.TaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						existing.CuryTaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						existing.TaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						existing.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						existing.TaxRate = Convert.ToDecimal(result.TaxSummary[i].Rate);

						Taxes.Update(existing);
						existingRows.Remove(existing.TaxID.Trim().ToUpperInvariant());
					}
					else
					{
						ARTaxTran tax = new ARTaxTran();
						tax.Module = BatchModule.AR;
						tax.TranType = invoice.DocType;
						tax.RefNbr = invoice.RefNbr;
						tax.TaxID = taxID;
						tax.TaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						tax.CuryTaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						tax.TaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						tax.TaxRate = Convert.ToDecimal(result.TaxSummary[i].Rate);
						tax.TaxType = "S";
						tax.TaxBucketID = 0;
						tax.AccountID = vendor.SalesTaxAcctID;
						tax.SubID = vendor.SalesTaxSubID;

						Taxes.Insert(tax);
					}
				}

				foreach (ARTaxTran taxTran in existingRows.Values)
				{
					Taxes.Delete(taxTran);
				}

				SOInvoice soInvoice = PXSelect<SOInvoice, Where<SOInvoice.docType, Equal<Required<SOInvoice.docType>>, And<SOInvoice.refNbr, Equal<Required<SOInvoice.refNbr>>>>>.Select(this, invoice.DocType, invoice.RefNbr);

				invoice.CuryTaxTotal = Math.Abs(result.TotalTax);
				Document.Cache.SetValueExt<ARInvoice.isTaxSaved>(invoice, true);
			}
			finally
			{
				ARSetup.Current.RequireControlTotal = requireControlTotal;
			}


			if (invoice.ApplyPaymentWhenTaxAvailable == true)
			{
				PXSelectBase<ARAdjust> select = new PXSelectJoin<ARAdjust,
					InnerJoin<ARPayment, On<ARAdjust.adjgDocType, Equal<ARPayment.docType>, And<ARAdjust.adjgRefNbr, Equal<ARPayment.refNbr>>>>,
					Where<ARAdjust.adjdDocType, Equal<Required<ARInvoice.docType>>,
					And<ARAdjust.adjdRefNbr, Equal<Required<ARInvoice.refNbr>>>>>(this);


				foreach (PXResult<ARAdjust, ARPayment> res in select.Select(invoice.DocType, invoice.RefNbr))
				{
					ARAdjust row = (ARAdjust)res;
					ARPayment payment = (ARPayment)res;

					ARAdjust copy = PXCache<ARAdjust>.CreateCopy(row);
					copy.CuryAdjdAmt = Math.Min(copy.CuryAdjdAmt.GetValueOrDefault(), invoice.CuryDocBal.GetValueOrDefault());
					Adjustments.Update(copy);
				}
			}

		}
        protected void ApplyTax(PMQuote quote, GetTaxResult result)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;

            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)PXSetup <TaxZone, Where <TaxZone.taxZoneID, Equal <Required <PMQuote.taxZoneID> > > > .Select(Base, quote.TaxZoneID);

                vendor = (VendorMaster)PXSelectReadonly <VendorMaster, Where <VendorMaster.bAccountID, Equal <Required <VendorMaster.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(CR.Messages.ExternalTaxVendorNotFound);
                }
            }

            //Clear all existing Tax transactions:
            foreach (PXResult <CRTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { quote }))
            {
                CRTaxTran taxTran = (CRTaxTran)res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = GetTaxID(result.TaxSummary[i]);

                //Insert Tax if not exists - just for the selectors sake
                Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(Base, taxID);

                if (tx == null)
                {
                    tx                   = new Tax();
                    tx.TaxID             = taxID;
                    tx.Descr             = PXMessages.LocalizeFormatNoPrefixNLA(TX.Messages.ExternalTaxProviderTaxId, taxID);
                    tx.TaxType           = CSTaxType.Sales;
                    tx.TaxCalcType       = CSTaxCalcType.Doc;
                    tx.TaxCalcLevel      = result.TaxSummary[i].TaxCalculationLevel.ToCSTaxCalcLevel();
                    tx.TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount;
                    tx.SalesTaxAcctID    = vendor.SalesTaxAcctID;
                    tx.SalesTaxSubID     = vendor.SalesTaxSubID;
                    tx.ExpenseAccountID  = vendor.TaxExpenseAcctID;
                    tx.ExpenseSubID      = vendor.TaxExpenseSubID;
                    tx.TaxVendorID       = taxZone.TaxVendorID;
                    tx.IsExternal        = true;

                    Base.Caches[typeof(Tax)].Insert(tx);
                }

                CRTaxTran tax = new CRTaxTran();
                tax.QuoteID        = quote.QuoteID;
                tax.TaxID          = taxID;
                tax.CuryTaxAmt     = result.TaxSummary[i].TaxAmount;
                tax.CuryTaxableAmt = result.TaxSummary[i].TaxableAmount;
                tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100;

                Base.Taxes.Insert(tax);
            }

            Base.Quote.SetValueExt <PMQuote.curyTaxTotal>(quote, result.TotalTaxAmount);

            decimal?СuryProductsAmount =
                quote.ManualTotalEntry == true
                                ? quote.CuryAmount - quote.CuryDiscTot
                                : quote.CuryLineTotal - quote.CuryDiscTot + quote.CuryTaxTotal;

            Base.Quote.SetValueExt <PMQuote.curyProductsAmount>(quote, СuryProductsAmount ?? 0m);
        }
Exemple #26
0
        public void IssueRefund(Order order, Address originAddress, decimal refundTotal)
        {
            if (!Enabled)
            {
                throw new InvalidOperationException("AvalaraInactiveException");
            }

            var customer     = new Customer(order.CustomerID);
            var cartItems    = order.CartItems;
            var orderOptions = GetOrderOptions(order);
            int numberOfRefundTransactions = (order.ChildOrderNumbers ?? String.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length;

            decimal discountAmount = -cartItems.DiscountResults.Sum(dr => dr.OrderTotal);               // This value is returned as negative, but Avalara expectes a positive

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

            taxRequest.Discount = discountAmount;
            taxRequest.DocCode  = order.OrderNumber.ToString() + "." + (numberOfRefundTransactions + 1).ToString();
            taxRequest.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
            taxRequest.TaxOverride.TaxDate         = order.OrderDate;
            taxRequest.TaxOverride.Reason          = "Refund";
            taxRequest.DocDate = DateTime.Now;
            taxRequest.Commit  = CommitRefunds;

            if (refundTotal > 0)
            {
                // Partial refund
                // Add in the refund line object
                Line refundLineItem = new Line
                {
                    Amount  = -refundTotal,
                    Qty     = 1,
                    No      = "1",
                    TaxCode = TaxRefunds ? null : "NT"                     // Make this refund non-taxable as recommended by Avalara
                };

                taxRequest.Lines.Add(refundLineItem);
            }
            else
            {
                // Refund the full order
                // Void any partial refunds
                VoidRefunds(order);

                // Add order items to the refund transaction
                // 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));

                // Add each line to the request, setting the line number sequentially
                int lineItemIndex = 0;
                foreach (var line in lineItems)
                {
                    line.Amount = -line.Amount;
                    line.No     = (++lineItemIndex).ToString();
                    taxRequest.Lines.Add(line);
                }
            }

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

            foreach (Message message in taxResult.Messages)
            {
                LogErrorMessage(message);
            }
        }
        protected void ApplyTax(FSServiceOrder order, GetTaxResult result)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;

            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)PXSetup <TaxZone, Where <TaxZone.taxZoneID, Equal <Required <FSServiceOrder.taxZoneID> > > > .Select(Base, order.TaxZoneID);

                vendor = (AP.Vendor) PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(PX.Objects.CR.Messages.ExternalTaxVendorNotFound);
                }
            }

            //Clear all existing Tax transactions:
            foreach (PXResult <FSServiceOrderTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { order }))
            {
                FSServiceOrderTaxTran taxTran = (FSServiceOrderTaxTran)res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = GetTaxID(result.TaxSummary[i]);

                //Insert Tax if not exists - just for the selectors sake
                Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(Base, taxID);

                if (tx == null)
                {
                    tx                   = new Tax();
                    tx.TaxID             = taxID;
                    tx.Descr             = PXMessages.LocalizeFormatNoPrefixNLA(PX.Objects.TX.Messages.ExternalTaxProviderTaxId, taxID);
                    tx.TaxType           = CSTaxType.Sales;
                    tx.TaxCalcType       = CSTaxCalcType.Doc;
                    tx.TaxCalcLevel      = result.TaxSummary[i].TaxCalculationLevel.ToCSTaxCalcLevel();
                    tx.TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount;
                    tx.SalesTaxAcctID    = vendor.SalesTaxAcctID;
                    tx.SalesTaxSubID     = vendor.SalesTaxSubID;
                    tx.ExpenseAccountID  = vendor.TaxExpenseAcctID;
                    tx.ExpenseSubID      = vendor.TaxExpenseSubID;
                    tx.TaxVendorID       = taxZone.TaxVendorID;
                    tx.IsExternal        = true;

                    Base.Caches[typeof(Tax)].Insert(tx);
                }

                FSServiceOrderTaxTran tax = new FSServiceOrderTaxTran();
                tax.EntityType     = ID.PostDoc_EntityType.SERVICE_ORDER;
                tax.EntityID       = order.SOID;
                tax.TaxID          = taxID;
                tax.CuryTaxAmt     = Math.Abs(result.TaxSummary[i].TaxAmount);
                tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].TaxableAmount);
                tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100;

                Base.Taxes.Insert(tax);
            }

            Base.CurrentServiceOrder.SetValueExt <FSServiceOrder.curyTaxTotal>(order, Math.Abs(result.TotalTaxAmount));

            decimal?СuryDocTotal = ServiceOrderEntry.GetCuryDocTotal(order.CuryBillableOrderTotal, order.CuryDiscTot, order.CuryTaxTotal, 0);

            Base.CurrentServiceOrder.SetValueExt <FSServiceOrder.curyDocTotal>(order, СuryDocTotal ?? 0m);
        }
        protected virtual void ApplyTax(POOrder order, GetTaxResult result, GetTaxResult resultUnbilled)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;
            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)Base.taxzone.View.SelectSingleBound(new object[] { order });
                vendor  = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(Messages.ExternalTaxVendorNotFound);
                }
            }
            //Clear all existing Tax transactions:
            foreach (PXResult <POTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { order }))
            {
                POTaxTran taxTran = (POTaxTran)res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = result.TaxSummary[i].TaxName;
                if (string.IsNullOrEmpty(taxID))
                {
                    taxID = result.TaxSummary[i].JurisCode;
                }

                if (string.IsNullOrEmpty(taxID))
                {
                    PXTrace.WriteInformation(Messages.EmptyValuesFromExternalTaxProvider);
                    continue;
                }

                CreateTax(Base, taxZone, vendor, result.TaxSummary[i], taxID);

                POTaxTran tax = new POTaxTran();
                tax.OrderType      = order.OrderType;
                tax.OrderNbr       = order.OrderNbr;
                tax.TaxID          = taxID;
                tax.CuryTaxAmt     = Math.Abs(result.TaxSummary[i].TaxAmount);
                tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].TaxableAmount);
                tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100;
                tax.JurisType      = result.TaxSummary[i].JurisType;
                tax.JurisName      = result.TaxSummary[i].JurisName;

                Base.Taxes.Insert(tax);
            }

            bool requireBlanketControlTotal  = Base.POSetup.Current.RequireBlanketControlTotal == true;
            bool requireDropShipControlTotal = Base.POSetup.Current.RequireDropShipControlTotal == true;
            bool requireOrderControlTotal    = Base.POSetup.Current.RequireOrderControlTotal == true;

            if (order.Hold != true)
            {
                Base.POSetup.Current.RequireBlanketControlTotal  = false;
                Base.POSetup.Current.RequireDropShipControlTotal = false;
                Base.POSetup.Current.RequireOrderControlTotal    = false;
            }

            try
            {
                Base.Document.SetValueExt <POOrder.curyTaxTotal>(order, Math.Abs(result.TotalTaxAmount));
                if (resultUnbilled != null)
                {
                    Base.Document.SetValueExt <POOrder.curyUnbilledTaxTotal>(order, Math.Abs(resultUnbilled.TotalTaxAmount));
                }
                Base.Document.Update(order);
            }
            finally
            {
                Base.POSetup.Current.RequireBlanketControlTotal  = requireBlanketControlTotal;
                Base.POSetup.Current.RequireDropShipControlTotal = requireDropShipControlTotal;
                Base.POSetup.Current.RequireOrderControlTotal    = requireOrderControlTotal;
            }

            SkipTaxCalcAndSave();
        }
        protected virtual void ApplyTax(ARCashSale invoice, GetTaxResult result)
        {
            TaxZone taxZone = null;

            AP.Vendor vendor = null;
            if (result.TaxSummary.Length > 0)
            {
                taxZone = (TaxZone)Base.taxzone.View.SelectSingleBound(new object[] { invoice });
                vendor  = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID);

                if (vendor == null)
                {
                    throw new PXException(TX.Messages.ExternalTaxVendorNotFound);
                }

                if (vendor.SalesTaxAcctID == null)
                {
                    throw new PXException(TX.Messages.TaxPayableAccountNotSpecified, vendor.AcctCD);
                }

                if (vendor.SalesTaxSubID == null)
                {
                    throw new PXException(TX.Messages.TaxPayableSubNotSpecified, vendor.AcctCD);
                }
            }
            //Clear all existing Tax transactions:
            foreach (PXResult <ARTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { invoice }))
            {
                ARTaxTran taxTran = (ARTaxTran)res;
                Base.Taxes.Delete(taxTran);
            }

            Base.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Length; i++)
            {
                string taxID = result.TaxSummary[i].TaxName;
                if (string.IsNullOrEmpty(taxID))
                {
                    taxID = result.TaxSummary[i].JurisCode;
                }

                if (string.IsNullOrEmpty(taxID))
                {
                    PXTrace.WriteInformation(Messages.EmptyValuesFromExternalTaxProvider);
                    continue;
                }

                CreateTax(Base, taxZone, vendor, result.TaxSummary[i], taxID);

                ARTaxTran tax = new ARTaxTran();
                tax.Module         = BatchModule.AR;
                tax.TranType       = invoice.DocType;
                tax.RefNbr         = invoice.RefNbr;
                tax.TaxID          = taxID;
                tax.CuryTaxAmt     = Math.Abs(result.TaxSummary[i].TaxAmount);
                tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].TaxableAmount);
                tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100;
                tax.TaxType        = "S";
                tax.TaxBucketID    = 0;
                tax.AccountID      = vendor.SalesTaxAcctID;
                tax.SubID          = vendor.SalesTaxSubID;
                tax.JurisType      = result.TaxSummary[i].JurisType;
                tax.JurisName      = result.TaxSummary[i].JurisName;

                Base.Taxes.Insert(tax);
            }

            bool requireControlTotal = Base.arsetup.Current.RequireControlTotal == true;

            if (invoice.Hold != true)
            {
                Base.arsetup.Current.RequireControlTotal = false;
            }


            try
            {
                invoice.CuryTaxTotal = Math.Abs(result.TotalTaxAmount);
                Base.Document.Cache.SetValueExt <ARCashSale.isTaxSaved>(invoice, true);
            }
            finally
            {
                Base.arsetup.Current.RequireControlTotal = requireControlTotal;
            }
        }
Exemple #30
0
        public decimal GetTaxRate(Customer customer, CartItemCollection cartItems, IEnumerable <OrderOption> orderOptions)
        {
            if (!Enabled)
            {
                throw new InvalidOperationException("AvalaraInactiveException");
            }

            if (!customer.HasAtLeastOneAddress() || !cartItems.Any())
            {
                return(0m);
            }

            // Return the cached value if it's present and still valid
            string  lastCartHash    = HttpContext.Current.Items["Avalara.CartHash"] as string;
            decimal?lastTaxAmount   = HttpContext.Current.Items["Avalara.TaxAmount"] as decimal?;
            string  currentCartHash = GetCartHash(cartItems, customer, orderOptions);

            if (lastTaxAmount != null && currentCartHash == lastCartHash)
            {
                return(lastTaxAmount.Value);
            }

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

            // 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));

            decimal discountAmount = -cartItems.DiscountResults.Sum(dr => dr.OrderTotal);               // This value is returned as negative, but Avalara expectes a positive

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

            taxRequest.Discount = discountAmount;

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

            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);
            }

            decimal taxAmount = taxResult.TotalTax;

            // Cache the tax amount
            HttpContext.Current.Items["Avalara.CartHash"]  = currentCartHash;
            HttpContext.Current.Items["Avalara.TaxAmount"] = taxAmount;

            return(taxAmount);
        }
        protected static void ApplyAvalaraTax(OpportunityMaint rg, CROpportunity order, GetTaxResult result)
        {
            var avalaraSetup = (TXAvalaraSetup)PXSetupOptional <TXAvalaraSetup> .Select(rg);

            TaxZone taxZone = (TaxZone)PXSetup <TaxZone, Where <TaxZone.taxZoneID, Equal <Required <CROpportunity.taxZoneID> > > > .Select(rg, order.TaxZoneID);

            AP.Vendor vendor = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(rg, taxZone.TaxVendorID);

            if (vendor == null)
            {
                throw new PXException("Tax Vendor is required but not found for the External TaxZone.");
            }

            Dictionary <string, CRTaxTran> existingRows = new Dictionary <string, CRTaxTran>();

            foreach (PXResult <CRTaxTran, Tax> res in rg.Taxes.View.SelectMultiBound(new object[] { order }))
            {
                CRTaxTran taxTran = (CRTaxTran)res;
                existingRows.Add(taxTran.TaxID.Trim().ToUpperInvariant(), taxTran);
            }

            rg.Views.Caches.Add(typeof(Tax));

            for (int i = 0; i < result.TaxSummary.Count; i++)
            {
                string taxID = result.TaxSummary[i].TaxName.ToUpperInvariant();

                //Insert Tax if not exists - just for the selectors sake
                Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(rg, taxID);

                if (tx == null)
                {
                    tx       = new Tax();
                    tx.TaxID = taxID;
                    //tx.Descr = string.Format("Avalara {0} {1}%", taxID, Convert.ToDecimal(result.TaxSummary[i].Rate)*100);
                    tx.Descr             = string.Format("Avalara {0}", taxID);
                    tx.TaxType           = CSTaxType.Sales;
                    tx.TaxCalcType       = CSTaxCalcType.Doc;
                    tx.TaxCalcLevel      = avalaraSetup.IsInclusiveTax == true ? CSTaxCalcLevel.Inclusive : CSTaxCalcLevel.CalcOnItemAmt;
                    tx.TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount;
                    tx.SalesTaxAcctID    = vendor.SalesTaxAcctID;
                    tx.SalesTaxSubID     = vendor.SalesTaxSubID;
                    tx.ExpenseAccountID  = vendor.TaxExpenseAcctID;
                    tx.ExpenseSubID      = vendor.TaxExpenseSubID;
                    tx.TaxVendorID       = taxZone.TaxVendorID;

                    rg.Caches[typeof(Tax)].Insert(tx);
                }

                CRTaxTran existing = null;
                existingRows.TryGetValue(taxID, out existing);

                if (existing != null)
                {
                    existing.TaxAmt         = Math.Abs(result.TaxSummary[i].Tax);
                    existing.CuryTaxAmt     = Math.Abs(result.TaxSummary[i].Tax);
                    existing.TaxableAmt     = Math.Abs(result.TaxSummary[i].Taxable);
                    existing.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
                    existing.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate);

                    rg.Taxes.Update(existing);
                    existingRows.Remove(existing.TaxID.Trim().ToUpperInvariant());
                }
                else
                {
                    CRTaxTran tax = new CRTaxTran();
                    tax.OpportunityID  = order.OpportunityID;
                    tax.TaxID          = taxID;
                    tax.TaxAmt         = Math.Abs(result.TaxSummary[i].Tax);
                    tax.CuryTaxAmt     = Math.Abs(result.TaxSummary[i].Tax);
                    tax.TaxableAmt     = Math.Abs(result.TaxSummary[i].Taxable);
                    tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
                    tax.TaxRate        = Convert.ToDecimal(result.TaxSummary[i].Rate);

                    rg.Taxes.Insert(tax);
                }
            }

            foreach (CRTaxTran taxTran in existingRows.Values)
            {
                rg.Taxes.Delete(taxTran);
            }

            rg.Opportunity.SetValueExt <CROpportunity.curyTaxTotal>(order, Math.Abs(result.TotalTax));

            try
            {
                rg.SkipAvalaraTaxProcessing = true;
                rg.Save.Press();
            }
            finally
            {
                rg.SkipAvalaraTaxProcessing = false;
            }
        }