예제 #1
0
        protected virtual void SetPOAdjustAdjdAmt(POAdjust row)
        {
            if (row == null)
            {
                return;
            }

            var order = POOrder.PK.Find(Base, row.AdjdOrderType, row.AdjdOrderNbr);

            if (order != null)
            {
                if (order.CuryID == Base.Document.Current.CuryID)
                {
                    POAdjustments.Cache.SetValueExt <POAdjust.curyAdjdAmt>(row, row.CuryAdjgAmt);
                }
                else
                {
                    PXCurrencyAttribute.CuryConvBase <POAdjust.adjgCuryInfoID>(POAdjustments.Cache, row, row.CuryAdjgAmt ?? 0, out decimal baseCuryAmt);
                    PXCurrencyAttribute.CuryConvCury(Base.Caches <POOrder>(), order, baseCuryAmt, out decimal orderCuryAmt);
                    POAdjustments.Cache.SetValueExt <POAdjust.curyAdjdAmt>(row, orderCuryAmt);
                }
            }

            POAdjustments.Cache.SetValueExt <POAdjust.adjdAmt>(row, row.AdjgAmt);
        }
예제 #2
0
        public override void Verify(PXCache cache, object item, List <object> pars, ref bool?result, ref object value)
        {
            decimal?curyAmount   = (decimal?)Calculate <CuryAmount>(cache, item);
            long?   curyInfoID   = (long?)Calculate <CuryInfoID>(cache, item);
            long?   toCuryInfoID = (long?)Calculate <ToCuryInfoID>(cache, item);

            CurrencyInfo orig_info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(cache.Graph, curyInfoID);

            CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(cache.Graph, toCuryInfoID);

            decimal val;
            decimal curyval;

            if (curyAmount == null || info == null || orig_info == null)
            {
                value = 0m;
                return;
            }

            if (string.Equals(info.CuryID, orig_info.CuryID))
            {
                value = curyAmount;
            }
            else
            {
                PXCurrencyAttribute.CuryConvBase(cache, orig_info, (decimal)curyAmount, out val);
                PXCurrencyAttribute.CuryConvCury(cache, info, val, out curyval);
                value = curyval;
            }
        }
        public static decimal? AdjustUnitCost(PXCache sender, UnitCostItem ucItem, int? inventoryID, CurrencyInfo currencyinfo, string UOM, decimal? currentUnitCost)
        {
            if (ucItem != null)
            {
                decimal unitCost = ucItem.Cost;

                if (currencyinfo != null && ucItem.CuryID != currencyinfo.CuryID)
                {
                    PXCurrencyAttribute.CuryConvCury(sender, currencyinfo, ucItem.Cost, out unitCost);
                }

                if (UOM == null)
                {
                    return null;
                }

                if (ucItem.UOM != UOM)
                {
                    decimal salesPriceInBase = INUnitAttribute.ConvertFromBase(sender, inventoryID, ucItem.UOM, unitCost, INPrecision.UNITCOST);
                    unitCost = INUnitAttribute.ConvertToBase(sender, inventoryID, UOM, salesPriceInBase, INPrecision.UNITCOST);
                }

                if (unitCost == 0m && currentUnitCost != null && currentUnitCost != 0m)
                    return currentUnitCost;
                else
                    return unitCost;
            }
            return null;
        }
예제 #4
0
        public override object Evaluate(PXCache cache, object item, Dictionary <Type, object> pars)
        {
            decimal?curyAmount   = (decimal?)pars[typeof(CuryAmount)];
            long?   curyInfoID   = (long?)pars[typeof(CuryInfoID)];
            long?   toCuryInfoID = (long?)pars[typeof(ToCuryInfoID)];

            CurrencyInfo orig_info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(cache.Graph, curyInfoID);

            CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(cache.Graph, toCuryInfoID);

            if (curyAmount == null || info == null || orig_info == null)
            {
                return(0m);
            }

            if (string.Equals(info.CuryID, orig_info.CuryID))
            {
                return(curyAmount);
            }

            decimal val;
            decimal curyval;

            PXCurrencyAttribute.CuryConvBase(cache, orig_info, (decimal)curyAmount, out val);
            PXCurrencyAttribute.CuryConvCury(cache, info, val, out curyval);
            return(curyval);
        }
예제 #5
0
        protected virtual void InsertUpdatePOAdjust(APAdjust apadjust)
        {
            if (Base.Document.Current?.DocType.IsNotIn(APDocType.Prepayment, APDocType.VoidCheck) == true ||
                apadjust?.AdjdDocType != APDocType.Prepayment)
            {
                return;
            }

            var prepaymentRequests = new PXSelectJoin <POOrderPrepayment,
                                                       InnerJoin <POOrder, On <POOrderPrepayment.orderType, Equal <POOrder.orderType>, And <POOrderPrepayment.orderNbr, Equal <POOrder.orderNbr> > > >,
                                                       Where <POOrderPrepayment.aPDocType, Equal <Required <APAdjust.adjdDocType> >,
                                                              And <POOrderPrepayment.aPRefNbr, Equal <Required <APAdjust.adjdRefNbr> >,
                                                                   And <POOrderPrepayment.aPDocType, Equal <APDocType.prepayment> > > > >(Base)
                                     .Select(apadjust.AdjdDocType, apadjust.AdjdRefNbr);

            foreach (PXResult <POOrderPrepayment, POOrder> row in prepaymentRequests)
            {
                POOrder           order             = row;
                POOrderPrepayment prepaymentRequest = row;

                POAdjust poadjustment = new PXSelect <POAdjust,
                                                      Where <POAdjust.adjgDocType, Equal <Current <APPayment.docType> >,
                                                             And <POAdjust.adjgRefNbr, Equal <Current <APPayment.refNbr> >,
                                                                  And <POAdjust.adjNbr, Equal <Current <APPayment.adjCntr> >,
                                                                       And <POAdjust.adjdDocType, Equal <Required <APInvoice.docType> >,
                                                                            And <POAdjust.adjdRefNbr, Equal <Required <APInvoice.refNbr> > > > > > > >(Base)
                                        .Select(apadjust.AdjdDocType, apadjust.AdjdRefNbr);

                if (poadjustment == null)
                {
                    poadjustment = POAdjustments.Insert(new POAdjust()
                    {
                        AdjgDocType   = Base.Document.Current.DocType,
                        AdjgRefNbr    = Base.Document.Current.RefNbr,
                        AdjdOrderType = prepaymentRequest.OrderType,
                        AdjdOrderNbr  = prepaymentRequest.OrderNbr,
                        AdjdDocType   = apadjust.AdjdDocType,
                        AdjdRefNbr    = apadjust.AdjdRefNbr,
                        AdjNbr        = Base.Document.Current.AdjCntr,
                        IsRequest     = true,
                    });
                }

                if (order.CuryID == Base.Document.Current.CuryID)
                {
                    POAdjustments.Cache.SetValueExt <POAdjust.curyAdjgAmt>(poadjustment, apadjust.CuryAdjgAmt);
                }
                else
                {
                    PXCurrencyAttribute.CuryConvCury(Base.Document.Cache, Base.Document.Current, apadjust.AdjAmt ?? 0, out decimal curyamount);
                    POAdjustments.Cache.SetValueExt <POAdjust.curyAdjgAmt>(poadjustment, curyamount);
                }

                POAdjustments.Update(poadjustment);
            }
        }
        /// <summary>
        /// Calculates Sales Price.
        /// </summary>
        /// <param name="sender">Cache</param>
        /// <param name="inventoryID">Inventory</param>
        /// <param name="curyID">Currency</param>
        /// <param name="UOM">Unit of measure</param>
        /// <param name="date">Date</param>
        /// <param name="alwaysFromBaseCurrency">If true sales price is always calculated (converted) from Base Currency.</param>
        /// <returns>Sales Price.</returns>
        public static decimal?CalculateSalesPrice(PXCache sender, int inventoryID, string curyID, string UOM, DateTime date, bool alwaysFromBaseCurrency)
        {
            InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(sender.Graph, inventoryID);

            decimal?salesPrice = null;

            #region Search for Sales Price in PriceList

            if (alwaysFromBaseCurrency == false)
            {
                SalesPriceItem spItem = FindSalesPrice(sender, inventoryID, curyID, UOM, date);

                if (spItem != null)
                {
                    if (spItem.UOM != UOM)
                    {
                        decimal salesPriceInBase = INUnitAttribute.ConvertToBase(sender, inventoryID, spItem.UOM, spItem.Price, INPrecision.UNITCOST);
                        salesPrice = INUnitAttribute.ConvertFromBase(sender, inventoryID, UOM, salesPriceInBase, INPrecision.UNITCOST);
                    }
                    else
                    {
                        salesPrice = spItem.Price;
                    }
                }
            }

            #endregion

            if (salesPrice == null)
            {
                #region Calculate from Base Price

                if (item.BasePriceDate != null)
                {
                    decimal salesPriceInBase;

                    if (date < item.BasePriceDate.Value)
                    {
                        //use last price
                        PXCurrencyAttribute.CuryConvCury(sender, null, item.LastBasePrice.Value, out salesPriceInBase);
                    }
                    else
                    {
                        //use current price
                        PXCurrencyAttribute.CuryConvCury(sender, null, item.BasePrice.Value, out salesPriceInBase);
                    }

                    salesPrice = INUnitAttribute.ConvertFromBase(sender, inventoryID, UOM, salesPriceInBase, INPrecision.UNITCOST);
                }

                #endregion
            }

            return(salesPrice);
        }
        private static void SetAmount(ARInvoiceEntry arGraph, decimal?curyTranAmt, decimal?tranAmt, decimal?qty, decimal signOperation, CurrencyInfo curyInfo, ARTran tran)
        {
            decimal curyamount;

            if (arGraph.currencyinfo.Current != null && curyInfo != null && arGraph.currencyinfo.Current.CuryID == curyInfo.CuryID)
            {
                curyamount = curyTranAmt.GetValueOrDefault(0);
            }
            else
            {
                PXCurrencyAttribute.CuryConvCury(arGraph.Document.Cache, arGraph.currencyinfo, tranAmt.GetValueOrDefault(), out curyamount);
            }
            tran.CuryTranAmt   = curyamount * signOperation;
            tran.CuryUnitPrice = Math.Abs((curyamount / (qty.GetValueOrDefault(1m) != 0m ? qty.GetValueOrDefault(1m) : 1m)));
            tran.CuryExtPrice  = curyamount * signOperation;
        }
        protected virtual decimal?GetUnitCostByExpenseItem(PXCache cache, EPExpenseClaimDetails receipt)
        {
            var     item = PXSelectorAttribute.Select <InventoryItem.inventoryID>(cache, receipt) as InventoryItem;
            decimal curyStdCost;

            if (item != null && CurrencyInfo.Current != null && CurrencyInfo.Current.CuryRate != null)
            {
                var cost = receipt.ExpenseDate >= item.StdCostDate ? item.StdCost.GetValueOrDefault() : item.LastStdCost.GetValueOrDefault();
                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.curyInfoID>(cache, receipt, cost, out curyStdCost, true);
            }
            else
            {
                curyStdCost = 0m;
            }

            return(curyStdCost);
        }
