public virtual RollupQty CalculateRollupQty <T>(T row, PMBudget status, decimal?quantity) where T : IBqlTable, IQuantify { string UOM = null; decimal rollupQty = 0; if (status == null) { //Status does not exist for given Inventory and <Other> is not present. } else { if (status.InventoryID == PMInventorySelectorAttribute.EmptyInventoryID) { //<Other> item is present. Update only if UOMs are convertable. decimal convertedQty; if (IN.INUnitAttribute.TryConvertGlobalUnits(graph, row.UOM, status.UOM, quantity.GetValueOrDefault(), IN.INPrecision.QUANTITY, out convertedQty)) { rollupQty = convertedQty; UOM = status.UOM; } } else { UOM = status.UOM; //Item matches. Convert to UOM of ProjectStatus. if (status.UOM != row.UOM && !string.IsNullOrEmpty(status.UOM) && !string.IsNullOrEmpty(row.UOM)) { if (PXAccess.FeatureInstalled <FeaturesSet.multipleUnitMeasure>()) { decimal inBase = IN.INUnitAttribute.ConvertToBase(graph.Caches[typeof(T)], row.InventoryID, row.UOM, quantity ?? 0, IN.INPrecision.QUANTITY); try { rollupQty = IN.INUnitAttribute.ConvertFromBase(graph.Caches[typeof(T)], row.InventoryID, status.UOM, inBase, IN.INPrecision.QUANTITY); } catch (PX.Objects.IN.PXUnitConversionException ex) { IN.InventoryItem item = PXSelectorAttribute.Select(graph.Caches[typeof(T)], row, "inventoryID") as IN.InventoryItem; string msg = PXMessages.LocalizeFormatNoPrefixNLA(Messages.UnitConversionNotDefinedForItemOnBudgetUpdate, item?.BaseUnit, status.UOM, item?.InventoryCD); throw new PXException(msg, ex); } } else { rollupQty = IN.INUnitAttribute.ConvertGlobalUnits(graph, row.UOM, status.UOM, quantity ?? 0, IN.INPrecision.QUANTITY); } } else if (!string.IsNullOrEmpty(status.UOM)) { rollupQty = quantity ?? 0; } } } return(new RollupQty(UOM, rollupQty)); }
public virtual void CheckPartiallyReceiptedPOServices(PXCache sender, PXFieldUpdatedEventArgs e, string poOrderType) { POSetup row = (POSetup)e.Row; if (row != null) { PXResultset <POLine> partiallyReceiptedPOServices = PXSelectReadonly2 <POLine, InnerJoin <IN.InventoryItem, On <POLine.FK.InventoryItem> >, Where <POLine.orderType, Equal <Required <POLine.orderType> >, And <POLine.lineType, Equal <POLineType.service>, And <POLine.completed, NotEqual <True>, And <POLine.receivedQty, NotEqual <decimal0> > > > > > .SelectWindowed(this, 0, 1000, poOrderType); if (partiallyReceiptedPOServices.Count > 0) { if (poOrderType == POOrderType.RegularOrder) { if (row.AddServicesFromNormalPOtoPR == true) { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromNormalPOtoPR>(sender, row, Messages.PossibleOverbillingAPNormalPO); } else { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromNormalPOtoPR>(sender, row, Messages.PossibleOverbillingPRNormalPO); } } else { if (row.AddServicesFromDSPOtoPR == true) { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromDSPOtoPR>(sender, row, Messages.PossibleOverbillingAPDSPO); } else { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromDSPOtoPR>(sender, row, Messages.PossibleOverbillingPRDSPO); } } string overbillingMessage = Messages.PossibleOverbillingTraceList + " \n"; int i = 0; foreach (PXResult <POLine, IN.InventoryItem> line in partiallyReceiptedPOServices) { POLine poline = (POLine)line; IN.InventoryItem item = (IN.InventoryItem)line; overbillingMessage += string.Format(Messages.PossibleOverbillingTraceMessage, (poOrderType == POOrderType.RegularOrder ? Messages.RegularOrder : Messages.DropShip), poline.OrderNbr, poline.LineNbr, item.InventoryCD) + "\n"; i++; if (i >= 1000) { break; } } PXTrace.WriteWarning(overbillingMessage); } } }
protected virtual void ARTran_InventoryID_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e) { var row = (ARTran)e.Row; if (row == null) { return; } IN.InventoryItem item = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(Base, row.InventoryID); InventoryItemRUTROT itemRR = RUTROTHelper.GetExtensionNullable <IN.InventoryItem, InventoryItemRUTROT>(item); Base.Transactions.Cache.SetValueExt <ARTranRUTROT.isRUTROTDeductible>(e.Row, itemRR?.IsRUTROTDeductible ?? false); }
private decimal CalculateRollupQty <T>(T row, IQuantify budget, decimal quantity) where T : IBqlTable, IQuantify { if (string.IsNullOrEmpty(budget.UOM) || string.IsNullOrEmpty(row.UOM) || quantity == 0) { return(0); } if (budget.UOM == row.UOM) { return(quantity); } decimal result = 0; if (budget.InventoryID == PMInventorySelectorAttribute.EmptyInventoryID) { //<Other> item is present. Update only if UOMs are convertable. decimal convertedQty; if (IN.INUnitAttribute.TryConvertGlobalUnits(graph, row.UOM, budget.UOM, quantity, IN.INPrecision.QUANTITY, out convertedQty)) { result = convertedQty; } } else { //Item matches. Convert to UOM of Project Budget. if (PXAccess.FeatureInstalled <FeaturesSet.multipleUnitMeasure>()) { decimal inBase = IN.INUnitAttribute.ConvertToBase(graph.Caches[typeof(T)], row.InventoryID, row.UOM, quantity, IN.INPrecision.QUANTITY); try { result = IN.INUnitAttribute.ConvertFromBase(graph.Caches[typeof(T)], row.InventoryID, budget.UOM, inBase, IN.INPrecision.QUANTITY); } catch (IN.PXUnitConversionException ex) { IN.InventoryItem item = PXSelectorAttribute.Select(graph.Caches[typeof(T)], row, "inventoryID") as IN.InventoryItem; string msg = PXMessages.LocalizeFormatNoPrefixNLA(Messages.UnitConversionNotDefinedForItemOnBudgetUpdate, item?.BaseUnit, budget.UOM, item?.InventoryCD); throw new PXException(msg, ex); } } else { result = IN.INUnitAttribute.ConvertGlobalUnits(graph, row.UOM, budget.UOM, quantity, IN.INPrecision.QUANTITY); } } return(result); }
protected virtual void ARSetup_DunningFeeInventoryID_FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e) { ARSetup setup = e.Row as ARSetup; if (setup == null || e.NewValue == null) { return; } IN.InventoryItem item = (IN.InventoryItem)PXSelectorAttribute.Select <ARSetup.dunningFeeInventoryID>(sender, setup, e.NewValue); if (item != null && item.SalesAcctID == null) { e.NewValue = item.InventoryCD; throw new PXSetPropertyException(Messages.DunningLetterFeeEmptySalesAccount); } }
public string GetTrace() { //Add transaction properties: PMAccountGroup ag = PXSelect <PMAccountGroup, Where <PMAccountGroup.groupID, Equal <Required <PMAccountGroup.groupID> > > > .Select(graph, tran.AccountGroupID); if (ag != null) { trace.AppendFormat(" PMTran.AccountGroup={0} ", ag.GroupCD); } IN.InventoryItem inventoryItem = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(graph, tran.InventoryID); if (inventoryItem != null) { trace.AppendFormat(" PMTran.InventoryID={0} ", inventoryItem.InventoryCD); } return(trace.ToString()); }
private static void AddInvoicedBase(PXCache sender, PMCommitment container) { PMCommitment commitment = (PMCommitment)sender.Graph.Caches[typeof(PMCommitment)].Locate(container); if (commitment == null) { commitment = PXSelect <PMCommitment, Where <PMCommitment.commitmentID, Equal <Required <PMCommitment.commitmentID> > > > .Select(sender.Graph, container.CommitmentID); } if (commitment != null) { decimal quantity = container.InvoicedQty.GetValueOrDefault(); if (commitment.UOM != container.UOM) { if (PXAccess.FeatureInstalled <FeaturesSet.multipleUnitMeasure>()) { decimal inBase = IN.INUnitAttribute.ConvertToBase(sender.Graph.Caches[typeof(PMCommitment)], commitment.InventoryID, container.UOM, quantity, IN.INPrecision.QUANTITY); try { quantity = IN.INUnitAttribute.ConvertFromBase(sender.Graph.Caches[typeof(PMCommitment)], commitment.InventoryID, commitment.UOM, inBase, IN.INPrecision.QUANTITY); } catch (PX.Objects.IN.PXUnitConversionException ex) { IN.InventoryItem item = PXSelectorAttribute.Select(sender.Graph.Caches[typeof(PMCommitment)], commitment, "inventoryID") as IN.InventoryItem; string msg = PXMessages.LocalizeFormatNoPrefixNLA(Messages.UnitConversionNotDefinedForItemOnBudgetUpdate, item?.BaseUnit, commitment.UOM, item?.InventoryCD); throw new PXException(msg, ex); } } else { quantity = IN.INUnitAttribute.ConvertGlobalUnits(sender.Graph, container.UOM, commitment.UOM, quantity, IN.INPrecision.QUANTITY); } } commitment.InvoicedAmount += container.InvoicedAmount.GetValueOrDefault(); commitment.InvoicedQty += quantity; sender.Graph.Caches[typeof(PMCommitment)].Update(commitment); } }
/// <summary> /// Updates Project Status Balance using PMProjectStatusAccum. /// </summary> public static IList <PMHistory> UpdateProjectBalance(PXGraph graph, PMTran pmt, PMAccountGroup ag, Account acc, int mult) { List <PMHistory> list = new List <PMHistory>(); PXSelectBase <PMProjectStatus> selectProjectStatus = new PXSelect <PMProjectStatus, Where <PMProjectStatus.accountGroupID, Equal <Required <PMProjectStatus.accountGroupID> >, And <PMProjectStatus.projectID, Equal <Required <PMProjectStatus.projectID> >, And <PMProjectStatus.projectTaskID, Equal <Required <PMProjectStatus.projectTaskID> >, And <PMProjectStatus.inventoryID, Equal <Required <PMProjectStatus.inventoryID> > > > > > >(graph); // select any without restricting by FinPeriod int inventoryID = PMProjectStatus.EmptyInventoryID; PMProjectStatus status = null; if (pmt.InventoryID != null) { status = selectProjectStatus.Select(ag.GroupID, pmt.ProjectID, pmt.TaskID, pmt.InventoryID); if (status == null) { status = selectProjectStatus.Select(ag.GroupID, pmt.ProjectID, pmt.TaskID, PMProjectStatus.EmptyInventoryID); } else { inventoryID = status.InventoryID ?? PMProjectStatus.EmptyInventoryID; } } else { status = selectProjectStatus.Select(ag.GroupID, pmt.ProjectID, pmt.TaskID, PMProjectStatus.EmptyInventoryID); } string UOM = null; decimal rollupQty = 0; if (status == null) { //Status does not exist for given Inventory and <Other> is not present. } else { if (status.InventoryID == PMProjectStatus.EmptyInventoryID) { //<Other> item is present. Update only if UOMs are same. decimal convertedQty; if (IN.INUnitAttribute.TryConvertGlobalUnits(graph, pmt.UOM, status.UOM, pmt.Qty.GetValueOrDefault(), IN.INPrecision.QUANTITY, out convertedQty)) { rollupQty = convertedQty; UOM = status.UOM; } } else { UOM = status.UOM; //Item matches. Convert to UOM of ProjectStatus. if (status.UOM != pmt.UOM) { decimal inBase = IN.INUnitAttribute.ConvertToBase(graph.Caches[pmt.GetType()], pmt.InventoryID, pmt.UOM, pmt.Qty ?? 0, IN.INPrecision.QUANTITY); try { rollupQty = IN.INUnitAttribute.ConvertFromBase(graph.Caches[pmt.GetType()], pmt.InventoryID, status.UOM, inBase, IN.INPrecision.QUANTITY); } catch (PX.Objects.IN.PXUnitConversionException ex) { IN.InventoryItem item = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(graph, pmt.InventoryID); string msg = PXMessages.LocalizeFormatNoPrefixNLA(Messages.UnitConversionNotDefinedForItemOnBudgetUpdate, item.BaseUnit, status.UOM, item.InventoryCD); throw new PXException(msg, ex); } } else { rollupQty = pmt.Qty ?? 0; } } } if (pmt.TaskID != null && (rollupQty != 0 || pmt.Amount != 0)) //TaskID will be null for Contract { PMProjectStatusAccum ps = new PMProjectStatusAccum(); ps.PeriodID = pmt.FinPeriodID; ps.ProjectID = pmt.ProjectID; ps.ProjectTaskID = pmt.TaskID; ps.AccountGroupID = ag.GroupID; ps.InventoryID = inventoryID; ps.UOM = UOM; if (status != null) { ps.IsProduction = status.IsProduction; } ps = (PMProjectStatusAccum)graph.Caches[typeof(PMProjectStatusAccum)].Insert(ps); decimal amt = mult * pmt.Amount.GetValueOrDefault(); ps.ActualQty += rollupQty * mult; ps.ActualAmount += amt; graph.Views.Caches.Add(typeof(PMProjectStatusAccum)); #region PMTask Totals Update PMTaskTotal ta = new PMTaskTotal(); ta.ProjectID = pmt.ProjectID; ta.TaskID = pmt.TaskID; ta = (PMTaskTotal)graph.Caches[typeof(PMTaskTotal)].Insert(ta); string accType = null; int multFix = 1; //flip back the sign if it was changed because of ag.Type<>acc.type if (pmt.TranType == BatchModule.PM && acc != null && !string.IsNullOrEmpty(acc.Type)) { //Only transactions that originated in PM were inverted and require to be fixed. accType = ag.Type; if (acc.Type != ag.Type) { multFix = -1; } } else { accType = ag.Type; } switch (accType) { case AccountType.Asset: ta.Asset += amt * multFix; break; case AccountType.Liability: ta.Liability += amt * multFix; break; case AccountType.Income: ta.Income += amt * multFix; break; case AccountType.Expense: ta.Expense += amt * multFix; break; } graph.Views.Caches.Add(typeof(PMTaskTotal)); #endregion #region History PMHistory hist = new PMHistory(); hist.ProjectID = pmt.ProjectID; hist.ProjectTaskID = pmt.TaskID; hist.AccountGroupID = ag.GroupID; hist.InventoryID = pmt.InventoryID ?? PMProjectStatus.EmptyInventoryID; hist.PeriodID = pmt.FinPeriodID; decimal baseQty = 0; list.Add(hist); if (pmt.InventoryID != null && pmt.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID && rollupQty != 0) { baseQty = mult * PX.Objects.IN.INUnitAttribute.ConvertToBase(graph.Caches[typeof(PMHistory)], pmt.InventoryID, UOM, rollupQty, PX.Objects.IN.INPrecision.QUANTITY); } hist.FinPTDAmount = amt; hist.FinYTDAmount = amt; hist.FinPTDQty = baseQty; hist.FinYTDQty = baseQty; if (pmt.FinPeriodID == pmt.TranPeriodID) { hist.TranPTDAmount = amt; hist.TranYTDAmount = amt; hist.TranPTDQty = baseQty; hist.TranYTDQty = baseQty; } else { PMHistory tranHist = new PMHistory(); tranHist.ProjectID = pmt.ProjectID; tranHist.ProjectTaskID = pmt.TaskID; tranHist.AccountGroupID = ag.GroupID; tranHist.InventoryID = pmt.InventoryID ?? PM.PMProjectStatus.EmptyInventoryID; tranHist.PeriodID = pmt.TranPeriodID; list.Add(tranHist); tranHist.TranPTDAmount = amt; tranHist.TranYTDAmount = amt; tranHist.TranPTDQty = baseQty; tranHist.TranYTDQty = baseQty; } #endregion } return(list); }
public static void ReleaseProcess(ARDunningLetterMaint graph, ARDunningLetter doc) { if (doc != null && doc.Released != true && doc.Voided != true) { graph.Document.Current = doc; doc.DunningLetterLevel = 0; foreach (ARDunningLetterDetail detail in graph.Details.Select()) { doc.DunningLetterLevel = Math.Max(doc.DunningLetterLevel ?? 0, detail.DunningLetterLevel ?? 0); } if (doc.DunningLetterLevel == 0) { throw new PXException(Messages.DunningLetterZeroLevel); } ARSetup setup = PXSelect <ARSetup> .Select(graph); ARDunningSetup dunningSetup = PXSelect <ARDunningSetup, Where <ARDunningSetup.dunningLetterLevel, Equal <Required <ARDunningLetter.dunningLetterLevel> > > > .Select(graph, doc.DunningLetterLevel); ARInvoiceEntry invGraph = PXGraph.CreateInstance <ARInvoiceEntry>(); if (dunningSetup.DunningFee.HasValue && dunningSetup.DunningFee != 0m) { if (setup.DunningFeeInventoryID == null) { throw new PXException(Messages.DunningLetterEmptyInventory); } Customer customer = graph.CurrentCustomer.Select(); ARInvoice feeInvoice = new ARInvoice { Released = false, Hold = false, Voided = false, BranchID = doc.BranchID, DocDate = doc.DunningLetterDate, CustomerID = doc.BAccountID }; invGraph.Document.Current = feeInvoice; feeInvoice.CustomerLocationID = customer.DefLocationID; invGraph.Document.Update(feeInvoice); feeInvoice.CuryID = customer.AllowOverrideCury == false && customer.CuryID != null ? customer.CuryID : ((GL.Company)PXSelect <GL.Company> .Select(invGraph)).BaseCuryID; invGraph.Document.SetValueExt <ARInvoice.curyID>(invGraph.Document.Current, feeInvoice.CuryID); invGraph.Document.Update(feeInvoice); feeInvoice.DocDesc = Messages.DunningLetterFee; feeInvoice.Hold = false; invGraph.Document.Update(feeInvoice); decimal curyVal; var curyInfo = invGraph.currencyinfo.Select(); PXCurrencyAttribute.PXCurrencyHelper.CuryConvCury(invGraph.Caches[typeof(CurrencyInfo)], curyInfo, dunningSetup.DunningFee ?? 0m, out curyVal); IN.InventoryItem item = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <ARSetup.dunningFeeInventoryID> > > > .Select(graph, setup.DunningFeeInventoryID); if (item == null) { throw new PXException(Messages.DunningLetterEmptyInventory); } if (item.SalesAcctID == null) { throw new PXException(Messages.DunningProcessFeeEmptySalesAccount); } ARTran detail = new ARTran { BranchID = doc.BranchID, Qty = 1, CuryUnitPrice = curyVal, InventoryID = setup.DunningFeeInventoryID, AccountID = item.SalesAcctID, SubID = item.SalesSubID }; invGraph.Transactions.Insert(detail); feeInvoice = PXCache <ARInvoice> .CreateCopy(invGraph.Document.Current); feeInvoice.OrigDocAmt = feeInvoice.DocBal; feeInvoice.CuryOrigDocAmt = feeInvoice.CuryDocBal; invGraph.Document.Update(feeInvoice); invGraph.Save.Press(); if (setup.AutoReleaseDunningFee == true) { invGraph.release.Press(); } doc.FeeRefNbr = invGraph.Document.Current.RefNbr; doc.FeeDocType = invGraph.Document.Current.DocType; } graph.Details.AllowUpdate = true; foreach (ARDunningLetterDetail detail in graph.Details.Select()) { detail.Released = true; graph.Details.Update(detail); } doc.Released = true; graph.Document.Update(doc); graph.Save.Press(); } }
private static ARInvoice InsertFeeInvoice(ARDunningLetter doc, decimal dunningFee) { ARInvoiceEntry invGraph = PXGraph.CreateInstance <ARInvoiceEntry>(); int? organizationID = PXAccess.GetParentOrganizationID(doc.BranchID); string finPeriodID = invGraph.GetService <IFinPeriodRepository>().GetPeriodIDFromDate(doc.DunningLetterDate, organizationID); invGraph.GetService <IFinPeriodUtils>().ValidateFinPeriod(doc.SingleToArray(), m => finPeriodID, m => m.BranchID.SingleToArray()); ARSetup setup = PXSelect <ARSetup> .Select(invGraph); Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <ARDunningLetter.bAccountID> > > > .Select(invGraph, doc.BAccountID); CS.Numbering numbering = PXSelect <CS.Numbering, Where <CS.Numbering.numberingID, Equal <Required <ARSetup.dunningFeeNumberingID> > > > .Select(invGraph, setup.DunningFeeNumberingID); if (setup.DunningFeeInventoryID == null) { throw new PXException(Messages.DunningLetterEmptyInventory); } IN.InventoryItem item = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <ARSetup.dunningFeeInventoryID> > > > .Select(invGraph, setup.DunningFeeInventoryID); if (item == null) { throw new PXException(Messages.DunningLetterEmptyInventory); } if (item.SalesAcctID == null) { throw new PXException(Messages.DunningProcessFeeEmptySalesAccount); } ARInvoice feeInvoice = new ARInvoice { DocType = ARDocType.Invoice }; if (numbering != null) { CS.AutoNumberAttribute.SetNumberingId <ARInvoice.refNbr>(invGraph.Document.Cache, feeInvoice.DocType, numbering.NumberingID); } feeInvoice = (ARInvoice)invGraph.Document.Cache.CreateCopy(invGraph.Document.Insert(feeInvoice)); feeInvoice.Released = false; feeInvoice.Hold = false; feeInvoice.Voided = false; feeInvoice.BranchID = doc.BranchID; feeInvoice.DocDate = doc.DunningLetterDate; feeInvoice.CustomerID = customer.BAccountID; feeInvoice.DocDesc = Messages.DunningLetterFee; feeInvoice.CustomerLocationID = customer.DefLocationID; feeInvoice.CuryID = customer.AllowOverrideCury == false && customer.CuryID != null ? customer.CuryID : ((GL.Company)PXSelect <GL.Company> .Select(invGraph)).BaseCuryID; invGraph.Document.Update(feeInvoice); decimal curyVal; CurrencyInfo curyInfo = invGraph.currencyinfo.Select(); PXCurrencyAttribute.PXCurrencyHelper.CuryConvCury(invGraph.Caches[typeof(CurrencyInfo)], curyInfo, dunningFee, out curyVal); ARTran detail = new ARTran { BranchID = doc.BranchID, Qty = 1, CuryUnitPrice = curyVal, InventoryID = setup.DunningFeeInventoryID, AccountID = item.SalesAcctID, SubID = item.SalesSubID }; invGraph.Transactions.Insert(detail); feeInvoice = PXCache <ARInvoice> .CreateCopy(invGraph.Document.Current); feeInvoice.OrigDocAmt = feeInvoice.DocBal; feeInvoice.CuryOrigDocAmt = feeInvoice.CuryDocBal; invGraph.Document.Update(feeInvoice); invGraph.Save.Press(); if (setup.AutoReleaseDunningFee == true) { invGraph.release.Press(); } return(invGraph.Document.Current); }
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 Result Calculate(PMTran pmt, PMAccountGroup ag, Account acc, int mult) { PMBudget status = SelectProjectBalance(pmt); int? inventoryID = status != null ? status.InventoryID : PMInventorySelectorAttribute.EmptyInventoryID; int? costCodeID = status != null ? status.CostCodeID : CostCodeAttribute.GetDefaultCostCode(); RollupQty rollup = null; if (settings.CostBudgetUpdateMode == CostBudgetUpdateModes.Detailed && ag.IsExpense == true && pmt.InventoryID != settings.EmptyInventoryID) { if (status == null || status.InventoryID == settings.EmptyInventoryID) { rollup = new RollupQty(pmt.UOM, pmt.Qty); inventoryID = pmt.InventoryID; if (pmt.CostCodeID != null) { costCodeID = pmt.CostCodeID; } } } if (rollup == null) { rollup = CalculateRollupQty(pmt, status); } List <PMHistory> list = new List <PMHistory>(); PMTaskTotal ta = null; PMBudget ps = null; if (pmt.TaskID != null && (rollup.Qty != 0 || pmt.Amount != 0)) //TaskID will be null for Contract { ps = new PMBudget(); ps.ProjectID = pmt.ProjectID; ps.ProjectTaskID = pmt.TaskID; ps.AccountGroupID = ag.GroupID; if (ag.Type == PMAccountType.OffBalance) { ps.Type = ag.IsExpense == true ? GL.AccountType.Expense : ag.Type; } else { ps.Type = ag.Type; } ps.InventoryID = inventoryID; ps.CostCodeID = costCodeID; ps.UOM = rollup.UOM; if (status != null) { ps.IsProduction = status.IsProduction; } decimal amt = mult * pmt.Amount.GetValueOrDefault(); if (!string.IsNullOrEmpty(ps.UOM)) { ps.ActualQty = rollup.Qty; // commented out otherwise invoice produces -ve Qty. * mult; } ps.ActualAmount = amt; #region PMTask Totals Update ta = new PMTaskTotal(); ta.ProjectID = pmt.ProjectID; ta.TaskID = pmt.TaskID; string accType = null; int multFix = 1; //flip back the sign if it was changed because of ag.Type<>acc.type if (pmt.TranType == BatchModule.PM && acc != null && !string.IsNullOrEmpty(acc.Type)) { //Only transactions that originated in PM were inverted and require to be fixed. accType = ag.Type; if (acc.Type != ag.Type) { multFix = -1; } } else { accType = ag.Type; } switch (accType) { case AccountType.Asset: ta.Asset = amt * multFix; break; case AccountType.Liability: ta.Liability = amt * multFix; break; case AccountType.Income: ta.Income = amt * multFix; break; case AccountType.Expense: ta.Expense = amt * multFix; break; } #endregion #region History PMHistory hist = new PMHistory(); hist.ProjectID = pmt.ProjectID; hist.ProjectTaskID = pmt.TaskID; hist.AccountGroupID = ag.GroupID; hist.InventoryID = pmt.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID; hist.CostCodeID = pmt.CostCodeID ?? CostCodeAttribute.GetDefaultCostCode(); hist.PeriodID = pmt.FinPeriodID; decimal baseQty = 0; list.Add(hist); if (pmt.InventoryID != null && pmt.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID && pmt.Qty != 0 && !string.IsNullOrEmpty(rollup.UOM)) { if (PXAccess.FeatureInstalled <FeaturesSet.multipleUnitMeasure>()) { baseQty = mult * IN.INUnitAttribute.ConvertToBase(graph.Caches[typeof(PMHistory)], pmt.InventoryID, pmt.UOM, pmt.Qty.Value, PX.Objects.IN.INPrecision.QUANTITY); } else { IN.InventoryItem initem = PXSelectorAttribute.Select <PMTran.inventoryID>(graph.Caches[typeof(PMTran)], pmt) as IN.InventoryItem; if (initem != null) { baseQty = mult * IN.INUnitAttribute.ConvertGlobalUnits(graph, pmt.UOM, initem.BaseUnit, pmt.Qty ?? 0, IN.INPrecision.QUANTITY); } } } hist.FinPTDAmount = amt; hist.FinYTDAmount = amt; hist.FinPTDQty = baseQty; hist.FinYTDQty = baseQty; if (pmt.FinPeriodID == pmt.TranPeriodID) { hist.TranPTDAmount = amt; hist.TranYTDAmount = amt; hist.TranPTDQty = baseQty; hist.TranYTDQty = baseQty; } else { PMHistory tranHist = new PMHistory(); tranHist.ProjectID = pmt.ProjectID; tranHist.ProjectTaskID = pmt.TaskID; tranHist.AccountGroupID = ag.GroupID; tranHist.InventoryID = pmt.InventoryID ?? PM.PMInventorySelectorAttribute.EmptyInventoryID; tranHist.CostCodeID = pmt.CostCodeID ?? CostCodeAttribute.GetDefaultCostCode(); tranHist.PeriodID = pmt.TranPeriodID; list.Add(tranHist); tranHist.TranPTDAmount = amt; tranHist.TranYTDAmount = amt; tranHist.TranPTDQty = baseQty; tranHist.TranYTDQty = baseQty; } #endregion } return(new Result(list, ps, ta)); }
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); }
public virtual void HandleARTranCostOrig(ARTran n, bool tranCostSet) { if (n.InventoryID != null && (n.LineType.IsIn(null, SOLineType.MiscCharge) || n.LineType.IsIn(SOLineType.Inventory, SO.SOLineType.NonInventory) && !tranCostSet)) { //TO DO: review this part and add more accurate cost selection conditions (INItemSite?) PXResult <IN.InventoryItem, IN.INItemSite> result = (PXResult <IN.InventoryItem, IN.INItemSite>) PXSelectJoin <IN.InventoryItem, LeftJoin <IN.INItemSite, On <IN.INItemSite.inventoryID, Equal <IN.InventoryItem.inventoryID>, And <IN.INItemSite.siteID, Equal <Required <IN.INItemSite.siteID> > > > >, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .SelectSingleBound(Base, null, n.SiteID, n.InventoryID); if (result != null) { IN.InventoryItem item = (IN.InventoryItem)result; IN.INItemSite itemSite = (IN.INItemSite)result; if (item.StkItem == true) { if (itemSite.ValMethod != null) { if (item.ValMethod == IN.INValMethod.Standard) { n.TranCostOrig = n.Qty * itemSite.StdCost; } else { n.TranCostOrig = n.Qty * itemSite.AvgCost; } } } else if (n.SOShipmentType != SOShipmentType.DropShip) { if (n.AccrueCost == true && n.AccruedCost != null) { n.TranCost = n.AccruedCost; n.TranCostOrig = n.AccruedCost; n.IsTranCostFinal = true; } else { if (item.KitItem == true && PXAccess.FeatureInstalled <FeaturesSet.kitAssemblies>() && this.SOSetup.Current != null) { switch (this.SOSetup.Current.SalesProfitabilityForNSKits) { case SalesProfitabilityNSKitMethod.NSKitStandardCostOnly: n.TranCost += n.BaseQty * item.StdCost; n.TranCostOrig = n.TranCost; n.IsTranCostFinal = true; break; case SalesProfitabilityNSKitMethod.NSKitStandardAndStockComponentsCost: n.TranCost += n.BaseQty * item.StdCost; n.TranCostOrig = n.TranCost; n.IsTranCostFinal = HasStockComponents(n); break; case SalesProfitabilityNSKitMethod.StockComponentsCostOnly: n.IsTranCostFinal = HasStockComponents(n); break; } } else { n.TranCost += n.BaseQty * item.StdCost; n.TranCostOrig = n.TranCost; n.IsTranCostFinal = true; } } } } } }
protected virtual void InsertARTran(ARInvoiceEntry arGraph, EPExpenseClaimDetails row, decimal signOperation, decimal tipQty = 1m, bool isTipTransaction = false) { CurrencyInfo curyInfo = PXSelect <CurrencyInfo> .Search <CurrencyInfo.curyInfoID>(arGraph, row.CuryInfoID); EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(arGraph); ARTran tran = arGraph.Transactions.Insert(); if (isTipTransaction) { IN.InventoryItem tipItem = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(arGraph, epsetup.NonTaxableTipItem); tran.InventoryID = epsetup.NonTaxableTipItem; tran.Qty = tipQty; tran.UOM = tipItem.BaseUnit; tran.TranDesc = tipItem.Descr; SetAmount(arGraph, row.CuryTipAmt, row.TipAmt, tipQty, signOperation, curyInfo, tran); tran = arGraph.Transactions.Update(tran); if (epsetup.UseReceiptAccountForTips == true) { tran.AccountID = row.SalesAccountID; tran.SubID = row.SalesSubID; } else { 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 <ARTran.branchID> > > > .Select(arGraph); Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <Contract.contractID> > > > .Select(this, row.ContractID); PMTask task = PXSelect <PMTask, Where <PMTask.projectID, Equal <Required <PMTask.projectID> >, And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(arGraph, row.ContractID, row.TaskID); EPEmployee employee = (EPEmployee)PXSelect <EPEmployee> .Search <EPEmployee.bAccountID>(this, row != null?row.EmployeeID : null); Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(arGraph.Caches[typeof(EPExpenseClaimDetails)], row); int?employee_SubID = (int?)arGraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.salesSubID>(employee); int?item_SubID = (int?)arGraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.salesSubID>(tipItem); int?company_SubID = (int?)arGraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(companyloc); int?project_SubID = (int?)arGraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract); int?task_SubID = (int?)arGraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task); int?location_SubID = (int?)arGraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation); object value = SubAccountMaskAttribute.MakeSub <EPSetup.salesSubMask>(arGraph, epsetup.SalesSubMask, new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID }, new Type[] { typeof(EPEmployee.salesSubID), typeof(IN.InventoryItem.salesSubID), typeof(Location.cSalesSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) }); arGraph.Caches[typeof(ARTran)].RaiseFieldUpdating <ARTran.subID>(tran, ref value); tran.SubID = (int?)value; } } else { tran.InventoryID = row.InventoryID; tran.Qty = row.Qty * signOperation; tran.UOM = row.UOM; tran = arGraph.Transactions.Update(tran); tran.AccountID = row.SalesAccountID; tran.SubID = row.SalesSubID; tran.TranDesc = row.TranDesc; //For gross taxes we can't put tranAmt. So we should use taxable amount EPTaxTran firstLevelTaxTran = null; foreach (EPTaxTran taxRow in PXSelect <EPTaxTran, Where <EPTaxTran.claimDetailID, Equal <Required <EPTaxTran.claimDetailID> >, And <EPTaxTran.isTipTax, Equal <False> > > > .Select(this, row.ClaimDetailID)) { if (firstLevelTaxTran == null || Math.Abs(firstLevelTaxTran.CuryTaxableAmt ?? 0m) > Math.Abs(taxRow.CuryTaxableAmt ?? 0m)) { firstLevelTaxTran = taxRow; } } decimal?curyAmt = firstLevelTaxTran?.CuryTaxableAmt ?? row.CuryTaxableAmt; decimal?amt = firstLevelTaxTran?.TaxableAmt ?? row.TaxableAmt; SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran); tran = arGraph.Transactions.Update(tran); if (tran.CuryTaxableAmt != 0 && tran.CuryTaxableAmt != curyAmt) // indicates that we have gross/ iclusive taxes. In this case recalculation is required { curyAmt = row.CuryTaxableAmt; amt = row.TaxableAmt; SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran); } } tran.Date = row.ExpenseDate; tran.ManualPrice = true; tran = arGraph.Transactions.Update(tran); PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], row, arGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.ar>()); }
public virtual decimal GetItemPrice(PXCache sender, string curyID, int?customerID, int?locationID, string contractStatus, int?contractItemID, int?itemID, string itemType, string priceOption, decimal?fixedPrice, decimal?setupPrice, decimal?qty, DateTime?date) { decimal itemPrice = 0m; ContractItem item = PXSelect <ContractItem, Where <ContractItem.contractItemID, Equal <Required <ContractItem.contractItemID> > > > .Select(sender.Graph, contractItemID); if (item != null) { IN.InventoryItem nonstock = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(sender.Graph, itemID); CR.Location customerLocation = PXSelect < CR.Location, Where < CR.Location.bAccountID, Equal <Required <Contract.customerID> >, And <CR.Location.locationID, Equal <Required <Contract.locationID> > > > > .Select(sender.Graph, customerID, locationID); string customerPriceClass = string.IsNullOrEmpty(customerLocation?.CPriceClassID) ? ARPriceClass.EmptyPriceClass : customerLocation.CPriceClassID; if (priceOption == null) { switch (itemType) { case ContractDetailType.Setup: priceOption = item.BasePriceOption; break; case ContractDetailType.Renewal: priceOption = item.RenewalPriceOption; break; case ContractDetailType.Billing: priceOption = item.FixedRecurringPriceOption; break; case ContractDetailType.UsagePrice: priceOption = item.UsagePriceOption; break; } } CM.CurrencyInfo currencyInfo = new CM.CurrencyInfo(); currencyInfo.BaseCuryID = new PXSetup <Company>(sender.Graph).Current.BaseCuryID; currencyInfo.CuryID = curyID; Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(sender.Graph, customerID); if (customer != null && customer.CuryRateTypeID != null) { currencyInfo.CuryRateTypeID = customer.CuryRateTypeID; } currencyInfo.SetCuryEffDate(sender.Graph.Caches[typeof(CM.CurrencyInfo)], date); if (nonstock != null && currencyInfo != null) { switch (priceOption) { case PriceOption.ItemPrice: itemPrice = ARSalesPriceMaint.CalculateSalesPrice(sender, customerPriceClass, customerID, itemID, currencyInfo, qty, nonstock.BaseUnit, date ?? DateTime.Now, false) ?? 0m; break; case PriceOption.ItemPercent: itemPrice = ((ARSalesPriceMaint.CalculateSalesPrice(sender, customerPriceClass, customerID, itemID, currencyInfo, qty, nonstock.BaseUnit, date ?? DateTime.Now, false) ?? 0m) / 100m * (fixedPrice ?? 0m)); break; case PriceOption.BasePercent: itemPrice = (setupPrice ?? 0m) / 100m * (fixedPrice ?? 0m); break; case PriceOption.Manually: itemPrice = fixedPrice ?? 0m; break; } } } return(itemPrice); }
public virtual Result Calculate(PMProject project, PMTran pmt, PMAccountGroup ag, string accountType, int amountSign, int qtySign) { PMBudgetLite target = null; bool isExisting; target = service.SelectProjectBalance(pmt, ag, project, out isExisting); var rollupQty = CalculateRollupQty(pmt, target); List <PMHistory> list = new List <PMHistory>(); PMTaskTotal ta = null; PMBudget ps = null; PMForecastHistory forecast = null; if (pmt.TaskID != null && (rollupQty != 0 || pmt.Amount != 0)) //TaskID will be null for Contract { ps = new PMBudget(); ps.ProjectID = target.ProjectID; ps.ProjectTaskID = target.TaskID; ps.AccountGroupID = target.AccountGroupID; ps.Type = target.Type; ps.InventoryID = target.InventoryID; ps.CostCodeID = target.CostCodeID; ps.UOM = target.UOM; ps.IsProduction = target.IsProduction; ps.Description = target.Description; if (ps.CuryInfoID == null) { ps.CuryInfoID = project.CuryInfoID; } decimal amt = amountSign * pmt.Amount.GetValueOrDefault(); decimal curyAmt = amountSign * pmt.ProjectCuryAmount.GetValueOrDefault(); ps.ActualQty = rollupQty * qtySign; ps.ActualAmount = amt; ps.CuryActualAmount = curyAmt; #region PMTask Totals Update ta = new PMTaskTotal(); ta.ProjectID = ps.ProjectID; ta.TaskID = ps.TaskID; string accType = ag.IsExpense == true ? AccountType.Expense : ag.Type; switch (accType) { case AccountType.Asset: ta.CuryAsset = curyAmt; ta.Asset = amt; break; case AccountType.Liability: ta.CuryLiability = curyAmt; ta.Liability = amt; break; case AccountType.Income: ta.CuryIncome = curyAmt; ta.Income = amt; break; case AccountType.Expense: ta.CuryExpense = curyAmt; ta.Expense = amt; break; } #endregion #region History PMHistory hist = new PMHistory(); hist.ProjectID = ps.ProjectID; hist.ProjectTaskID = ps.TaskID; hist.AccountGroupID = ps.AccountGroupID; hist.InventoryID = pmt.InventoryID ?? ps.InventoryID; hist.CostCodeID = pmt.CostCodeID ?? ps.CostCodeID; hist.PeriodID = pmt.FinPeriodID; hist.BranchID = pmt.BranchID; decimal baseQty = 0; list.Add(hist); if (pmt.InventoryID != null && pmt.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID && pmt.Qty != 0) { if (PXAccess.FeatureInstalled <FeaturesSet.multipleUnitMeasure>()) { baseQty = qtySign * IN.INUnitAttribute.ConvertToBase(graph.Caches[typeof(PMHistory)], pmt.InventoryID, pmt.UOM, pmt.Qty.Value, PX.Objects.IN.INPrecision.QUANTITY); } else { IN.InventoryItem initem = PXSelectorAttribute.Select <PMTran.inventoryID>(graph.Caches[typeof(PMTran)], pmt) as IN.InventoryItem; if (initem != null && !string.IsNullOrEmpty(pmt.UOM)) { baseQty = qtySign * IN.INUnitAttribute.ConvertGlobalUnits(graph, pmt.UOM, initem.BaseUnit, pmt.Qty ?? 0, IN.INPrecision.QUANTITY); } } } hist.FinPTDCuryAmount = curyAmt; hist.FinPTDAmount = amt; hist.FinYTDCuryAmount = curyAmt; hist.FinYTDAmount = amt; hist.FinPTDQty = baseQty; hist.FinYTDQty = baseQty; if (pmt.FinPeriodID == pmt.TranPeriodID) { hist.TranPTDCuryAmount = curyAmt; hist.TranPTDAmount = amt; hist.TranYTDCuryAmount = curyAmt; hist.TranYTDAmount = amt; hist.TranPTDQty = baseQty; hist.TranYTDQty = baseQty; } else { PMHistory tranHist = new PMHistory(); tranHist.ProjectID = ps.ProjectID; tranHist.ProjectTaskID = ps.TaskID; tranHist.AccountGroupID = ps.AccountGroupID; tranHist.InventoryID = pmt.InventoryID ?? PM.PMInventorySelectorAttribute.EmptyInventoryID; tranHist.CostCodeID = pmt.CostCodeID ?? CostCodeAttribute.GetDefaultCostCode(); tranHist.PeriodID = pmt.TranPeriodID; tranHist.BranchID = pmt.BranchID; list.Add(tranHist); tranHist.TranPTDCuryAmount = curyAmt; tranHist.TranPTDAmount = amt; tranHist.TranYTDCuryAmount = curyAmt; tranHist.TranYTDAmount = amt; tranHist.TranPTDQty = baseQty; tranHist.TranYTDQty = baseQty; } #endregion forecast = new PMForecastHistory(); forecast.ProjectID = ps.ProjectID; forecast.ProjectTaskID = ps.ProjectTaskID; forecast.AccountGroupID = ps.AccountGroupID; forecast.InventoryID = ps.InventoryID; forecast.CostCodeID = ps.CostCodeID; forecast.PeriodID = pmt.TranPeriodID; forecast.ActualQty = ps.ActualQty; forecast.CuryActualAmount = ps.CuryActualAmount; forecast.ActualAmount = ps.ActualAmount; } return(new Result(list, ps, ta, forecast)); }