Esempio n. 1
0
        public StandardJsonResult CalculateTax(decimal subtotal, string countryCode, int?regionId, int?taxClassId)
        {
            var taxResult = new
            {
                taxRate   = 0m,
                taxAmount = 0m,
                taxName   = "Tax"
            };

            TaxZone taxZone = taxZoneService.Find(countryCode, regionId);

            //TODO: Tax class should be calculated per product
            if (taxZone != null)
            {
                TaxRate taxRate = db.TaxRates.FirstOrDefault(r => r.TaxZoneId == taxZone.Id);
                if (taxRate != null)
                {
                    TaxClassRate taxClassRate =
                        db.TaxClassRates.FirstOrDefault(r => r.TaxRateId == taxRate.Id && r.TaxClassId == taxClassId);

                    decimal rate = taxClassRate != null ? taxClassRate.Amount : taxRate.Amount;
                    taxResult = new
                    {
                        taxRate   = rate,
                        taxAmount = (subtotal * rate) / 100m,
                        taxName   = taxRate.Name
                    };
                }
            }

            return(JsonSuccess(taxResult));
        }
        public static decimal CalcResidualAmt(PXCache cache, object row, string aTaxZoneID, string aTaxCategoryID, DateTime aDocDate,
                                              string TaxCalcMode, decimal ControlTotalAmt, decimal LinesTotal, decimal TaxTotal)
        {
            decimal taxableAmount = 0.0m;
            TaxZone zone          = PXSelect <TaxZone, Where <TaxZone.taxZoneID, Equal <Required <TaxZone.taxZoneID> > > > .SelectWindowed(cache.Graph, 0, 1, aTaxZoneID);

            if (PXAccess.FeatureInstalled <FeaturesSet.manualVATEntryMode>() && zone != null && zone.IsManualVATZone == true)
            {
                taxableAmount = ControlTotalAmt - LinesTotal - TaxTotal;
            }
            else
            {
                switch (TaxCalcMode)
                {
                case TaxCalculationMode.Gross:
                    taxableAmount = TaxAttribute.CalcTaxableFromTotalAmount(cache, row, aTaxZoneID,
                                                                            aTaxCategoryID, aDocDate, ControlTotalAmt - LinesTotal, false, TaxAttribute.TaxCalcLevelEnforcing.EnforceInclusive);
                    break;

                case TaxCalculationMode.Net:
                    taxableAmount = TaxAttribute.CalcTaxableFromTotalAmount(cache, row, aTaxZoneID,
                                                                            aTaxCategoryID, aDocDate, ControlTotalAmt - LinesTotal - TaxTotal, false, TaxAttribute.TaxCalcLevelEnforcing.EnforceCalcOnItemAmount);
                    break;

                case TaxCalculationMode.TaxSetting:
                    //disabled for now
                    //taxableAmount = TaxAttribute.CalcTaxableFromTotalAmount(cache, row, aTaxZoneID,
                    //	aTaxCategoryID, aDocDate, ControlTotalAmt - LinesTotal, false, GLTaxAttribute.TaxCalcLevelEnforcing.None);
                    break;
                }
            }
            return(taxableAmount);
        }
Esempio n. 3
0
        public ActionResult Delete(int[] ids)
        {
            if (ids == null || !ids.Any())
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var model = new TaxZonesDeleteViewModel();

            model.TaxZones = new List <TaxZoneDeleteViewModel>();

            foreach (int id in ids)
            {
                TaxZone taxZone = taxZoneService.Find(id);
                if (taxZone == null)
                {
                    continue;
                }

                model.TaxZones.Add(new TaxZoneDeleteViewModel
                {
                    Id   = taxZone.Id,
                    Name = taxZone.Name,
                });
            }
            return(View(model));
        }
Esempio n. 4
0
        public decimal CalculateTax(string countryCode, int?regionId, int?taxClassId, decimal price)
        {
            TaxZone taxZone = taxZoneService.Find(countryCode, regionId);

            if (taxZone == null)
            {
                return(0m);
            }

            return(taxRateService.CalculateTax(taxZone.Id, taxClassId, price));
        }
Esempio n. 5
0
        public void Delete(int id)
        {
            TaxZone taxZone  = Find(id);
            var     taxRates = taxRateService.FindByZone(id).ToList();

            foreach (var taxRate in taxRates)
            {
                taxRateService.Delete(taxRate.Id);
            }
            db.TaxZones.Remove(taxZone);
            db.SaveChanges();
        }
        public override void Persist()
        {
            if (SiteMaster.Current != null)
            {
                object devConfirmPassword = SiteMaster.Current.DevConfirmPassword;
                SiteMaster.Cache.RaiseFieldVerifying <KCSiteMaster.devConfirmPassword>(SiteMaster.Current, ref devConfirmPassword);

                object ftpConfirmPassword = SiteMaster.Current.FTPConfirmPassword;
                SiteMaster.Cache.RaiseFieldVerifying <KCSiteMaster.fTPConfirmPassword>(SiteMaster.Current, ref ftpConfirmPassword);


                KCSiteMaster siteExists = PXSelectReadonly <KCSiteMaster, Where <KCSiteMaster.accountId, Equal <Required <KCSiteMaster.accountId> >, And <KCSiteMaster.siteMasterCD, NotEqual <Required <KCSiteMaster.siteMasterCD> > > > > .Select(this, SiteMaster.Current.AccountId, SiteMaster.Current.SiteMasterCD);

                if (siteExists != null)
                {
                    string msg = KCMessages.AlreadyExistAccountId;
                    SiteMaster.Cache.RaiseExceptionHandling <KCSiteMaster.accountId>(SiteMaster.Current, SiteMaster.Current.AccountId, new PXSetPropertyException <KCSiteMaster.accountId>(msg));
                    throw new PXSetPropertyException <KCSiteMaster.accountId>(msg);
                }
            }
            var           isCATaxZoneExist = TaxZoneId.SelectSingle(KCConstants.Channel);
            var           isCATaxExist     = TaxId.SelectSingle(KCConstants.ChannelAdvisor);
            SalesTaxMaint stax             = PXGraph.CreateInstance <SalesTaxMaint>();
            TaxZoneMaint  CAtaxzone        = PXGraph.CreateInstance <TaxZoneMaint>();
            Tax           tax        = stax.Tax.Insert();
            TaxZone       newTaxZone = CAtaxzone.TxZone.Insert();
            TaxZoneDet    taxZoneDet = CAtaxzone.TxZoneDet.Insert();

            if (isCATaxExist == null)
            {
                stax.Tax.Cache.SetValue <Tax.taxID>(tax, KCConstants.ChannelAdvisor);
                stax.Tax.Cache.SetValue <Tax.descr>(tax, KCConstants.ChannelAdvisor);
                stax.Tax.Cache.SetValue <Tax.salesTaxAcctID>(tax, KCConstants.salesTaxAcctID);
                stax.Tax.Cache.SetValue <Tax.salesTaxSubID>(tax, KCConstants.salesTaxSubID);
                stax.Tax.Cache.SetValue <Tax.taxCalcType>(tax, KCConstants.taxCalcType);
                stax.Tax.Cache.SetValue <Tax.taxCalcLevel>(tax, KCConstants.taxCalcLevel);
                stax.Persist();
            }
            if (isCATaxZoneExist == null)
            {
                CAtaxzone.TxZone.Cache.SetValue <TaxZone.taxZoneID>(newTaxZone, KCConstants.Channel);
                CAtaxzone.TxZone.Cache.SetValue <TaxZone.descr>(newTaxZone, KCConstants.Channel);
                CAtaxzone.TxZone.Cache.SetValue <TaxZone.dfltTaxCategoryID>(newTaxZone, KCConstants.Taxable);
                CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxZoneID>(taxZoneDet, newTaxZone.TaxZoneID);
                CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxID>(taxZoneDet, KCConstants.ChannelAdvisor);
                CAtaxzone.Persist();
            }
            base.Persist();
        }
        protected virtual void POLandedCostDoc_CuryDiscTot_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            bool    calc    = true;
            TaxZone taxZone = PXSelect <TaxZone, Where <TaxZone.taxZoneID, Equal <Required <TaxZone.taxZoneID> > > > .Select(sender.Graph, (string)sender.GetValue(e.Row, _TaxZoneID));

            if (taxZone != null && taxZone.IsExternal == true)
            {
                calc = false;
            }

            this._ParentRow = e.Row;
            if (!(_TaxCalc == TaxCalc.ManualLineCalc && totals.Any()))
            {
                CalcTotals(sender, e.Row, calc);
            }
            this._ParentRow = null;
        }