예제 #9
0
        protected virtual void EPExpenseClaimDetails_InventoryID_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e)
        {
            EPExpenseClaimDetails row = e.Row as EPExpenseClaimDetails;

            InventoryItem item = PXSelectorAttribute.Select <InventoryItem.inventoryID>(cache, row) as InventoryItem;
            decimal       curyStdCost;

            if (item != null && currencyinfo.Current != null && currencyinfo.Current.CuryRate != null)
            {
                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.curyInfoID>(cache, e.Row, item.StdCost.Value, out curyStdCost, true);
            }
            else
            {
                curyStdCost = 0m;
            }
            cache.SetValueExt <EPExpenseClaimDetails.curyUnitCost>(row, curyStdCost);
        }
예제 #10
0
        /// <summary>
        /// Calculates Unit Cost.
        /// </summary>
        /// <param name="sender">Cache</param>
        /// <param name="inventoryID">Inventory</param>
        /// <param name="curyID">Currency</param>
        /// <param name="UOM">Unit of measure</param>
        /// <param name="date">Date</param>
        /// <returns>Unit Cost</returns>
        public static decimal?CalculateUnitCost(PXCache sender, int?vendorID, int?vendorLocationID, int?inventoryID, CurrencyInfo currencyinfo, string UOM, decimal?quantity, DateTime date, decimal?currentUnitCost, bool alwaysFromBaseCurrency = false)
        {
            InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(sender.Graph, inventoryID);

            UnitCostItem ucItem = FindUnitCost(sender, vendorID, vendorLocationID, inventoryID, alwaysFromBaseCurrency ? currencyinfo.BaseCuryID : currencyinfo.CuryID, Math.Abs(quantity ?? 0m), UOM, date);

            if (ucItem != null)
            {
                decimal unitCost = ucItem.Cost;

                if (ucItem.CuryID != currencyinfo.CuryID)
                {
                    PXCurrencyAttribute.CuryConvCury(sender, currencyinfo, ucItem.Cost, out unitCost);
                }

                if (UOM == null)
                {
                    return(null);
                }

                if (ucItem.UOM != UOM)
                {
                    decimal salesPriceInBase = INUnitAttribute.ConvertFromBase(sender, inventoryID, ucItem.UOM, unitCost, INPrecision.UNITCOST);
                    unitCost = INUnitAttribute.ConvertToBase(sender, inventoryID, UOM, salesPriceInBase, INPrecision.UNITCOST);
                }

                if (unitCost == 0m && currentUnitCost != null && currentUnitCost != 0m)
                {
                    return(currentUnitCost);
                }
                else
                {
                    return(unitCost);
                }
            }

            if (currentUnitCost != null && currentUnitCost != 0m)
            {
                return(currentUnitCost);
            }
            else
            {
                return(null);
            }
        }
예제 #11
0
        protected virtual void EPExpenseClaimDetails_InventoryID_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e)
        {
            EPExpenseClaimDetails row = e.Row as EPExpenseClaimDetails;

            InventoryItem item = PXSelectorAttribute.Select <InventoryItem.inventoryID>(cache, row) as InventoryItem;
            decimal       curyStdCost;

            if (item != null && currencyinfo.Current != null && currencyinfo.Current.CuryRate != null)
            {
                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.curyInfoID>(cache, e.Row, item.StdCost.Value, out curyStdCost, true);
            }
            else
            {
                curyStdCost = 0m;
            }
            cache.SetValueExt <EPExpenseClaimDetails.curyUnitCost>(row, curyStdCost);
            if (item != null && (epsetup.Current.AllowMixedTaxSettingInClaims == true || CurrentClaimDetails.Current.RefNbr == null))
            {
                cache.SetValueExt <EPExpenseClaimDetails.taxCalcMode>(row, item.TaxCalcMode);
            }
        }
            public decimal Convert <InventoryIDField, CuryInfoIDField>(PXGraph graph, object inventoryRow, object curyRow, string uom)
                where InventoryIDField : IBqlField
                where CuryInfoIDField : IBqlField
            {
                ItemCost price = this;

                if (price == null || price.Cost == 0 || price.Item == null || inventoryRow == null || curyRow == null)
                {
                    return(0);
                }

                decimal result = price.Cost;

                if (ConvertCury)
                {
                    PXCache curyCache = graph.Caches[curyRow.GetType()];
                    PXCurrencyAttribute.CuryConvCury <CuryInfoIDField>(curyCache, curyRow, price.BaseCost, out result, true);
                }

                if (price.UOM != uom && !string.IsNullOrEmpty(uom))
                {
                    if (inventoryRow == null)
                    {
                        return(0);
                    }

                    PXCache invCache = graph.Caches[inventoryRow.GetType()];
                    decimal baseUOM  =
                        price.UOM != price.Item.BaseUnit ?
                        INUnitAttribute.ConvertFromBase <InventoryIDField>(invCache, inventoryRow, price.UOM, result, INPrecision.UNITCOST) :
                        result;

                    result =
                        uom != price.Item.BaseUnit ?
                        INUnitAttribute.ConvertToBase <InventoryIDField>(invCache, inventoryRow, uom, baseUOM, INPrecision.UNITCOST) :
                        baseUOM;
                }

                return(result);
            }
예제 #13
0
        protected virtual void _(Events.FieldDefaulting <POAdjust, POAdjust.curyAdjgAmt> eventArgs)
        {
            if (eventArgs.Row == null)
            {
                return;
            }

            var order = POOrder.PK.Find(Base, eventArgs.Row.AdjdOrderType, eventArgs.Row.AdjdOrderNbr);

            if (order != null)
            {
                if (order.CuryID == Base.Document.Current.CuryID)
                {
                    eventArgs.NewValue = order.CuryUnprepaidTotal;
                }
                else
                {
                    PXCurrencyAttribute.CuryConvCury(Base.Document.Cache, Base.Document.Current, order.UnprepaidTotal ?? 0, out decimal curyamount);
                    eventArgs.NewValue = curyamount;
                }
            }
        }
        /// <summary>
        /// Calculates Sales Price.
        /// </summary>
        /// <param name="sender">Cache</param>
        /// <param name="inventoryID">Inventory</param>
        /// <param name="curyID">Currency</param>
        /// <param name="UOM">Unit of measure</param>
        /// <param name="date">Date</param>
        /// <param name="alwaysFromBaseCurrency">If true sales price is always calculated (converted) from Base Currency.</param>
        /// <returns>Sales Price.</returns>
        public static decimal?CalculateSalesPrice(PXCache sender, string custPriceClass, int?customerID, int?inventoryID, CurrencyInfo currencyinfo, decimal?quantity, string UOM, DateTime date, bool alwaysFromBaseCurrency)
        {
            //InventoryItem item = PXSelect<InventoryItem, Where<InventoryItem.inventoryID, Equal<Required<InventoryItem.inventoryID>>>>.Select(sender.Graph, inventoryID);
            SalesPriceItem spItem;

            try
            {
                spItem = FindSalesPrice(sender, custPriceClass, customerID, inventoryID, alwaysFromBaseCurrency ? currencyinfo.BaseCuryID : currencyinfo.CuryID, Math.Abs(quantity ?? 0m), UOM, date);
            }
            catch (PXUnitConversionException)
            {
                return(null);
            }

            if (spItem != null)
            {
                decimal salesPrice = spItem.Price;

                if (spItem.CuryID != currencyinfo.CuryID)
                {
                    PXCurrencyAttribute.CuryConvCury(sender, currencyinfo, spItem.Price, out salesPrice);
                }

                if (UOM == null)
                {
                    return(null);
                }

                if (spItem.UOM != UOM)
                {
                    decimal salesPriceInBase = INUnitAttribute.ConvertFromBase(sender, inventoryID, spItem.UOM, salesPrice, INPrecision.UNITCOST);
                    salesPrice = INUnitAttribute.ConvertToBase(sender, inventoryID, UOM, salesPriceInBase, INPrecision.UNITCOST);
                }

                return(salesPrice);
            }

            return(null);
        }
        public static Decimal ConventCury(PXGraph graph, string curyRateTypeID, string curyID, decimal curyCost, string destinationCuryID)
        {
            if (curyID == destinationCuryID)
            {
                return(curyCost);
            }

            Decimal baseCost   = curyCost;
            string  BaseCuryID = new PXSetup <Company>(graph).Current.BaseCuryID;

            if (curyID != BaseCuryID)
            {
                PXCurrencyAttribute.CuryConvBase(graph.Caches[typeof(CurrencyInfo)], GetCurrencyInfo(graph, curyRateTypeID, curyID), curyCost, out baseCost, true);
            }
            Decimal cost = baseCost;

            if (destinationCuryID != BaseCuryID)
            {
                PXCurrencyAttribute.CuryConvCury(graph.Caches[typeof(CurrencyInfo)], GetCurrencyInfo(graph, curyRateTypeID, destinationCuryID), baseCost, out cost, true);
            }
            return(cost);
        }
예제 #16
0
        protected virtual void EPExpenseClaimDetails_InventoryID_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e)
        {
            EPExpenseClaimDetails tran = e.Row as EPExpenseClaimDetails;

            cache.SetDefaultExt <EPExpenseClaimDetails.taxCategoryID>(e.Row);

            InventoryItem item = PXSelectorAttribute.Select <InventoryItem.inventoryID>(cache, tran) as InventoryItem;

            if (item != null && tran != null)
            {
                decimal curyStdCost;
                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.curyInfoID>(currencyinfo.Cache, e.Row, item.StdCost.Value, out curyStdCost);

                tran.ExpenseAccountID = item.COGSAcctID;
                tran.UOM          = item.PurchaseUnit;
                tran.CuryUnitCost = curyStdCost;
                tran.TranDesc     = item.Descr;

                if (tran.Billable == true)
                {
                    tran.SalesAccountID = item.SalesAcctID;
                }
            }
        }
예제 #17
0
        private InvoiceTran AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>
            (TAPDocumentGraphExtension apDocumentGraphExtension,
            TGraph docgraph,
            ExpenseClaimEntry expenseClaimGraph,
            TAPDocument invoice,
            decimal signOperation,
            EPExpenseClaimDetails claimdetail,
            InvoiceTran tran,
            bool isTipTran)
            where TGraph : PXGraph, new()
            where TAPDocument : InvoiceBase, new()
            where TInvoiceMapping : IBqlMapping
            where TAPDocumentGraphExtension : PX.Objects.Common.GraphExtensions.Abstract.InvoiceBaseGraphExtension <TGraph, TAPDocument, TInvoiceMapping>

        {
            var cmdEPTaxTran = new PXSelect <EPTaxTran,
                                             Where <EPTaxTran.claimDetailID, Equal <Required <EPTaxTran.claimDetailID> > > >(docgraph);

            var cmdEPTax = new PXSelect <EPTax,
                                         Where <EPTax.claimDetailID, Equal <Required <EPTax.claimDetailID> >,
                                                And <EPTax.taxID, Equal <Required <EPTax.taxID> > > > >(docgraph);

            if (isTipTran)
            {
                cmdEPTaxTran.WhereAnd <Where <EPTaxTran.isTipTax, Equal <True> > >();
                cmdEPTax.WhereAnd <Where <EPTax.isTipTax, Equal <True> > >();
            }
            else
            {
                cmdEPTaxTran.WhereAnd <Where <EPTaxTran.isTipTax, Equal <False> > >();
                cmdEPTax.WhereAnd <Where <EPTax.isTipTax, Equal <False> > >();
            }

            CurrencyInfo expenseCuriInfo = PXSelect <CurrencyInfo,
                                                     Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(docgraph, null, claimdetail.CuryInfoID);

            CurrencyInfo currencyinfo = PXSelect <CurrencyInfo,
                                                  Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(docgraph, null, claimdetail.ClaimCuryInfoID);

            foreach (EPTaxTran epTaxTran in cmdEPTaxTran.Select(claimdetail.ClaimDetailID))
            {
                #region Add taxes
                GenericTaxTran new_aptax = apDocumentGraphExtension.TaxTrans.Search <GenericTaxTran.taxID>(epTaxTran.TaxID);

                if (new_aptax == null)
                {
                    new_aptax       = new GenericTaxTran();
                    new_aptax.TaxID = epTaxTran.TaxID;
                    TaxAttribute.SetTaxCalc <InvoiceTran.taxCategoryID>(apDocumentGraphExtension.InvoiceTrans.Cache, null, TaxCalc.NoCalc);
                    new_aptax = apDocumentGraphExtension.TaxTrans.Insert(new_aptax);
                    if (new_aptax != null)
                    {
                        new_aptax = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                        new_aptax.CuryTaxableAmt = 0m;
                        new_aptax.CuryTaxAmt     = 0m;
                        new_aptax.CuryExpenseAmt = 0m;
                        new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                    }
                }

                if (new_aptax != null)
                {
                    EPTax epTax = cmdEPTax.Select(claimdetail.ClaimDetailID, new_aptax.TaxID);
                    new_aptax                      = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                    new_aptax.TaxRate              = epTaxTran.TaxRate;
                    new_aptax.CuryTaxableAmt       = (new_aptax.CuryTaxableAmt ?? 0m) + epTaxTran.ClaimCuryTaxableAmt * signOperation;
                    new_aptax.CuryTaxAmt           = (new_aptax.CuryTaxAmt ?? 0m) + epTaxTran.ClaimCuryTaxAmt * signOperation;
                    new_aptax.CuryTaxAmtSumm       = new_aptax.CuryTaxAmt;
                    new_aptax.CuryExpenseAmt       = (new_aptax.CuryExpenseAmt ?? 0m) + epTaxTran.ClaimCuryExpenseAmt * signOperation;
                    new_aptax.NonDeductibleTaxRate = epTaxTran.NonDeductibleTaxRate;
                    TaxAttribute.SetTaxCalc <InvoiceTran.taxCategoryID>(apDocumentGraphExtension.InvoiceTrans.Cache, null, TaxCalc.ManualCalc);
                    new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                    //On first inserting APTaxTran APTax line will be created automatically.
                    //However, new APTax will not be inserted on APTaxTran line update, even if we already have more lines.
                    //So, we have to do it manually.
                    LineTax aptax = apDocumentGraphExtension.LineTaxes.Search <LineTax.lineNbr, LineTax.taxID>(tran.LineNbr, new_aptax.TaxID);
                    if (aptax == null)
                    {
                        decimal ClaimCuryTaxableAmt = 0m;
                        decimal ClaimCuryTaxAmt     = 0m;
                        decimal ClaimCuryExpenseAmt = 0m;

                        if (CurrencyHelper.IsSameCury(claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID, expenseCuriInfo, currencyinfo))
                        {
                            ClaimCuryTaxableAmt = epTax.CuryTaxableAmt ?? 0m;
                            ClaimCuryTaxAmt     = epTax.CuryTaxAmt ?? 0m;
                            ClaimCuryExpenseAmt = epTax.CuryExpenseAmt ?? 0m;
                        }
                        else if (currencyinfo?.CuryRate != null)
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.TaxableAmt ?? 0m, out ClaimCuryTaxableAmt);
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.TaxAmt ?? 0m, out ClaimCuryTaxAmt);
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.ExpenseAmt ?? 0m, out ClaimCuryExpenseAmt);
                        }
                        aptax = apDocumentGraphExtension.LineTaxes.Insert(new LineTax()
                        {
                            LineNbr        = tran.LineNbr,
                            TaxID          = new_aptax.TaxID,
                            TaxRate        = epTax.TaxRate,
                            CuryTaxableAmt = ClaimCuryTaxableAmt * signOperation,
                            CuryTaxAmt     = ClaimCuryTaxAmt * signOperation,
                            CuryExpenseAmt = ClaimCuryExpenseAmt * signOperation
                        });
                    }
                    Tax taxRow = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(docgraph, new_aptax.TaxID);

                    if ((taxRow.TaxCalcLevel == CSTaxCalcLevel.Inclusive ||
                         (invoice.TaxCalcMode == TaxCalculationMode.Gross && taxRow.TaxCalcLevel == CSTaxCalcLevel.CalcOnItemAmt)) &&
                        (tran.CuryTaxableAmt == null || tran.CuryTaxableAmt == 0m))
                    {
                        tran.CuryTaxableAmt = epTaxTran.ClaimCuryTaxableAmt * signOperation;
                        tran.CuryTaxAmt     = epTaxTran.ClaimCuryTaxAmt * signOperation;
                        tran = apDocumentGraphExtension.InvoiceTrans.Update(tran);
                    }
                }
                #endregion
            }

            return(tran);
        }
        protected virtual decimal ConvertAmt(string from, string to, string rateType, DateTime effectiveDate, decimal amount)
        {
            if (from == to)
            {
                return(amount);
            }

            decimal result = amount;

            PXCache curyCache = CarrierRatesDummyCuryInfo.Cache;

            using (var rs = new ReadOnlyScope(curyCache))
            {
                if (from == Base.Accessinfo.BaseCuryID)
                {
                    CurrencyInfo ci = new CurrencyInfo();
                    ci.CuryRateTypeID = rateType;
                    ci.CuryID         = to;
                    ci = (CurrencyInfo)curyCache.Insert(ci);
                    ci.SetCuryEffDate(curyCache, effectiveDate);
                    curyCache.Update(ci);
                    PXCurrencyAttribute.CuryConvCury(curyCache, ci, amount, out result);
                    curyCache.Delete(ci);
                }
                else if (to == Base.Accessinfo.BaseCuryID)
                {
                    CurrencyInfo ci = new CurrencyInfo();
                    ci.CuryRateTypeID = rateType;
                    ci.CuryID         = from;
                    ci = (CurrencyInfo)curyCache.Insert(ci);
                    ci.SetCuryEffDate(curyCache, effectiveDate);
                    curyCache.Update(ci);
                    PXCurrencyAttribute.CuryConvBase(curyCache, ci, amount, out result);
                    curyCache.Delete(ci);
                }
                else
                {
                    CurrencyInfo ciFrom = new CurrencyInfo();
                    ciFrom.CuryRateTypeID = rateType;
                    ciFrom.CuryID         = from;
                    ciFrom = (CurrencyInfo)curyCache.Insert(ciFrom);
                    ciFrom.SetCuryEffDate(curyCache, effectiveDate);
                    curyCache.Update(ciFrom);
                    decimal inBase;
                    PXCurrencyAttribute.CuryConvBase(curyCache, ciFrom, amount, out inBase, true);

                    CurrencyInfo ciTo = new CurrencyInfo();
                    ciTo.CuryRateTypeID = rateType;
                    ciTo.CuryID         = to;
                    ciTo = (CurrencyInfo)curyCache.Insert(ciTo);
                    ciTo.SetCuryEffDate(curyCache, effectiveDate);
                    curyCache.Update(ciFrom);
                    PXCurrencyAttribute.CuryConvCury(curyCache, ciTo, inBase, out result, true);

                    curyCache.Delete(ciFrom);
                    curyCache.Delete(ciTo);
                }
            }

            return(result);
        }