Esempio n. 8
0
        public TaxZone Find(string countryCode, int?regionId)
        {
            TaxZone taxZone = null;
            var     zones   = FindAll();

            if (regionId.HasValue)
            {
                taxZone = zones.FirstOrDefault(z =>
                                               z.IsActive && z.Countries.Any(c => c.Code == countryCode) && z.Regions.Any(r => r.Id == regionId));
            }
            if (taxZone == null)
            {
                taxZone = zones.FirstOrDefault(z =>
                                               z.IsActive && z.Countries.Any(c => c.Code == countryCode) && !z.Regions.Any());
            }
            if (taxZone == null)
            {
                taxZone = zones.FirstOrDefault(z =>
                                               z.IsActive && !z.Countries.Any() && !z.Regions.Any());
            }

            return(taxZone);
        }
Esempio n. 9
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            TaxZone taxZone = taxZoneService.Find(id.Value);

            if (taxZone == null)
            {
                return(HttpNotFound());
            }
            var model = Mapper.Map <TaxZoneEditViewModel>(taxZone);

            string[] countryCodes = taxZone.Countries.Select(c => c.Code).ToArray();
            model.CountryCodesJson = JsonConvert.SerializeObject(countryCodes);

            int[] regionIds = taxZone.Regions.Select(r => r.Id).ToArray();
            model.RegionIdsJson = JsonConvert.SerializeObject(regionIds);

            ViewBag.Countries = countryService.FindAll().Where(c => c.IsActive || countryCodes.Contains(c.Code)).ToList();
            return(View(model));
        }
        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();
        }
        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);
                }
            }
        }
Esempio n. 12
0
        public ActionResult Checkout(ShoppingCartCheckoutViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(JsonValidationError());
            }

            // Get cart contents
            ShoppingCart cart = GetOrCreateCart();

            if (!cart.ShoppingCartItems.Any())
            {
                return(JsonError("Your shopping cart is empty!"));
            }

            // Check quantity
            foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems)
            {
                Product product = db.Products.Find(cartItem.ProductId);
                int?    qty     = null;
                if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Quantity.HasValue)
                {
                    qty = cartItem.ProductSku.Quantity.Value;
                }
                if (qty == null && product.Quantity.HasValue)
                {
                    qty = product.Quantity.Value;
                }
                if (qty.HasValue && qty < cartItem.Quantity)
                {
                    return(JsonError(string.Format("The requested quantity for \"{0}\" is not available", product.Name)));
                }
            }

            // Get current user (or create a new one)
            User user = null;

            if (User.Identity.IsAuthenticated)
            {
                user = customerService.Find(currentUser.User.Id);
            }
            if (user == null)
            {
                var userModel = new CustomerViewModel
                {
                    FirstName   = model.BillingAddress.FirstName,
                    LastName    = model.BillingAddress.LastName,
                    Company     = model.BillingAddress.Company,
                    PhoneNumber = model.BillingAddress.Phone,
                    Email       = model.Email
                };
                try
                {
                    user = customerService.AddOrUpdate(userModel);
                }
                catch (ArgumentException err)
                {
                    return(JsonError(err.Message));
                }

                customerService.LoginUser(HttpContext, user);
            }

            // Get addresses
            var billingAddress = Mapper.Map <Address>(model.BillingAddress);

            billingAddress.Type = AddressType.Billing;

            var shippingAddress = Mapper.Map <Address>(model.SameShippingAddress
                ? model.BillingAddress
                : model.ShippingAddress);

            shippingAddress.Type = AddressType.Shipping;

            var defaultBillingAddress = customerService.GetAddress(user.Id, AddressType.Billing);

            if (defaultBillingAddress == null)
            {
                // Add default billing address
                defaultBillingAddress           = Mapper.Map <Address>(model.BillingAddress);
                defaultBillingAddress.Type      = AddressType.Billing;
                defaultBillingAddress.IsPrimary = true;
                user.Addresses.Add(defaultBillingAddress);
            }

            var defaultShippingAddress = customerService.GetAddress(user.Id, AddressType.Shipping);

            if (defaultShippingAddress == null)
            {
                // Add default shipping address
                defaultShippingAddress = Mapper.Map <Address>(model.SameShippingAddress
                    ? model.BillingAddress
                    : model.ShippingAddress);
                defaultShippingAddress.Type      = AddressType.Shipping;
                defaultShippingAddress.IsPrimary = true;
                user.Addresses.Add(defaultShippingAddress);
            }

            db.SaveChanges();

            // Create order
            var order = new Order
            {
                UserId          = user.Id,
                BillingAddress  = billingAddress,
                ShippingAddress = shippingAddress,
                DatePlaced      = DateTime.Now,
                DateUpdated     = DateTime.Now,
                IPAddress       = Request.UserHostAddress,
                UserComments    = model.UserComments,
                Status          = OrderStatus.AwaitingPayment
            };

            db.Orders.Add(order);

            TaxZone taxZone = taxZoneService.Find(billingAddress.CountryCode, billingAddress.RegionId);

            foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems)
            {
                Product    product    = db.Products.Find(cartItem.ProductId);
                ProductSku productSku = cartItem.ProductSku;

                if (productSku != null && productSku.Quantity.HasValue)
                {
                    productSkuService.RemoveQuantity(productSku.Id, cartItem.Quantity);
                }
                else if (product.Quantity.HasValue)
                {
                    productService.RemoveQuantity(product.Id, cartItem.Quantity);
                }

                decimal price = product.SalePrice ?? product.Price;
                if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Price.HasValue)
                {
                    price = cartItem.ProductSku.Price.Value;
                }

                var cartItemOptions  = JsonConvert.DeserializeObject <ShoppingCartItemOptionViewModel[]>(cartItem.Options);
                var orderItemOptions = Mapper.Map <OrderItemOption[]>(cartItemOptions);

                var orderItem = new OrderItem
                {
                    Order        = order,
                    ProductId    = product.Id,
                    ProductSkuId = cartItem.ProductSkuId,
                    Quantity     = cartItem.Quantity,
                    Options      = JsonConvert.SerializeObject(orderItemOptions),
                    ItemPrice    = price
                };

                db.OrderItems.Add(orderItem);

                order.Subtotal += cartItem.Quantity * price;

                if (taxZone != null)
                {
                    order.TaxAmount += taxRateService.CalculateTax(taxZone.Id, product.TaxClassId, price * cartItem.Quantity);
                }
            }

            ShippingMethod shippingMethod = db.ShippingMethods.Find(model.ShippingMethodId);

            order.ShippingAmount = shippingService.CalculateShipping(shippingMethod,
                                                                     cart.ShoppingCartItems.Sum(i => i.Quantity),
                                                                     cart.ShoppingCartItems.Sum(i => i.Quantity * i.Product.Weight),
                                                                     order.Subtotal, shippingAddress).GetValueOrDefault();

            order.Total = order.Subtotal + order.ShippingAmount;
            if (!settings.Get <bool>(SettingField.TaxIncludedInPrices))
            {
                order.Total += order.TaxAmount;
            }

            db.SaveChanges();

            return(JsonSuccess(new { orderId = order.Id, paymentMethodId = model.PaymentMethodId }));
        }
        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 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;
            }
        }
        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;
            }
        }