예제 #19
0
        public static void ReleaseDoc(EPExpenseClaim claim)
        {
            #region prepare required variables
            APInvoiceEntry    docgraph          = PXGraph.CreateInstance <APInvoiceEntry>();
            ExpenseClaimEntry expenseClaimGraph = PXGraph.CreateInstance <ExpenseClaimEntry>();


            var receipts = PXSelect <EPExpenseClaimDetails,
                                     Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr).Select(
                result => (EPExpenseClaimDetails)result).GroupBy(
                item => Tuple.Create(
                    item.TaxZoneID,
                    item.TaxCalcMode
                    )).ToDictionary(x => x.Key, group => group.ToList());

            if (receipts.Count() == 0)
            {
                receipts.Add(Tuple.Create(claim.TaxZoneID, claim.TaxCalcMode), new List <EPExpenseClaimDetails>());
            }
            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

            APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph);

            EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID);

            Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();
            #endregion

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (var res in receipts)
                {
                    docgraph.Clear(PXClearOption.ClearAll);
                    docgraph.SelectTimeStamp();
                    docgraph.vendor.Current   = employee;
                    docgraph.location.Current = emplocation;

                    CurrencyInfo infoOriginal = PXSelect <CurrencyInfo,
                                                          Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID);

                    CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy(infoOriginal);

                    info.CuryInfoID = null;
                    info            = docgraph.currencyinfo.Insert(info);
                    #region CreateInoiceHeader
                    APInvoice invoice = new APInvoice();


                    bool reversedDocument = false;
                    if (res.Value.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0)
                    {
                        invoice.DocType  = APInvoiceType.DebitAdj;
                        reversedDocument = true;
                    }
                    else
                    {
                        invoice.DocType = APInvoiceType.Invoice;
                    }
                    decimal signOperation;
                    if (reversedDocument)
                    {
                        signOperation = -1;
                    }
                    else
                    {
                        signOperation = 1;
                    }

                    invoice.CuryInfoID = info.CuryInfoID;

                    invoice.Hold     = true;
                    invoice.Released = false;
                    invoice.Printed  = false;
                    invoice.OpenDoc  = true;

                    invoice.DocDate          = claim.DocDate;
                    invoice.FinPeriodID      = claim.FinPeriodID;
                    invoice.InvoiceNbr       = claim.RefNbr;
                    invoice.DocDesc          = claim.DocDesc;
                    invoice.VendorID         = claim.EmployeeID;
                    invoice.CuryID           = info.CuryID;
                    invoice.VendorLocationID = claim.LocationID;
                    invoice.APAccountID      = emplocation != null ? emplocation.APAccountID : null;
                    invoice.APSubID          = emplocation != null ? emplocation.APSubID : null;
                    invoice.TaxZoneID        = res.Key.Item1;
                    invoice.TaxCalcMode      = res.Key.Item2;
                    invoice.BranchID         = claim.BranchID;
                    invoice.OrigModule       = BatchModule.EP;
                    invoice.OrigRefNbr       = claim.RefNbr;

                    invoice = docgraph.Document.Insert(invoice);

                    PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                    info.CuryInfoID = invoice.CuryInfoID;

                    PXCache claimcache       = docgraph.Caches[typeof(EPExpenseClaim)];
                    PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)];

                    PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, docgraph.Document.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    #endregion
                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID, APTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    decimal?claimCuryTaxRoundDiff = 0m;
                    decimal?claimTaxRoundDiff     = 0m;
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        #region AddDetails

                        decimal tipQty;
                        if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                        {
                            tipQty = 1;
                        }
                        else
                        {
                            tipQty = -1;
                        }
                        Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

                        if (claimdetail.TaskID != null)
                        {
                            PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, claimdetail.TaskID);

                            if (task != null && !(bool)task.VisibleInAP)
                            {
                                throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP);
                            }
                        }

                        APTran tran = new APTran();
                        tran.InventoryID = claimdetail.InventoryID;
                        tran.TranDesc    = claimdetail.TranDesc;
                        decimal unitCost;
                        decimal amount;
                        decimal taxableAmt;
                        decimal taxAmt;
                        if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            unitCost   = claimdetail.CuryUnitCost ?? 0m;
                            amount     = claimdetail.CuryTaxableAmt ?? 0m;
                            taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                            taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                        }
                        else
                        {
                            if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                            {
                                unitCost = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                            }
                            if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                            {
                                amount = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                            }
                            if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                            {
                                taxableAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                            }
                            if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                            {
                                taxAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                            }
                        }

                        tran.ManualPrice       = true;
                        tran.CuryUnitCost      = unitCost;
                        tran.Qty               = claimdetail.Qty * signOperation;
                        tran.UOM               = claimdetail.UOM;
                        tran.NonBillable       = claimdetail.Billable != true;
                        claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                        claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                        tran.Date              = claimdetail.ExpenseDate;

                        if (contract.BaseType == PMProject.ProjectBaseType.Project)
                        {
                            tran.ProjectID = claimdetail.ContractID;
                        }
                        else
                        {
                            tran.ProjectID = ProjectDefaultAttribute.NonProject();
                        }

                        tran.TaskID        = claimdetail.TaskID;
                        tran.CostCodeID    = claimdetail.CostCodeID;
                        tran.AccountID     = claimdetail.ExpenseAccountID;
                        tran.SubID         = claimdetail.ExpenseSubID;
                        tran.TaxCategoryID = claimdetail.TaxCategoryID;
                        tran.BranchID      = claimdetail.BranchID;
                        tran                = docgraph.Transactions.Insert(tran);
                        tran.CuryLineAmt    = amount * signOperation;
                        tran.CuryTaxAmt     = 0;
                        tran.CuryTaxableAmt = taxableAmt * signOperation;
                        tran.CuryTaxAmt     = taxAmt * signOperation;
                        tran                = docgraph.Transactions.Update(tran);


                        if ((claimdetail.CuryTipAmt ?? 0) != 0)
                        {
                            APTran tranTip = new APTran();
                            if (epsetup.NonTaxableTipItem == null)
                            {
                                throw new PXException(Messages.TipItemIsNotDefined);
                            }
                            IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                                 Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                            if (tipItem == null)
                            {
                                string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                                throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                            }
                            tranTip.InventoryID = epsetup.NonTaxableTipItem;
                            tranTip.TranDesc    = tipItem.Descr;
                            if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                            {
                                tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                                tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                            }
                            else
                            {
                                decimal tipAmt;
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                                tranTip.CuryUnitCost = Math.Abs(tipAmt);
                                tranTip.CuryTranAmt  = tipAmt * signOperation;
                            }
                            tranTip.Qty         = tipQty;
                            tranTip.UOM         = tipItem.BaseUnit;
                            tranTip.NonBillable = claimdetail.Billable != true;
                            tranTip.Date        = claimdetail.ExpenseDate;

                            tranTip.BranchID = claimdetail.BranchID;
                            tranTip          = docgraph.Transactions.Insert(tranTip);

                            if (epsetup.UseReceiptAccountForTips == true)
                            {
                                tranTip.AccountID = claimdetail.ExpenseAccountID;
                                tranTip.SubID     = claimdetail.ExpenseSubID;
                            }
                            else
                            {
                                tranTip.AccountID = tipItem.COGSAcctID;
                                Location companyloc = (Location)PXSelectJoin <Location,
                                                                              InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                        And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                         InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                              Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                                PMTask task = PXSelect <PMTask,
                                                        Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                               And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                                Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                                int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                                int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                                int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                                int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                                int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                                int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                                object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                        new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                        new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                                docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                                tranTip.SubID = (int?)value;
                            }
                            tranTip = docgraph.Transactions.Update(tranTip);
                            tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                            tranTip.ProjectID     = tran.ProjectID;
                            tranTip.TaskID        = tran.TaskID;
                            tranTip = AddTaxes(docgraph, invoice, signOperation, claimdetail, tranTip, true);
                            tranTip = docgraph.Transactions.Update(tranTip);
                        }

                        PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, docgraph.Transactions.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                        claimdetail.Released = true;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                        #endregion


                        tran = AddTaxes(docgraph, invoice, signOperation, claimdetail, tran, false);
                    }

                    #region legacy taxes
                    foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                     Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                    {
                        #region Add taxes
                        APTaxTran new_aptax = docgraph.Taxes.Search <APTaxTran.taxID>(tax.TaxID);

                        if (new_aptax == null)
                        {
                            new_aptax       = new APTaxTran();
                            new_aptax.TaxID = tax.TaxID;
                            new_aptax       = docgraph.Taxes.Insert(new_aptax);
                            if (new_aptax != null)
                            {
                                new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                                new_aptax.CuryTaxableAmt = 0m;
                                new_aptax.CuryTaxAmt     = 0m;
                                new_aptax.CuryExpenseAmt = 0m;
                                new_aptax = docgraph.Taxes.Update(new_aptax);
                            }
                        }

                        if (new_aptax != null)
                        {
                            new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                            new_aptax.TaxRate        = tax.TaxRate;
                            new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                            new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                            new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                            new_aptax = docgraph.Taxes.Update(new_aptax);
                        }
                        #endregion
                    }
                    #endregion

                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                    invoice.Hold           = false;
                    docgraph.Document.Update(invoice);
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (APTran line in docgraph.Transactions.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }

                    docgraph.Document.Update(invoice);
                    docgraph.Save.Press();
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        claimdetail.APDocType = invoice.DocType;
                        claimdetail.APRefNbr  = invoice.RefNbr;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    }
                    claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                    claim.Released = true;
                    expenseClaimGraph.ExpenseClaim.Update(claim);

                    #region EP History Update
                    EPHistory hist = new EPHistory();
                    hist.EmployeeID  = invoice.VendorID;
                    hist.FinPeriodID = invoice.FinPeriodID;
                    hist             = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(hist);

                    hist.FinPtdClaimed += invoice.DocBal;
                    hist.FinYtdClaimed += invoice.DocBal;
                    if (invoice.FinPeriodID == invoice.TranPeriodID)
                    {
                        hist.TranPtdClaimed += invoice.DocBal;
                        hist.TranYtdClaimed += invoice.DocBal;
                    }
                    else
                    {
                        EPHistory tranhist = new EPHistory();
                        tranhist.EmployeeID      = invoice.VendorID;
                        tranhist.FinPeriodID     = invoice.TranPeriodID;
                        tranhist                 = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist);
                        tranhist.TranPtdClaimed += invoice.DocBal;
                        tranhist.TranYtdClaimed += invoice.DocBal;
                    }
                    expenseClaimGraph.Views.Caches.Add(typeof(EPHistory));
                    #endregion

                    expenseClaimGraph.Save.Press();

                    doclist.Add(docgraph.Document.Current);
                }

                ts.Complete();
            }

            if ((bool)epsetup.AutomaticReleaseAP == true)
            {
                APDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
        public virtual void RecalcAmountInClaimCury(EPExpenseClaimDetails receipt)
        {
            if (receipt != null && receipt.TranAmt != null && receipt.TranAmtWithTaxes != null)
            {
                decimal curyClaim           = 0m;
                decimal curyClaimWithTaxes  = 0m;
                decimal curyClaimTax        = 0m;
                decimal curyTaxRoundDiff    = 0m;
                decimal curyVatExemptTotal  = 0m;
                decimal curyVatTaxableTotal = 0m;

                if (!receipt.IsPaidWithCard || receipt.IsPaidWithCard && receipt.CorpCardID != null)
                {
                    PXCache      taxTranCache    = Base.Caches[typeof(EPTaxTran)];
                    CurrencyInfo expenseCuriInfo = PXSelect <CurrencyInfo,
                                                             Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(Base, null, receipt.CuryInfoID);

                    CurrencyInfo currencyinfo = PXSelect <CurrencyInfo,
                                                          Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(Base, null, receipt.ClaimCuryInfoID);

                    if (CurrencyHelper.IsSameCury(receipt.CuryInfoID, receipt.ClaimCuryInfoID, expenseCuriInfo, currencyinfo))
                    {
                        curyClaim           = receipt.CuryTranAmt ?? 0m;
                        curyClaimWithTaxes  = receipt.CuryTranAmtWithTaxes ?? 0m;
                        curyClaimTax        = receipt.CuryTaxTotal ?? 0m;
                        curyTaxRoundDiff    = receipt.CuryTaxRoundDiff ?? 0m;
                        curyVatExemptTotal  = receipt.CuryVatExemptTotal ?? 0m;
                        curyVatTaxableTotal = receipt.CuryVatTaxableTotal ?? 0m;
                        foreach (EPTaxTran copy in PXSelect <EPTaxTran,
                                                             Where <EPTaxTran.claimDetailID, Equal <Required <EPExpenseClaimDetails.claimDetailID> > > > .Select(Base, receipt.ClaimDetailID))
                        {
                            if (taxTranCache.GetStatus(copy) != PXEntryStatus.Inserted)
                            {
                                taxTranCache.SetStatus(copy, PXEntryStatus.Updated);
                            }
                            taxTranCache.SetValue <EPTaxTran.claimCuryExpenseAmt>(copy, copy.CuryExpenseAmt ?? 0m);
                            taxTranCache.SetValue <EPTaxTran.claimCuryTaxableAmt>(copy, copy.CuryTaxableAmt ?? 0m);
                            taxTranCache.SetValue <EPTaxTran.claimCuryTaxAmt>(copy, copy.CuryTaxAmt ?? 0m);
                        }
                    }
                    else if (currencyinfo?.CuryRate != null)
                    {
                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, receipt.TranAmt ?? 0m, out curyClaim);
                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, receipt.TranAmtWithTaxes ?? 0m, out curyClaimWithTaxes);
                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, receipt.TaxTotal ?? 0m, out curyClaimTax);
                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, receipt.TaxRoundDiff ?? 0m, out curyTaxRoundDiff);
                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, receipt.VatExemptTotal ?? 0m, out curyVatExemptTotal);
                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, receipt.VatTaxableTotal ?? 0m, out curyVatTaxableTotal);
                        foreach (EPTaxTran copy in PXSelect <EPTaxTran,
                                                             Where <EPTaxTran.claimDetailID, Equal <Required <EPExpenseClaimDetails.claimDetailID> > > > .Select(Base, receipt.ClaimDetailID))
                        {
                            if (taxTranCache.GetStatus(copy) != PXEntryStatus.Inserted)
                            {
                                taxTranCache.SetStatus(copy, PXEntryStatus.Updated);
                            }
                            decimal newValue;
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, copy.ExpenseAmt ?? 0m, out newValue);
                            taxTranCache.SetValue <EPTaxTran.claimCuryExpenseAmt>(copy, newValue);

                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, copy.TaxableAmt ?? 0m, out newValue);
                            taxTranCache.SetValue <EPTaxTran.claimCuryTaxableAmt>(copy, newValue);

                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(Receipts.Cache, receipt, copy.TaxAmt ?? 0m, out newValue);
                            taxTranCache.SetValue <EPTaxTran.claimCuryTaxAmt>(copy, newValue);
                        }
                    }
                }

                EPExpenseClaimDetails oldReceipt = (EPExpenseClaimDetails)Receipts.Cache.CreateCopy(receipt);

                receipt.ClaimCuryTranAmt          = curyClaim;
                receipt.ClaimCuryTranAmtWithTaxes = curyClaimWithTaxes;
                receipt.ClaimCuryTaxTotal         = curyClaimTax;
                receipt.ClaimCuryTaxRoundDiff     = curyTaxRoundDiff;
                receipt.ClaimCuryVatExemptTotal   = curyVatExemptTotal;
                receipt.ClaimCuryVatTaxableTotal  = curyVatTaxableTotal;

                if (Claim != null && receipt.RefNbr != null)
                {
                    EPExpenseClaim claim = GetParentClaim(receipt.RefNbr);

                    SumClaimValues(claim, receipt, oldReceipt);
                }
            }
        }
예제 #21
0
        public static void RecalcAmountInClaimCury(PXCache receiptsCache, EPExpenseClaimDetails receipt)
        {
            if (receipt != null && receipt.TranAmt != null && receipt.TranAmtWithTaxes != null && receipt.RefNbr != null)
            {
                PXGraph      graph           = receiptsCache.Graph;
                PXCache      taxTranCache    = graph.Caches[typeof(EPTaxTran)];
                CurrencyInfo expenseCuriInfo = PXSelect <CurrencyInfo,
                                                         Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(graph, null, receipt.CuryInfoID);

                CurrencyInfo currencyinfo = PXSelect <CurrencyInfo,
                                                      Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(graph, null, receipt.ClaimCuryInfoID);

                decimal curyClaim           = 0m;
                decimal curyClaimWithTaxes  = 0m;
                decimal curyClaimTax        = 0m;
                decimal curyTaxRoundDiff    = 0m;
                decimal curyVatExemptTotal  = 0m;
                decimal curyVatTaxableTotal = 0m;

                if (IsSameCury(receipt.CuryInfoID, receipt.ClaimCuryInfoID, expenseCuriInfo, currencyinfo))
                {
                    curyClaim           = receipt.CuryTranAmt ?? 0m;
                    curyClaimWithTaxes  = receipt.CuryTranAmtWithTaxes ?? 0m;
                    curyClaimTax        = receipt.CuryTaxTotal ?? 0m;
                    curyTaxRoundDiff    = receipt.CuryTaxRoundDiff ?? 0m;
                    curyVatExemptTotal  = receipt.CuryVatExemptTotal ?? 0m;
                    curyVatTaxableTotal = receipt.CuryVatTaxableTotal ?? 0m;
                    foreach (EPTaxTran copy in PXSelect <EPTaxTran,
                                                         Where <EPTaxTran.claimDetailID, Equal <Required <EPExpenseClaimDetails.claimDetailID> > > > .Select(receiptsCache.Graph, receipt.ClaimDetailID))
                    {
                        if (taxTranCache.GetStatus(copy) != PXEntryStatus.Inserted)
                        {
                            taxTranCache.SetStatus(copy, PXEntryStatus.Updated);
                        }
                        taxTranCache.SetValue <EPTaxTran.claimCuryExpenseAmt>(copy, copy.CuryExpenseAmt ?? 0m);
                        taxTranCache.SetValue <EPTaxTran.claimCuryTaxableAmt>(copy, copy.CuryTaxableAmt ?? 0m);
                        taxTranCache.SetValue <EPTaxTran.claimCuryTaxAmt>(copy, copy.CuryTaxAmt ?? 0m);
                    }
                }
                else if (currencyinfo?.CuryRate != null)
                {
                    PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, receipt.TranAmt ?? 0m, out curyClaim);
                    PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, receipt.TranAmtWithTaxes ?? 0m, out curyClaimWithTaxes);
                    PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, receipt.TaxTotal ?? 0m, out curyClaimTax);
                    PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, receipt.TaxRoundDiff ?? 0m, out curyTaxRoundDiff);
                    PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, receipt.VatExemptTotal ?? 0m, out curyVatExemptTotal);
                    PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, receipt.VatTaxableTotal ?? 0m, out curyVatTaxableTotal);
                    foreach (EPTaxTran copy in PXSelect <EPTaxTran,
                                                         Where <EPTaxTran.claimDetailID, Equal <Required <EPExpenseClaimDetails.claimDetailID> > > > .Select(receiptsCache.Graph, receipt.ClaimDetailID))
                    {
                        if (taxTranCache.GetStatus(copy) != PXEntryStatus.Inserted)
                        {
                            taxTranCache.SetStatus(copy, PXEntryStatus.Updated);
                        }
                        decimal newValue;
                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, copy.ExpenseAmt ?? 0m, out newValue);
                        taxTranCache.SetValue <EPTaxTran.claimCuryExpenseAmt>(copy, newValue);

                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, copy.TaxableAmt ?? 0m, out newValue);
                        taxTranCache.SetValue <EPTaxTran.claimCuryTaxableAmt>(copy, newValue);

                        PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(receiptsCache, receipt, copy.TaxAmt ?? 0m, out newValue);
                        taxTranCache.SetValue <EPTaxTran.claimCuryTaxAmt>(copy, newValue);
                    }
                }
                receipt.ClaimCuryTranAmt          = curyClaim;
                receipt.ClaimCuryTranAmtWithTaxes = curyClaimWithTaxes;
                receipt.ClaimCuryTaxTotal         = curyClaimTax;
                receipt.ClaimCuryTaxRoundDiff     = curyTaxRoundDiff;
                receipt.ClaimCuryVatExemptTotal   = curyVatExemptTotal;
                receipt.ClaimCuryVatTaxableTotal  = curyVatTaxableTotal;
            }
        }
        private static APTran AddTaxes(APInvoiceEntry docgraph, ExpenseClaimEntry expenseClaimGraph, APInvoice invoice, decimal signOperation, EPExpenseClaimDetails claimdetail, APTran tran, bool isTipTran)
        {
            var cmdEPTaxTran = new PXSelect <EPTaxTran,
                                             Where <EPTaxTran.claimDetailID, Equal <Required <EPTaxTran.claimDetailID> > > >(docgraph);

            var cmdEPTax = new PXSelect <EPTax,
                                         Where <EPTax.claimDetailID, Equal <Required <EPTax.claimDetailID> >,
                                                And <EPTax.taxID, Equal <Required <EPTax.taxID> > > > >(docgraph);

            if (isTipTran)
            {
                cmdEPTaxTran.WhereAnd <Where <EPTaxTran.isTipTax, Equal <True> > >();
                cmdEPTax.WhereAnd <Where <EPTax.isTipTax, Equal <True> > >();
            }
            else
            {
                cmdEPTaxTran.WhereAnd <Where <EPTaxTran.isTipTax, Equal <False> > >();
                cmdEPTax.WhereAnd <Where <EPTax.isTipTax, Equal <False> > >();
            }

            CurrencyInfo expenseCuriInfo = PXSelect <CurrencyInfo,
                                                     Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(docgraph, null, claimdetail.CuryInfoID);

            CurrencyInfo currencyinfo = PXSelect <CurrencyInfo,
                                                  Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(docgraph, null, claimdetail.ClaimCuryInfoID);

            foreach (EPTaxTran epTaxTran in cmdEPTaxTran.Select(claimdetail.ClaimDetailID))
            {
                #region Add taxes
                APTaxTran new_aptax = docgraph.Taxes.Search <APTaxTran.taxID>(epTaxTran.TaxID);

                if (new_aptax == null)
                {
                    new_aptax       = new APTaxTran();
                    new_aptax.TaxID = epTaxTran.TaxID;
                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.NoCalc);
                    new_aptax = docgraph.Taxes.Insert(new_aptax);
                    if (new_aptax != null)
                    {
                        new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                        new_aptax.CuryTaxableAmt = 0m;
                        new_aptax.CuryTaxAmt     = 0m;
                        new_aptax.CuryExpenseAmt = 0m;
                        new_aptax = docgraph.Taxes.Update(new_aptax);
                    }
                }

                if (new_aptax != null)
                {
                    new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                    new_aptax.TaxRate        = epTaxTran.TaxRate;
                    new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + epTaxTran.ClaimCuryTaxableAmt * signOperation;
                    new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + epTaxTran.ClaimCuryTaxAmt * signOperation;
                    new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + epTaxTran.ClaimCuryExpenseAmt * signOperation;
                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    new_aptax = docgraph.Taxes.Update(new_aptax);
                    //On first inserting APTaxTran APTax line will be created automatically.
                    //However, new APTax will not be inserted on APTaxTran line update, even if we already have more lines.
                    //So, we have to do it manually.
                    APTax aptax = docgraph.Tax_Rows.Search <APTax.lineNbr, APTax.taxID>(tran.LineNbr, new_aptax.TaxID);
                    if (aptax == null)
                    {
                        EPTax   epTax = cmdEPTax.Select(claimdetail.ClaimDetailID, new_aptax.TaxID);
                        decimal ClaimCuryTaxableAmt = 0m;
                        decimal ClaimCuryTaxAmt     = 0m;
                        decimal ClaimCuryExpenseAmt = 0m;

                        if (EPClaimReceiptController.IsSameCury(claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID, expenseCuriInfo, currencyinfo))
                        {
                            ClaimCuryTaxableAmt = epTax.CuryTaxableAmt ?? 0m;
                            ClaimCuryTaxAmt     = epTax.CuryTaxAmt ?? 0m;
                            ClaimCuryExpenseAmt = epTax.CuryExpenseAmt ?? 0m;
                        }
                        else if (currencyinfo?.CuryRate != null)
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.TaxableAmt ?? 0m, out ClaimCuryTaxableAmt);
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.TaxAmt ?? 0m, out ClaimCuryTaxAmt);
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.ExpenseAmt ?? 0m, out ClaimCuryExpenseAmt);
                        }
                        aptax = docgraph.Tax_Rows.Insert(new APTax()
                        {
                            LineNbr        = tran.LineNbr,
                            TaxID          = new_aptax.TaxID,
                            TaxRate        = epTax.TaxRate,
                            CuryTaxableAmt = ClaimCuryTaxableAmt * signOperation,
                            CuryTaxAmt     = ClaimCuryTaxAmt * signOperation,
                            CuryExpenseAmt = ClaimCuryExpenseAmt * signOperation
                        });
                    }
                    Tax taxRow = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(docgraph, new_aptax.TaxID);

                    if ((taxRow.TaxCalcLevel == CSTaxCalcLevel.Inclusive ||
                         (invoice.TaxCalcMode == TaxCalculationMode.Gross && taxRow.TaxCalcLevel == CSTaxCalcLevel.CalcOnItemAmt)) &&
                        (tran.CuryTaxableAmt == null || tran.CuryTaxableAmt == 0m))
                    {
                        tran.CuryTaxableAmt = epTaxTran.ClaimCuryTaxableAmt * signOperation;
                        tran.CuryTaxAmt     = epTaxTran.ClaimCuryTaxAmt * signOperation;
                        tran = docgraph.Transactions.Update(tran);
                    }
                }
                #endregion
            }

            return(tran);
        }