Esempio n. 16
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("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;
            }
        }
        public string GetTaxSettings(KCAPIOrder order, SOOrderEntry orderEntry)
        {
            //string marketplaceName = order.SiteName;
            string marketplaceName = order.BillingFirstName.Split()[0];
            var    orderExt        = orderEntry.GetExtension <KCSOOrderEntryExt>();
            PXResultset <KCTaxManagement> taxManagement = null;
            KCTaxManagement taxrecord     = null;
            int?            marketplaceId = orderExt.KCMarketplaceEntity.SelectSingle(marketplaceName)?.MarketplaceId;

            if (marketplaceId == null)
            {
                marketplaceName = order.SiteName;
                marketplaceId   = orderExt.KCMarketplaceEntity.SelectSingle(marketplaceName)?.MarketplaceId;
            }
            var marketplace      = orderExt.KCMarketplaceManagement.SelectSingle(marketplaceId.ToString());
            var isCATaxZoneExist = orderExt.KCTaxZoneId.SelectSingle(KCConstants.Channel);

            Boolean.TryParse(orderExt.KCXSiteMaster.SelectSingle().IsImportTax, out bool IsImport);
            if (marketplace != null)
            {
                taxManagement = orderExt.KCTaxManagementView.Select(marketplace.MarketplaceId);
                var taxrecordlist = taxManagement.RowCast <KCTaxManagement>().ToList().Where
                                        (x => x.CountryId == order.BillingCountry);
                foreach (var taxman in taxrecordlist)
                {
                    var byState = taxrecordlist.Where(x => (x?.StateId == order.BillingStateOrProvince) || x?.StateId?.Contains(order.BillingStateOrProvince) == true);
                    if (byState.Count() == 0 && taxrecordlist.Where(x => x.CountryId == order.BillingCountry && x?.StateId == null).Count() != 0)
                    {
                        taxrecord = taxrecordlist.Where(x => x.CountryId == order.BillingCountry && x?.StateId == null).FirstOrDefault();
                    }
                    else
                    {
                        taxrecord = byState.FirstOrDefault();
                    }
                }
            }
            if (marketplace != null) // If marketplace exist on Marketplace grid settings
            {
                if (taxManagement != null && taxrecord != null)
                {
                    if (!taxrecord.UseDefTaxZone.GetValueOrDefault()) // if this row has UseDefTaxZone on true
                    {
                        string defTaxZone = taxrecord.TaxZoneId;
                        return(defTaxZone);
                    }
                    else
                    {
                        //if (orderExt.KCXSiteMaster.SelectSingle().IsImportTax == "0") // if UseDefTaxZone is true--use General settings
                        {
                            if (isCATaxZoneExist == null)
                            {
                                SalesTaxMaint stax       = PXGraph.CreateInstance <SalesTaxMaint>();
                                TaxZoneMaint  CAtaxzone  = PXGraph.CreateInstance <TaxZoneMaint>();
                                Tax           tax        = stax.Tax.Insert();
                                TaxZone       newTaxZone = CAtaxzone.TxZone.Insert();
                                TaxZoneDet    taxZoneDet = CAtaxzone.TxZoneDet.Insert();
                                stax.Tax.Cache.SetValue <Tax.taxID>(tax, KCConstants.ChannelAdvisor);
                                stax.Tax.Cache.SetValue <Tax.descr>(tax, KCConstants.ChannelAdvisor);
                                stax.Tax.Cache.SetValue <Tax.salesTaxAcctID>(tax, KCConstants.salesTaxAcctID);
                                stax.Tax.Cache.SetValue <Tax.salesTaxSubID>(tax, KCConstants.salesTaxSubID);
                                stax.Tax.Cache.SetValue <Tax.taxCalcType>(tax, KCConstants.taxCalcType);
                                stax.Tax.Cache.SetValue <Tax.taxCalcLevel>(tax, KCConstants.taxCalcLevel);
                                stax.Persist();
                                CAtaxzone.TxZone.Cache.SetValue <TaxZone.taxZoneID>(newTaxZone, KCConstants.Channel);
                                CAtaxzone.TxZone.Cache.SetValue <TaxZone.descr>(newTaxZone, KCConstants.Channel);
                                CAtaxzone.TxZone.Cache.SetValue <TaxZone.dfltTaxCategoryID>(newTaxZone, KCConstants.Taxable);
                                CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxZoneID>(taxZoneDet, newTaxZone.TaxZoneID);
                                CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxID>(taxZoneDet, tax.TaxID);
                                CAtaxzone.Persist();
                                string defTaxZone = newTaxZone.TaxZoneID;
                                return(defTaxZone);
                            }
                            else
                            {
                                string defTaxZone = isCATaxZoneExist.TaxZoneID;
                                return(defTaxZone);
                            }
                        }
                        //else
                        //{
                        //    string defTaxZone = orderExt.KCXSiteMaster.SelectSingle().TaxZone;
                        //    return defTaxZone;
                        //}
                    }
                }
                else
                {
                    if (!marketplace.UseDefTaxZone.GetValueOrDefault()) // if this row has UseDefTaxZone on true
                    {
                        string defTaxZone = marketplace.TaxZone;
                        return(defTaxZone);
                    }
                    else
                    {
                        //if (orderExt.KCXSiteMaster.SelectSingle().IsImportTax == "0") // if UseDefTaxZone is true--use General settings
                        {
                            if (isCATaxZoneExist == null)
                            {
                                SalesTaxMaint stax       = PXGraph.CreateInstance <SalesTaxMaint>();
                                TaxZoneMaint  CAtaxzone  = PXGraph.CreateInstance <TaxZoneMaint>();
                                Tax           tax        = stax.Tax.Insert();
                                TaxZone       newTaxZone = CAtaxzone.TxZone.Insert();
                                TaxZoneDet    taxZoneDet = CAtaxzone.TxZoneDet.Insert();
                                stax.Tax.Cache.SetValue <Tax.taxID>(tax, KCConstants.ChannelAdvisor);
                                stax.Tax.Cache.SetValue <Tax.descr>(tax, KCConstants.ChannelAdvisor);
                                stax.Tax.Cache.SetValue <Tax.salesTaxAcctID>(tax, KCConstants.salesTaxAcctID);
                                stax.Tax.Cache.SetValue <Tax.salesTaxSubID>(tax, KCConstants.salesTaxSubID);
                                stax.Tax.Cache.SetValue <Tax.taxCalcType>(tax, KCConstants.taxCalcType);
                                stax.Tax.Cache.SetValue <Tax.taxCalcLevel>(tax, KCConstants.taxCalcLevel);
                                stax.Persist();
                                CAtaxzone.TxZone.Cache.SetValue <TaxZone.taxZoneID>(newTaxZone, KCConstants.Channel);
                                CAtaxzone.TxZone.Cache.SetValue <TaxZone.descr>(newTaxZone, KCConstants.Channel);
                                CAtaxzone.TxZone.Cache.SetValue <TaxZone.dfltTaxCategoryID>(newTaxZone, KCConstants.Taxable);
                                CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxZoneID>(taxZoneDet, newTaxZone.TaxZoneID);
                                CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxID>(taxZoneDet, tax.TaxID);
                                CAtaxzone.Persist();
                                string defTaxZone = newTaxZone.TaxZoneID;
                                return(defTaxZone);
                            }
                            else
                            {
                                string defTaxZone = isCATaxZoneExist.TaxZoneID;
                                return(defTaxZone);
                            }
                        }
                        //else
                        //{
                        //    string defTaxZone = orderExt.KCXSiteMaster.SelectSingle().TaxZone;
                        //    return defTaxZone;
                        //}
                    }
                }
            }
            else
            {
                if (orderExt.KCXSiteMaster.SelectSingle().IsImportTax == "0") // if UseDefTaxZone is true--use General settings
                {
                    if (isCATaxZoneExist == null)
                    {
                        SalesTaxMaint stax       = PXGraph.CreateInstance <SalesTaxMaint>();
                        TaxZoneMaint  CAtaxzone  = PXGraph.CreateInstance <TaxZoneMaint>();
                        Tax           tax        = stax.Tax.Insert();
                        TaxZone       newTaxZone = CAtaxzone.TxZone.Insert();
                        TaxZoneDet    taxZoneDet = CAtaxzone.TxZoneDet.Insert();
                        stax.Tax.Cache.SetValue <Tax.taxID>(tax, KCConstants.ChannelAdvisor);
                        stax.Tax.Cache.SetValue <Tax.descr>(tax, KCConstants.ChannelAdvisor);
                        stax.Tax.Cache.SetValue <Tax.salesTaxAcctID>(tax, KCConstants.salesTaxAcctID);
                        stax.Tax.Cache.SetValue <Tax.salesTaxSubID>(tax, KCConstants.salesTaxSubID);
                        stax.Tax.Cache.SetValue <Tax.taxCalcType>(tax, KCConstants.taxCalcType);
                        stax.Tax.Cache.SetValue <Tax.taxCalcLevel>(tax, KCConstants.taxCalcLevel);
                        stax.Persist();
                        CAtaxzone.TxZone.Cache.SetValue <TaxZone.taxZoneID>(newTaxZone, KCConstants.Channel);
                        CAtaxzone.TxZone.Cache.SetValue <TaxZone.descr>(newTaxZone, KCConstants.Channel);
                        CAtaxzone.TxZone.Cache.SetValue <TaxZone.dfltTaxCategoryID>(newTaxZone, KCConstants.Taxable);
                        CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxZoneID>(taxZoneDet, newTaxZone.TaxZoneID);
                        CAtaxzone.TxZoneDet.Cache.SetValue <TaxZoneDet.taxID>(taxZoneDet, tax.TaxID);
                        CAtaxzone.Persist();

                        string defTaxZone = newTaxZone.TaxZoneID;
                        return(defTaxZone);
                    }
                    else
                    {
                        string defTaxZone = isCATaxZoneExist.TaxZoneID;
                        return(defTaxZone);
                    }
                }
                else
                {
                    string defTaxZone = orderExt.KCXSiteMaster.SelectSingle().TaxZone;
                    return(defTaxZone);
                }
            }
        }
Esempio n. 18
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;
            }
        }
Esempio n. 19
0
        protected override void Seed(DAL.DataContext context)
        {
            #region Import translations

            if (context.Translations.None())
            {
                DataImportController.ImportTranslationsCsv(context, new CsvReader(File.OpenText(
                                                                                      HostingEnvironment.MapPath("~/Content/DataInitializer/Translations/Translations.csv"))),
                                                           TranslationArea.Frontend);

                DataImportController.ImportTranslationsCsv(context, new CsvReader(File.OpenText(
                                                                                      HostingEnvironment.MapPath("~/Content/DataInitializer/Translations/TranslationsAdmin.csv"))),
                                                           TranslationArea.Backend);
            }

            Thread.CurrentThread.CurrentUICulture = new CultureInfo(
                WebConfigurationManager.AppSettings["DefaultCulture"]);

            #endregion

            #region Create user roles

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            if (!roleManager.RoleExists(User.ADMIN_ROLE))
            {
                roleManager.Create(new IdentityRole(User.ADMIN_ROLE));
            }

            if (!roleManager.RoleExists(User.CUSTOMER_ROLE))
            {
                roleManager.Create(new IdentityRole(User.CUSTOMER_ROLE));
            }

            if (!roleManager.RoleExists(User.OPERATOR_ROLE))
            {
                roleManager.Create(new IdentityRole(User.OPERATOR_ROLE));
            }

            #endregion

            #region Create users

            if (context.Users.None())
            {
                var userManager = new UserManager <User>(new UserStore <User>(context));

                // Create admin user
                var admin = new User
                {
                    FirstName   = "Admin",
                    LastName    = "Admin",
                    Company     = "Admin",
                    PhoneNumber = "1-800-ADMIN",
                    UserName    = WebConfigurationManager.AppSettings["DefaultUserEmail"],
                    Email       = WebConfigurationManager.AppSettings["DefaultUserEmail"],
                };
                IdentityResult result = userManager.Create(admin, WebConfigurationManager.AppSettings["DefaultUserPassword"]);
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
                userManager.AddToRole(admin.Id, User.ADMIN_ROLE);
            }

            #endregion

            #region Create EmailTemplates

            if (context.EmailTemplates.None())
            {
                var templateTypes = new List <EmailTemplate>
                {
                    new EmailTemplate
                    {
                        Subject = "Order Successful".TA(),
                        Body    = "Your order has been received successfully".TA(),
                        Type    = EmailTemplateType.OrderCompleted
                    }
                };

                templateTypes.ForEach(t => context.EmailTemplates.AddOrUpdate(t));
                context.SaveChanges();
            }

            #endregion

            #region Import countries and states

            if (context.Countries.None())
            {
                string countryJson =
                    File.ReadAllText(HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/Countries.json"));
                dynamic json = JsonConvert.DeserializeObject(countryJson);

                foreach (dynamic item in json)
                {
                    var country = new Country {
                        Code = item.code, Name = item.name, IsActive = true
                    };
                    context.Countries.Add(country);

                    if (item.filename != null)
                    {
                        dynamic regionJson =
                            File.ReadAllText(
                                HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/" + item.filename +
                                                           ".json"));
                        dynamic json2 = JsonConvert.DeserializeObject(regionJson);
                        foreach (dynamic item2 in json2)
                        {
                            var region = new Region {
                                Country = country, Code = item2.code, Name = item2.name
                            };
                            context.Regions.Add(region);
                        }
                    }
                }

                context.SaveChanges();
            }

            #endregion

            #region Create default shipping and tax zones

            if (context.TaxZones.None())
            {
                var taxZone = new TaxZone {
                    Name = "Default".TA(), IsActive = true
                };
                context.TaxZones.Add(taxZone);
            }

            if (context.ShippingZones.None())
            {
                var shippingZone = new ShippingZone {
                    Name = "Default".TA(), IsActive = true
                };
                context.ShippingZones.Add(shippingZone);
            }

            #endregion

            #region Create default content pages

            if (context.ContentPages.None())
            {
                var page = new ContentPage
                {
                    Title   = "About Us".TA(),
                    Content =
                        "Edit this page contents from the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 1,
                    FooterPosition = 1
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Contact Us".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 2,
                    FooterPosition = 2
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Terms & Conditions".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 3,
                    FooterPosition = 3
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Privacy Policy".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 4,
                    FooterPosition = 4
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Orders and Returns".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 5,
                    FooterPosition = 5
                };
                context.ContentPages.Add(page);
                context.SaveChanges();
            }

            #endregion

            #region Create default news blog

            if (context.Blogs.None())
            {
                User admin = context.Users.OrderByDescending(u => u.DateRegistered).FirstOrDefault();

                var blog = new Blog
                {
                    Title = "News".T()
                };
                context.Blogs.Add(blog);

                if (admin != null)
                {
                    var blogPost = new BlogPost
                    {
                        UserId  = admin.Id,
                        Blog    = blog,
                        Title   = "Store created".T(),
                        Content = "You can use the blog functionality to post updates for your users...".T()
                    };
                    context.BlogPosts.Add(blogPost);
                }

                context.SaveChanges();
            }

            #endregion

            #region Payment methods

            if (context.PaymentMethods.None())
            {
                var paymentMethods = new List <PaymentMethod>
                {
                    new PaymentMethod
                    {
                        Name     = "Bank Deposit".TA(),
                        Settings =
                            "Bank Name: ACME Bank\nBank Branch: New York\nAccount Name: John Smith\nAccount Number: XXXXXXXXXXX\n\nType any special instructions in here.",
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name     = "Cash on Delivery".TA(),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name      = "Check".TA(),
                        Countries =
                            new Collection <Country>(
                                context.Countries.Where(c => c.Code == "US").ToArray()),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name     = "Money Order".TA(),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name     = "Pay in Store".TA(),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name      = "ePay.bg".TA(),
                        ClassName = "EPayBgButton",
                        Countries =
                            new Collection <Country>(
                                context.Countries.Where(c => c.Code == "BG").ToArray()),
                        Type     = PaymentMethodType.Hosted,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name      = "Paypal Website Payments (Standard)".TA(),
                        ClassName = "PayPalStandard",
                        Type      = PaymentMethodType.Hosted,
                        IsActive  = true
                    },
                };
                paymentMethods.ForEach(c => context.PaymentMethods.AddOrUpdate(c));
                context.SaveChanges();
            }

            #endregion
        }
        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 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);
        }