예제 #23
0
        public virtual List <APRegister> ReleaseClaimDetails
        <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>
            (ExpenseClaimEntry expenseClaimGraph, EPExpenseClaim claim, IEnumerable <EPExpenseClaimDetails> receipts, string receiptGroupPaidWithType)
            where TGraph : PXGraph, new()
            where TAPDocument : InvoiceBase, new()
            where TInvoiceMapping : IBqlMapping
            where TAPDocumentGraphExtension : PX.Objects.Common.GraphExtensions.Abstract.InvoiceBaseGraphExtension <TGraph, TAPDocument, TInvoiceMapping>
        {
            #region prepare required variable

            var docgraph = PXGraph.CreateInstance <TGraph>();

            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

            TAPDocumentGraphExtension apDocumentGraphExtension = docgraph.FindImplementation <TAPDocumentGraphExtension>();

            List <List <EPExpenseClaimDetails> > receiptsForDocument = new List <List <EPExpenseClaimDetails> >();

            if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
            {
                receiptsForDocument = receipts.GroupBy(item => new { item.TaxZoneID, item.TaxCalcMode })
                                      .Select(group => group.ToList())
                                      .ToList();
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
            {
                if (epsetup.PostSummarizedCorpCardExpenseReceipts == true)
                {
                    receiptsForDocument = receipts.GroupBy(item =>
                                                           new
                    {
                        item.TaxZoneID,
                        item.TaxCalcMode,
                        item.CorpCardID,
                        item.ExpenseDate,
                        item.ExpenseRefNbr
                    })
                                          .Select(group => group.ToList())
                                          .ToList();
                }
                else
                {
                    receiptsForDocument = receipts.Select(receipt => receipt.SingleToList()).ToList();
                }
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
            {
                receiptsForDocument = new List <List <EPExpenseClaimDetails> >()
                {
                    receipts.ToList()
                };
            }
            else
            {
                throw new NotImplementedException();
            }

            if (!receiptsForDocument.Any())
            {
                receiptsForDocument.Add(new List <EPExpenseClaimDetails>());
            }

            APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph);

            EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID);

            Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();


            if (claim.FinPeriodID != null)
            {
                FinPeriodUtils.ValidateFinPeriod(claim.SingleToArray());
            }
            #endregion

            foreach (var receiptGroup in receiptsForDocument)
            {
                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count > 1)
                {
                    EPExpenseClaimDetails[] matchedReceipts = receiptGroup.Where(receipt => receipt.BankTranDate != null).Take(11).ToArray();

                    if (matchedReceipts.Any())
                    {
                        PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran>[] rows =
                            PXSelectJoin <EPExpenseClaimDetails,
                                          InnerJoin <CABankTranMatch,
                                                     On <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                                         And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                              And <CABankTranMatch.docRefNbr, Equal <EPExpenseClaimDetails.claimDetailCD> > > >,
                                                     InnerJoin <CABankTran,
                                                                On <CABankTran.tranID, Equal <CABankTranMatch.tranID> > > >,
                                          Where <EPExpenseClaimDetails.claimDetailCD, In <Required <EPExpenseClaimDetails.claimDetailCD> > > >
                            .Select(expenseClaimGraph, matchedReceipts.Select(receipt => receipt.ClaimDetailCD).ToArray())
                            .Cast <PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran> >()
                            .ToArray();

                        throw new PXException(Messages.ExpenseReceiptCannotBeSummarized,
                                              rows.Select(row => String.Concat(PXMessages.LocalizeNoPrefix(Messages.Receipt),
                                                                               " ",
                                                                               ((EPExpenseClaimDetails)row).ClaimDetailCD,
                                                                               " - ",
                                                                               ((CABankTran)row).GetFriendlyKeyImage(Caches[typeof(CABankTran)])))
                                              .ToArray()
                                              .JoinIntoStringForMessageNoQuotes(maxCount: 10));
                    }
                }

                docgraph.Clear(PXClearOption.ClearAll);
                docgraph.SelectTimeStamp();
                apDocumentGraphExtension.Contragent.Current = apDocumentGraphExtension.Contragent.Cache.GetExtension <Contragent>(employee);
                apDocumentGraphExtension.Location.Current   = emplocation;

                CurrencyInfo infoOriginal = PXSelect <CurrencyInfo,
                                                      Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID);

                CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy(infoOriginal);

                info.CuryInfoID = null;
                info            = apDocumentGraphExtension.CurrencyInfo.Insert(info);

                #region CreateInvoiceHeader

                var invoice = new TAPDocument();

                CABankTranMatch bankTranMatch = null;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
                {
                    invoice.DocType = receiptGroup.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0
                        ? APInvoiceType.DebitAdj
                        : APInvoiceType.Invoice;
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
                {
                    EPExpenseClaimDetails receipt = receiptGroup.First();

                    invoice.DocType = APDocType.QuickCheck;

                    CACorpCard card = CACorpCard.PKID.Find(this, receipt.CorpCardID);

                    PaymentMethodAccount paymentMethodAccount = PXSelect <PaymentMethodAccount,
                                                                          Where <PaymentMethodAccount.cashAccountID, Equal <Required <PaymentMethodAccount.cashAccountID> > > >
                                                                .Select(this, card.CashAccountID);

                    invoice.CashAccountID   = card.CashAccountID;
                    invoice.PaymentMethodID = paymentMethodAccount.PaymentMethodID;
                    invoice.ExtRefNbr       = receipt.ExpenseRefNbr;

                    if (receiptGroup.Count == 1)
                    {
                        bankTranMatch =
                            PXSelect <CABankTranMatch,
                                      Where <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                             And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                  And <CABankTranMatch.docRefNbr, Equal <Required <CABankTranMatch.docRefNbr> > > > > >
                            .Select(expenseClaimGraph, receipt.ClaimDetailCD);

                        if (bankTranMatch != null)
                        {
                            CABankTran bankTran = CABankTran.PK.Find(expenseClaimGraph, bankTranMatch.TranID);

                            invoice.ClearDate = bankTran.ClearDate;
                            invoice.Cleared   = true;
                        }
                    }
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.DocType = APDocType.DebitAdj;
                }
                else
                {
                    throw new NotImplementedException();
                }

                invoice.CuryInfoID = info.CuryInfoID;

                invoice.Hold     = true;
                invoice.Released = false;
                invoice.Printed  = invoice.DocType == APDocType.QuickCheck;
                invoice.OpenDoc  = true;

                invoice.HeaderDocDate        = claim.DocDate;
                invoice.FinPeriodID          = claim.FinPeriodID;
                invoice.InvoiceNbr           = claim.RefNbr;
                invoice.DocDesc              = claim.DocDesc;
                invoice.ContragentID         = claim.EmployeeID;
                invoice.CuryID               = info.CuryID;
                invoice.ContragentLocationID = claim.LocationID;
                invoice.ModuleAccountID      = emplocation != null ? emplocation.APAccountID : null;
                invoice.ModuleSubID          = emplocation != null ? emplocation.APSubID : null;
                invoice.TaxCalcMode          = receiptGroup.Any() ? receiptGroup.First().TaxCalcMode: claim.TaxCalcMode;
                invoice.BranchID             = claim.BranchID;
                invoice.OrigModule           = BatchModule.EP;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1)
                {
                    invoice.OrigDocType = EPExpenseClaimDetails.DocType;
                    invoice.OrigRefNbr  = receiptGroup.Single().ClaimDetailCD;
                }
                else
                {
                    invoice.OrigDocType = EPExpenseClaim.DocType;
                    invoice.OrigRefNbr  = claim.RefNbr;
                }

                bool reversedDocument = invoice.DocType == APInvoiceType.DebitAdj && receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount;

                decimal signOperation = reversedDocument ? -1 : 1;

                invoice = apDocumentGraphExtension.Documents.Insert(invoice);
                (apDocumentGraphExtension.Documents.Cache as PXModelExtension <TAPDocument>)?.UpdateExtensionMapping(invoice, MappingSyncDirection.BaseToExtension);

                invoice.TaxZoneID = receiptGroup.Any() ? receiptGroup.First().TaxZoneID : claim.TaxZoneID;

                invoice = apDocumentGraphExtension.Documents.Update(invoice);

                PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                info.CuryInfoID = invoice.CuryInfoID;

                PXCache claimcache       = docgraph.Caches[typeof(EPExpenseClaim)];
                PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)];

                PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, apDocumentGraphExtension.Documents.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                #endregion

                TaxAttribute.SetTaxCalc <InvoiceTran.taxCategoryID>(apDocumentGraphExtension.InvoiceTrans.Cache, null, TaxCalc.ManualCalc);

                decimal?claimCuryTaxRoundDiff = 0m;
                decimal?claimTaxRoundDiff     = 0m;
                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    #region AddDetails

                    decimal tipQty;
                    if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                    {
                        tipQty = 1;
                    }
                    else
                    {
                        tipQty = -1;
                    }
                    Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

                    if (claimdetail.TaskID != null)
                    {
                        PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, claimdetail.TaskID);

                        if (task != null && !(bool)task.VisibleInAP)
                        {
                            throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP);
                        }
                    }

                    InvoiceTran tran = new InvoiceTran();
                    tran.InventoryID = claimdetail.InventoryID;
                    tran.TranDesc    = claimdetail.TranDesc;
                    decimal unitCost;
                    decimal amount;
                    decimal taxableAmt;
                    decimal taxAmt;
                    if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                    {
                        unitCost   = claimdetail.CuryUnitCost ?? 0m;
                        amount     = claimdetail.CuryTaxableAmt ?? 0m;
                        taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                        taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                    }
                    else
                    {
                        if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                        {
                            unitCost = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                        }
                        if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                        {
                            amount = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                        }
                        if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                        {
                            taxableAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                        }
                        if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                        {
                            taxAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                        }
                    }

                    tran.ManualPrice       = true;
                    tran.CuryUnitCost      = unitCost;
                    tran.Qty               = claimdetail.Qty * signOperation;
                    tran.UOM               = claimdetail.UOM;
                    tran.NonBillable       = claimdetail.Billable != true;
                    claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                    claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                    tran.Date              = claimdetail.ExpenseDate;

                    if (contract.BaseType == CT.CTPRType.Project)
                    {
                        tran.ProjectID = claimdetail.ContractID;
                    }
                    else
                    {
                        tran.ProjectID = ProjectDefaultAttribute.NonProject();
                    }

                    tran.TaskID     = claimdetail.TaskID;
                    tran.CostCodeID = claimdetail.CostCodeID;

                    if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        CACorpCard  card        = CACorpCard.PKID.Find(this, claimdetail.CorpCardID);
                        CashAccount cashAccount = CashAccount.PK.Find(this, card.CashAccountID);

                        tran.AccountID = cashAccount.AccountID;
                        tran.SubID     = cashAccount.SubID;
                    }
                    else
                    {
                        tran.AccountID = claimdetail.ExpenseAccountID;
                        tran.SubID     = claimdetail.ExpenseSubID;
                    }

                    tran.BranchID = claimdetail.BranchID;


                    tran = InsertInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });

                    if (claimdetail.PaidWith == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        claimdetail.APLineNbr = tran.LineNbr;
                    }

                    tran.CuryLineAmt    = amount * signOperation;
                    tran.CuryTaxAmt     = 0;
                    tran.CuryTaxableAmt = taxableAmt * signOperation;
                    tran.CuryTaxAmt     = taxAmt * signOperation;
                    tran.TaxCategoryID  = claimdetail.TaxCategoryID;


                    tran = UpdateInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });


                    if ((claimdetail.CuryTipAmt ?? 0) != 0)
                    {
                        InvoiceTran tranTip = new InvoiceTran();
                        if (epsetup.NonTaxableTipItem == null)
                        {
                            throw new PXException(Messages.TipItemIsNotDefined);
                        }
                        IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                             Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                        if (tipItem == null)
                        {
                            string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                            throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                        }
                        tranTip.InventoryID = epsetup.NonTaxableTipItem;
                        tranTip.TranDesc    = tipItem.Descr;
                        if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                            tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                        }
                        else
                        {
                            decimal tipAmt;
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                            tranTip.CuryUnitCost = Math.Abs(tipAmt);
                            tranTip.CuryTranAmt  = tipAmt * signOperation;
                        }
                        tranTip.Qty         = tipQty;
                        tranTip.UOM         = tipItem.BaseUnit;
                        tranTip.NonBillable = claimdetail.Billable != true;
                        tranTip.Date        = claimdetail.ExpenseDate;

                        tranTip.BranchID = claimdetail.BranchID;

                        tranTip = InsertInvoiceTipTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                              new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });


                        if (epsetup.UseReceiptAccountForTips == true)
                        {
                            tranTip.AccountID = claimdetail.ExpenseAccountID;
                            tranTip.SubID     = claimdetail.ExpenseSubID;
                        }
                        else
                        {
                            tranTip.AccountID = tipItem.COGSAcctID;
                            Location companyloc = (Location)PXSelectJoin <Location,
                                                                          InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                    And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                     InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                          Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                            PMTask task = PXSelect <PMTask,
                                                    Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                           And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                            Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                            int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                            int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                            int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                            int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                            int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                            int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                            object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                    new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                    new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                            docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                            tranTip.SubID = (int?)value;
                        }

                        tranTip = UpdateInvoiceTipTransactionAccounts(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                      new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });

                        tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                        tranTip.ProjectID     = tran.ProjectID;
                        tranTip.TaskID        = tran.TaskID;
                        tranTip = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tranTip, true);


                        tranTip = UpdateInvoiceTipTransactionTaxesAndProject(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                             new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });
                    }

                    PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, apDocumentGraphExtension.InvoiceTrans.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    claimdetail.Released = true;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    #endregion

                    if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        tran = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tran, false);
                    }
                }

                #region legacy taxes
                foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                 Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                {
                    #region Add taxes
                    GenericTaxTran new_aptax = apDocumentGraphExtension.TaxTrans.Search <GenericTaxTran.taxID>(tax.TaxID);

                    if (new_aptax == null)
                    {
                        new_aptax       = new GenericTaxTran();
                        new_aptax.TaxID = tax.TaxID;
                        new_aptax       = apDocumentGraphExtension.TaxTrans.Insert(new_aptax);
                        if (new_aptax != null)
                        {
                            new_aptax = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                            new_aptax.CuryTaxableAmt = 0m;
                            new_aptax.CuryTaxAmt     = 0m;
                            new_aptax.CuryExpenseAmt = 0m;
                            new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                        }
                    }

                    if (new_aptax != null)
                    {
                        new_aptax                = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                        new_aptax.TaxRate        = tax.TaxRate;
                        new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                        new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                        new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                        new_aptax                = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                    }
                    #endregion
                }
                #endregion

                invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                invoice.Hold           = false;
                apDocumentGraphExtension.SuppressApproval();
                apDocumentGraphExtension.Documents.Update(invoice);

                if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (InvoiceTran line in apDocumentGraphExtension.InvoiceTrans.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }
                }

                invoice = apDocumentGraphExtension.Documents.Update(invoice);
                docgraph.Actions.PressSave();

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1 &&
                    bankTranMatch != null)
                {
                    CABankTransactionsMaint.RematchFromExpenseReceipt(this, bankTranMatch, invoice.CATranID, invoice.ContragentID, receiptGroup.Single());
                }

                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    claimdetail.APDocType = invoice.DocType;
                    claimdetail.APRefNbr  = invoice.RefNbr;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                }

                claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                claim.Released = true;

                expenseClaimGraph.ExpenseClaim.Update(claim);


                #region EP History Update
                EPHistory hist = new EPHistory();
                hist.EmployeeID  = invoice.ContragentID;
                hist.FinPeriodID = invoice.FinPeriodID;
                hist             = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(hist);

                hist.FinPtdClaimed += invoice.DocBal;
                hist.FinYtdClaimed += invoice.DocBal;
                if (invoice.FinPeriodID == invoice.HeaderTranPeriodID)
                {
                    hist.TranPtdClaimed += invoice.DocBal;
                    hist.TranYtdClaimed += invoice.DocBal;
                }
                else
                {
                    EPHistory tranhist = new EPHistory();
                    tranhist.EmployeeID      = invoice.ContragentID;
                    tranhist.FinPeriodID     = invoice.HeaderTranPeriodID;
                    tranhist                 = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist);
                    tranhist.TranPtdClaimed += invoice.DocBal;
                    tranhist.TranYtdClaimed += invoice.DocBal;
                }
                expenseClaimGraph.Views.Caches.Add(typeof(EPHistory));
                #endregion

                expenseClaimGraph.Save.Press();

                Actions.PressSave();

                doclist.Add((APRegister)apDocumentGraphExtension.Documents.Current.Base);
            }

            return(doclist);
        }