Esempio n. 22
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();
        }
Esempio n. 23
0
        protected override void Seed(DataContext context)
        {
            #region Delete old photos

            foreach (var file in Directory.GetFiles(HostingEnvironment.MapPath("~/Storage/"), "*.*"))
            {
                if (file.Contains("web.config"))
                {
                    continue;
                }
                File.Delete(file);
            }

            #endregion

            #region Import countries and states

            string countryJson =
                File.ReadAllText(HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/Countries.json"));
            dynamic json = JsonConvert.DeserializeObject(countryJson);

            foreach (dynamic item in json)
            {
                var country = new Country {
                    Code = item.code, Name = item.name
                };
                country.IsActive = country.Code == "US" || country.Code == "BG";
                context.Countries.Add(country);

                if (item.filename != null)
                {
                    dynamic regionJson =
                        File.ReadAllText(
                            HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/" + item.filename + ".json"));
                    dynamic json2 = JsonConvert.DeserializeObject(regionJson);
                    foreach (dynamic item2 in json2)
                    {
                        var region = new Region {
                            Country = country, Code = item2.code, Name = item2.name
                        };
                        context.Regions.Add(region);
                    }
                }
            }

            try
            {
                context.SaveChanges();
            }
            catch (Exception err)
            {
                throw err;
            }

            #endregion

            #region Import taxes

            string vatJson =
                File.ReadAllText(HostingEnvironment.MapPath("~/Content/DataInitializer/TaxRates/vat.json"));
            dynamic vats = JsonConvert.DeserializeObject(vatJson);

            foreach (dynamic vat in vats)
            {
                var     countryCode = (string)vat.countryCode;
                Country country     = context.Countries.First(c => c.Code == countryCode);
                var     taxZone     = new TaxZone
                {
                    Name      = country.Name,
                    IsActive  = true,
                    Countries = new Collection <Country> {
                        country
                    }
                };

                var taxRate = new TaxRate
                {
                    Name     = "VAT",
                    TaxZone  = taxZone,
                    Amount   = vat.percentage,
                    IsActive = true
                };

                context.TaxZones.Add(taxZone);
                context.TaxRates.Add(taxRate);
            }

            var calTaxZone = new TaxZone
            {
                Name      = "California Tax",
                Countries = new Collection <Country> {
                    context.Countries.First(c => c.Code == "US")
                },
                Regions = new Collection <Region> {
                    context.Regions.First(r => r.Name == "California")
                },
                IsActive = true
            };
            var calTaxRate = new TaxRate
            {
                Name     = "Sales Tax",
                TaxZone  = calTaxZone,
                Amount   = 7.5m,
                IsActive = true
            };

            context.TaxZones.Add(calTaxZone);
            context.TaxRates.Add(calTaxRate);

            context.SaveChanges();

            #endregion

            #region Create shipping options

            var defShipZone = new ShippingZone
            {
                Name     = "Default",
                IsActive = true
            };
            context.ShippingZones.Add(defShipZone);

            var worldWideShippingUPS = new ShippingMethod
            {
                ShippingZone   = defShipZone,
                Name           = "UPS Worldwide",
                Type           = ShippingMethodType.Flat,
                FlatRateAmount = 500
            };
            context.ShippingMethods.Add(worldWideShippingUPS);

            var bgShipZone = new ShippingZone
            {
                Name      = "Bulgaria",
                Countries = new Collection <Country> {
                    context.Countries.First(c => c.Code == "BG")
                },
                IsActive = true
            };
            context.ShippingZones.Add(bgShipZone);

            var freeBgShipping = new ShippingMethod
            {
                ShippingZone         = bgShipZone,
                Name                 = "Free shipping",
                Type                 = ShippingMethodType.Free,
                FreeShippingMinTotal = 2000
            };
            var econtShipping = new ShippingMethod
            {
                ShippingZone   = bgShipZone,
                Name           = "Econt",
                Type           = ShippingMethodType.Flat,
                FlatRateAmount = 10
            };
            context.ShippingMethods.Add(econtShipping);
            context.ShippingMethods.Add(freeBgShipping);

            context.SaveChanges();

            #endregion

            #region Payment methods

            var paymentMethods = new List <PaymentMethod>
            {
                new PaymentMethod
                {
                    Name     = "Bank Deposit",
                    Settings =
                        "Bank Name: ACME Bank\nBank Branch: New York\nAccount Name: John Smith\nAccount Number: XXXXXXXXXXX\n\nType any special instructions in here.",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name     = "Cash on Delivery",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name      = "Check",
                    Countries =
                        new Collection <Country>(
                            context.Countries.Where(c => c.Code == "US").ToArray()),
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name     = "Money Order",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name     = "Pay in Store",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name      = "ePay.bg",
                    ClassName = "EPayBgButton",
                    Countries =
                        new Collection <Country>(
                            context.Countries.Where(c => c.Code == "BG").ToArray()),
                    Type     = PaymentMethodType.Hosted,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name      = "Paypal Website Payments (Standard)",
                    ClassName = "PayPalStandard",
                    Type      = PaymentMethodType.Hosted,
                    IsActive  = true
                },
            };
            paymentMethods.ForEach(c => context.PaymentMethods.AddOrUpdate(c));
            context.SaveChanges();

            #endregion

            #region Create users

            var userManager = new UserManager <User>(new UserStore <User>(context));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            // Create admin role
            roleManager.Create(new IdentityRole(User.ADMIN_ROLE));
            roleManager.Create(new IdentityRole(User.CUSTOMER_ROLE));

            // Create admin user
            var admin = new User
            {
                FirstName   = "Admin",
                LastName    = "Adminov",
                Company     = "Admin Inc",
                PhoneNumber = "1-800-ADMIN",
                UserName    = "******",
                Email       = "*****@*****.**",
            };
            IdentityResult result = userManager.Create(admin, "123pass");
            if (!result.Succeeded)
            {
                throw new Exception(string.Join("\n", result.Errors));
            }
            userManager.AddToRole(admin.Id, User.ADMIN_ROLE);

            // Create regular user
            var user = new User
            {
                FirstName   = "Tester",
                LastName    = "Testerov",
                Company     = "Test Ltd",
                PhoneNumber = "1-800-USER",
                UserName    = "******",
                Email       = "*****@*****.**"
            };
            userManager.Create(user, "123pass");
            userManager.AddToRole(user.Id, User.CUSTOMER_ROLE);

            #endregion

            #region Create EmailTemplates

            var templateTypes = new List <EmailTemplate>
            {
                new EmailTemplate
                {
                    Subject = "Order Successful",
                    Body    = "Your order has been received successfully",
                    Type    = EmailTemplateType.OrderCompleted
                }
            };

            templateTypes.ForEach(t => context.EmailTemplates.AddOrUpdate(t));
            context.SaveChanges();

            #endregion

            context.SaveChanges();

            // Temporary until better solution is added to EF Code First
            context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('Orders', RESEED, 101)");

            base.Seed(context);
        }
        /*protected virtual GetTaxRequest BuildGetTaxRequestOpen(FSAppointment order)
         * {
         *  Stopwatch sw = new Stopwatch();
         *  sw.Start();
         *
         *  if (order == null)
         *      throw new PXArgumentException(ErrorMessages.ArgumentNullException);
         *
         *  Customer cust = (Customer)Base.TaxCustomer.View.SelectSingleBound(new object[] { order });
         *  Location loc = (Location)Base.TaxLocation.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 = cust.AcctCD;
         *  request.OriginAddress = AddressConverter.ConvertTaxAddress(fromAddress);
         *  request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
         *  request.DocCode = string.Format("SO.{0}.{1}", order.SrvOrdType, order.RefNbr);
         *  request.DocDate = order.ScheduledDateTimeBegin.GetValueOrDefault();
         *  request.LocationCode = GetExternalTaxProviderLocationCode(order);
         *
         *  int mult = 1;
         *
         *  if (!string.IsNullOrEmpty(loc.CAvalaraCustomerUsageType))
         *  {
         *      request.CustomerUsageType = loc.CAvalaraCustomerUsageType;
         *  }
         *  if (!string.IsNullOrEmpty(loc.CAvalaraExemptionNumber))
         *  {
         *      request.ExemptionNo = loc.CAvalaraExemptionNumber;
         *  }
         *
         *  FSSrvOrdType srvOrdType = (FSSrvOrdType)Base.ServiceOrderTypeSelected.View.SelectSingleBound(new object[] { order });
         *
         *  if (srvOrdType.DefaultOperation == SOOperation.Receipt)
         *  {
         *      request.DocType = TaxDocumentType.ReturnOrder;
         *      mult = -1;
         *
         *      PXSelectBase<FSAppointmentDet> selectLineWithInvoiceDate = new PXSelect<FSAppointmentDet,
         *      Where<FSAppointmentDet.srvOrdType, Equal<Required<FSAppointmentDet.srvOrdType>>, And<FSAppointmentDet.refNbr, Equal<Required<FSAppointmentDet.refNbr>>,
         *      And<FSAppointmentDet.invoiceDate, IsNotNull>>>>(Base);
         *
         *      FSAppointmentDet soLine = selectLineWithInvoiceDate.SelectSingle(order.SrvOrdType, order.RefNbr);
         *      if (soLine != null && soLine.TranDate != null)
         *      {
         *          request.TaxOverride.Reason = Messages.ReturnReason;
         *          request.TaxOverride.TaxDate = soLine.TranDate.Value;
         *          request.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
         *      }
         *
         *  }
         *  else
         *  {
         *      request.DocType = TaxDocumentType.SalesOrder;
         *  }
         *  request.DocType = TaxDocumentType.SalesOrder;
         *
         *
         *  PXSelectBase<FSAppointmentDet> select = new PXSelectJoin<FSAppointmentDet,
         *      LeftJoin<InventoryItem, On<InventoryItem.inventoryID, Equal<FSAppointmentDet.inventoryID>>,
         *          LeftJoin<Account, On<Account.accountID, Equal<FSAppointmentDet.acctID>>>>,
         *      Where<FSAppointmentDet.srvOrdType, Equal<Current<FSAppointment.srvOrdType>>,
         *          And<FSAppointmentDet.refNbr, Equal<Current<FSAppointment.refNbr>>>>,
         *      OrderBy<Asc<FSAppointmentDet.srvOrdType, Asc<FSAppointmentDet.refNbr, Asc<FSAppointmentDet.lineNbr>>>>>(Base);
         *
         *  request.Discount = order.CuryDiscTot.GetValueOrDefault();
         *
         *  foreach (PXResult<FSAppointmentDet, InventoryItem, Account> res in select.View.SelectMultiBound(new object[] { order }))
         *  {
         *      FSAppointmentDet tran = (FSAppointmentDet)res;
         *      InventoryItem item = (InventoryItem)res;
         *      Account salesAccount = (Account)res;
         *
         *      if (tran.OpenAmt >= 0)
         *      {
         *          var line = new TaxCartItem();
         *          line.Index = tran.LineNbr ?? 0;
         *          if (srvOrdType.DefaultOperation != tran.Operation)
         *              line.Amount = -1 * mult * tran.CuryOpenAmt.GetValueOrDefault();
         *          else
         *              line.Amount = mult * tran.CuryOpenAmt.GetValueOrDefault();
         *          line.Description = tran.TranDesc;
         *          line.DestinationAddress = AddressConverter.ConvertTaxAddress(GetToAddress(order, tran));
         *          line.OriginAddress = AddressConverter.ConvertTaxAddress(GetFromAddress(order, tran));
         *          line.ItemCode = item.InventoryCD;
         *          line.Quantity = Math.Abs(tran.OpenQty.GetValueOrDefault());
         *          line.Discounted = request.Discount > 0;
         *          line.RevAcct = salesAccount.AccountCD;
         *
         *          line.TaxCode = tran.TaxCategoryID;
         *
         *          request.CartItems.Add(line);
         *      }
         *  }
         *
         *  sw.Stop();
         *  Debug.Print("BuildGetTaxRequestOpen() in {0} millisec.", sw.ElapsedMilliseconds);
         *
         *  return request;
         * }
         */
        /*protected virtual GetTaxRequest BuildGetTaxRequestUnbilled(FSAppointment order)
         * {
         *  Stopwatch sw = new Stopwatch();
         *  sw.Start();
         *
         *  if (order == null)
         *      throw new PXArgumentException(ErrorMessages.ArgumentNullException);
         *
         *  Customer cust = (Customer)Base.TaxCustomer.View.SelectSingleBound(new object[] { order });
         *  Location loc = (Location)Base.TaxLocation.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 = cust.AcctCD;
         *  request.OriginAddress = AddressConverter.ConvertTaxAddress(fromAddress);
         *  request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
         *  request.DocCode = string.Format("{0}.{1}.Open", order.SrvOrdType, order.RefNbr);
         *  request.DocDate = order.ScheduledDateTimeBegin.GetValueOrDefault();
         *  request.LocationCode = GetExternalTaxProviderLocationCode(order);
         *
         *  int mult = 1;
         *
         *  if (!string.IsNullOrEmpty(order.AvalaraCustomerUsageType))
         *  {
         *      request.CustomerUsageType = order.AvalaraCustomerUsageType;
         *  }
         *  if (!string.IsNullOrEmpty(loc.CAvalaraExemptionNumber))
         *  {
         *      request.ExemptionNo = loc.CAvalaraExemptionNumber;
         *  }
         *
         *  FSSrvOrdType srvOrdType = (FSSrvOrdType)Base.ServiceOrderTypeSelected.View.SelectSingleBound(new object[] { order });
         *
         *  if (srvOrdType.DefaultOperation == SOOperation.Receipt)
         *  {
         *      request.DocType = TaxDocumentType.ReturnOrder;
         *      mult = -1;
         *
         *      PXSelectBase<FSAppointmentDet> selectLineWithInvoiceDate = new PXSelect<FSAppointmentDet,
         *      Where<FSAppointmentDet.srvOrdType, Equal<Required<FSAppointmentDet.srvOrdType>>, And<FSAppointmentDet.refNbr, Equal<Required<FSAppointmentDet.refNbr>>,
         *      And<FSAppointmentDet.invoiceDate, IsNotNull>>>>(Base);
         *
         *      FSAppointmentDet soLine = selectLineWithInvoiceDate.SelectSingle(order.SrvOrdType, order.RefNbr);
         *      if (soLine != null && soLine.TranDate != null)
         *      {
         *          request.TaxOverride.Reason = Messages.ReturnReason;
         *          request.TaxOverride.TaxDate = soLine.TranDate.Value;
         *          request.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
         *      }
         *
         *  }
         *  else
         *  {
         *      request.DocType = TaxDocumentType.SalesOrder;
         *  }
         *
         *
         *  PXSelectBase<FSAppointmentDet> select = new PXSelectJoin<FSAppointmentDet,
         *      LeftJoin<InventoryItem, On<InventoryItem.inventoryID, Equal<FSAppointmentDet.inventoryID>>,
         *          LeftJoin<Account, On<Account.accountID, Equal<FSAppointmentDet.salesAcctID>>>>,
         *      Where<FSAppointmentDet.srvOrdType, Equal<Current<FSAppointment.srvOrdType>>,
         *          And<FSAppointmentDet.refNbr, Equal<Current<FSAppointment.refNbr>>>>,
         *      OrderBy<Asc<FSAppointmentDet.srvOrdType, Asc<FSAppointmentDet.refNbr, Asc<FSAppointmentDet.lineNbr>>>>>(Base);
         *
         *  request.Discount = order.CuryDiscTot.GetValueOrDefault();
         *
         *  foreach (PXResult<FSAppointmentDet, InventoryItem, Account> res in select.View.SelectMultiBound(new object[] { order }))
         *  {
         *      FSAppointmentDet tran = (FSAppointmentDet)res;
         *      InventoryItem item = (InventoryItem)res;
         *      Account salesAccount = (Account)res;
         *
         *      if (tran.UnbilledAmt >= 0)
         *      {
         *          var line = new TaxCartItem();
         *          line.Index = tran.LineNbr ?? 0;
         *          if (srvOrdType.DefaultOperation != tran.Operation)
         *              line.Amount = -1 * mult * tran.CuryUnbilledAmt.GetValueOrDefault();
         *          else
         *              line.Amount = mult * tran.CuryUnbilledAmt.GetValueOrDefault();
         *          line.Description = tran.TranDesc;
         *          line.DestinationAddress = AddressConverter.ConvertTaxAddress(GetToAddress(order, tran));
         *          line.OriginAddress = AddressConverter.ConvertTaxAddress(GetFromAddress(order, tran));
         *          line.ItemCode = item.InventoryCD;
         *          line.Quantity = Math.Abs(tran.UnbilledQty.GetValueOrDefault());
         *          line.Discounted = request.Discount > 0;
         *          line.RevAcct = salesAccount.AccountCD;
         *
         *          line.TaxCode = tran.TaxCategoryID;
         *
         *          request.CartItems.Add(line);
         *      }
         *  }
         *
         *  sw.Stop();
         *  Debug.Print("BuildGetTaxRequestUnbilled() in {0} millisec.", sw.ElapsedMilliseconds);
         *
         *  return request;
         * }
         */
        /*protected virtual GetTaxRequest BuildGetTaxRequestFreight(FSAppointment order)
         * {
         *  Stopwatch sw = new Stopwatch();
         *  sw.Start();
         *
         *  if (order == null)
         *      throw new PXArgumentException(ErrorMessages.ArgumentNullException);
         *
         *  Customer cust = (Customer)Base.TaxCustomer.View.SelectSingleBound(new object[] { order });
         *  Location loc = (Location)Base.TaxLocation.View.SelectSingleBound(new object[] { order });
         *
         *  IAddressBase fromAddress = GetFromAddress(order);
         *  IAddressBase toAddress = GetToAddress(order);
         *
         *  if (fromAddress == null)
         *      throw new PXException(PX.Objects.CR.Messages.FailedGetFromAddressCR);
         *
         *  if (toAddress == null)
         *      throw new PXException(PX.Objects.CR.Messages.FailedGetToAddressCR);
         *
         *  GetTaxRequest request = new GetTaxRequest();
         *  request.CompanyCode = CompanyCodeFromBranch(order.TaxZoneID, order.BranchID);
         *  request.CurrencyCode = order.CuryID;
         *  request.CustomerCode = cust.AcctCD;
         *  request.OriginAddress = AddressConverter.ConvertTaxAddress(fromAddress);
         *  request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
         *  request.DocCode = $"{order.SrvOrdType}.{order.RefNbr}.Freight";
         *  request.DocDate = order.ScheduledDateTimeBegin.GetValueOrDefault();
         *  request.LocationCode = GetExternalTaxProviderLocationCode(order);
         *
         *  int mult = 1;
         *
         *  if (!string.IsNullOrEmpty(loc.CAvalaraCustomerUsageType))
         *  {
         *      request.CustomerUsageType = loc.CAvalaraCustomerUsageType;
         *  }
         *  if (!string.IsNullOrEmpty(loc.CAvalaraExemptionNumber))
         *  {
         *      request.ExemptionNo = loc.CAvalaraExemptionNumber;
         *  }
         *
         *  FSSrvOrdType srvOrdType = (FSSrvOrdType)Base.ServiceOrderTypeSelected.View.SelectSingleBound(new object[] { order });
         *
         *  if (srvOrdType.ARDocType == ARDocType.CreditMemo)
         *  {
         *      request.DocType = TaxDocumentType.ReturnOrder;
         *      mult = -1;
         *  }
         *  else
         *  {
         *      request.DocType = TaxDocumentType.SalesOrder;
         *  }
         *
         *  if (order.CuryFreightTot > 0)
         *  {
         *      var line = new TaxCartItem();
         *      line.Index = short.MaxValue;
         *      line.Amount = mult * order.CuryFreightTot.GetValueOrDefault();
         *      line.Description = PXMessages.LocalizeNoPrefix(Messages.FreightDesc);
         *      line.DestinationAddress = request.DestinationAddress;
         *      line.OriginAddress = request.OriginAddress;
         *      line.ItemCode = "N/A";
         *      line.Discounted = false;
         *      line.TaxCode = order.FreightTaxCategoryID;
         *
         *      request.CartItems.Add(line);
         *  }
         *
         *  sw.Stop();
         *  Debug.Print("BuildGetTaxRequestFreight() in {0} millisec.", sw.ElapsedMilliseconds);
         *
         *  return request;
         * }
         */
        protected virtual void ApplyTax(FSAppointment order, GetTaxResult result, GetTaxResult resultOpen, GetTaxResult resultUnbilled, GetTaxResult resultFreight)
        {
            TaxZone taxZone = (TaxZone)Base.TaxZone.View.SelectSingleBound(new object[] { order });

            if (taxZone == null)
            {
                throw new PXException(PX.Objects.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(PX.Objects.CR.Messages.ExternalTaxVendorNotFound);
            }

            /*var sign = ((FSSrvOrdType)Base.ServiceOrderTypeSelected.View.SelectSingleBound(new object[] { order })).DefaultOperation == SOOperation.Receipt
             *  ? Sign.Minus
             *  : Sign.Plus;*/
            var sign = Sign.Plus;

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

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

                decimal freightTax = 0;
                if (resultFreight != null)
                {
                    freightTax = sign * resultFreight.TotalTaxAmount;
                }

                //bool requireControlTotal = Base.ServiceOrderTypeSelected.Current.RequireControlTotal == true;

                /*if (order.Hold != true)
                 *  Base.ServiceOrderTypeSelected.Current.RequireControlTotal = false;*/

                var taxDetails = new List <PX.TaxProvider.TaxDetail>();
                foreach (TaxProvider.TaxDetail tax in result.TaxSummary.OrderByDescending(e => e.TaxAmount))
                {
                    if (tax.TaxAmount != 0 ||
                        taxDetails.Find(e => e.TaxName == tax.TaxName) == default(TaxProvider.TaxDetail))
                    {
                        taxDetails.Add(tax);
                    }
                }

                if (resultFreight != null)
                {
                    foreach (TaxProvider.TaxDetail tax in resultFreight.TaxSummary.OrderByDescending(e => e.TaxAmount))
                    {
                        if (tax.TaxAmount != 0 ||
                            taxDetails.Find(e => e.TaxName == tax.TaxName) == default(TaxProvider.TaxDetail))
                        {
                            taxDetails.Add(tax);
                        }
                    }
                }

                try
                {
                    foreach (var taxDetail in taxDetails)
                    {
                        string taxID = taxDetail.TaxName;

                        if (string.IsNullOrEmpty(taxID))
                        {
                            taxID = taxDetail.JurisCode;
                        }

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

                        CreateTax(Base, taxZone, vendor, taxDetail, taxID);

                        FSAppointmentTaxTran tax = (FSAppointmentTaxTran)Base.Taxes.Cache.CreateInstance();;

                        tax.TaxID          = taxID;
                        tax.CuryTaxAmt     = Math.Abs(taxDetail.TaxAmount);
                        tax.CuryTaxableAmt = Math.Abs(taxDetail.TaxableAmount);
                        tax.TaxRate        = Convert.ToDecimal(taxDetail.Rate) * 100;
                        tax.JurisType      = taxDetail.JurisType;
                        tax.JurisName      = taxDetail.JurisName;

                        Base.Taxes.Insert(tax);
                    }

                    Base.AppointmentSelected.SetValueExt <FSAppointment.curyTaxTotal>(order, sign * result.TotalTaxAmount + freightTax);

                    decimal?СuryDocTotal = AppointmentEntry.GetCuryDocTotal(order.CuryBillableLineTotal, order.CuryLogBillableTranAmountTotal, order.CuryDiscTot, order.CuryTaxTotal, 0);
                    Base.AppointmentSelected.SetValueExt <FSAppointment.curyDocTotal>(order, СuryDocTotal ?? 0m);
                }
                finally
                {
                    //Base.ServiceOrderTypeSelected.Current.RequireControlTotal = requireControlTotal;
                }
            }


            /*if (resultUnbilled != null)
             *  Base.AppointmentRecords.SetValueExt<FSAppointment.curyUnbilledTaxTotal>(order, sign * resultUnbilled.TotalTaxAmount);
             *
             * if (resultOpen != null)
             *  Base.AppointmentRecords.SetValueExt<FSAppointment.curyOpenTaxTotal>(order, sign * resultOpen.TotalTaxAmount);*/

            order            = (FSAppointment)Base.AppointmentSelected.Cache.CreateCopy(order);
            order.IsTaxValid = true;
            Base.AppointmentSelected.Cache.Update(order);

            if (Base.TimeStamp == null)
            {
                Base.SelectTimeStamp();
            }

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