protected virtual void CABankTran_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
        {
            CABankTran row    = e.Row as CABankTran;
            CABankTran oldRow = e.OldRow as CABankTran;

            if (row.TranDate != oldRow.TranDate)
            {
                CABankTranHeader parent = this.Header.Current;
                if (parent != null)
                {
                    if (!parent.TranMaxDate.HasValue || parent.TranMaxDate < row.TranDate)
                    {
                        parent.TranMaxDate = row.TranDate;
                        this.Header.Update(parent);
                    }
                    else if (oldRow.TranDate.HasValue && parent.TranMaxDate == oldRow.TranDate)
                    {
                        CABankTran latest = PXSelect <CABankTran, Where <CABankTran.cashAccountID, Equal <Required <CABankTran.cashAccountID> >,
                                                                         And <CABankTran.headerRefNbr, Equal <Required <CABankTran.headerRefNbr> > > >, OrderBy <Desc <CABankTran.tranDate> > > .Select(this, parent.CashAccountID, parent.RefNbr);

                        parent.TranMaxDate = (latest != null ? latest.TranDate : null);
                        this.Header.Update(parent);
                    }
                }
            }
        }
        protected virtual void CABankTran_RowDeleting(PXCache sender, PXRowDeletingEventArgs e)
        {
            CABankTran row = e.Row as CABankTran;

            if (row.Processed == true || row.DocumentMatched == true)
            {
                throw new PXSetPropertyException(Messages.CannotDeleteTran);
            }
        }
 private void UnmatchAllProcess()
 {
     foreach (var matchedLine in MatchedDetails.Select())
     {
         CABankTran detail = matchedLine;
         UnmatchBankTran(detail, true);
     }
     this.Save.Press();
 }
예제 #4
0
        protected virtual void CABankTranRule_RowDeleting(PXCache cache, PXRowDeletingEventArgs e)
        {
            var        rule    = e.Row as CABankTranRule;
            CABankTran referer = PXSelect <CABankTran, Where <CABankTran.ruleID, Equal <Required <CABankTran.ruleID> > > > .Select(this, rule.RuleID);

            if (referer != null)
            {
                throw new PXException(Messages.BankRuleInUseCantDelete);
            }
        }
        public virtual IEnumerable Unmatch(PXAdapter adapter)
        {
            CABankTran detail = Details.Current;

            if (detail.DocumentMatched == true)
            {
                if (detail.Processed == true)
                {
                    if (Details.Ask(Messages.ClearMatch, Messages.UnmatchTranMsg, MessageButtons.OKCancel) == WebDialogResult.Cancel)
                    {
                        return(adapter.Get());
                    }
                    detail.Processed = false;
                }
                foreach (CABankTranMatch match in TranMatch.Select(detail.TranID))
                {
                    if (match.DocModule == GL.BatchModule.AP && match.DocType == CATranType.CABatch)
                    {
                        foreach (CATran tran in CATransInBatch.Select(match.DocRefNbr))
                        {
                            if (tran != null && tran.TranID != null && tran.ReconNbr == null)
                            {
                                tran.ClearDate = null;
                                tran.Cleared   = false;
                                CATransInBatch.Update(tran);
                            }
                        }
                    }
                    else
                    {
                        CATran tran = CATrans.Select(match.CATranID);
                        if (tran != null && tran.TranID != null && tran.ReconNbr == null)
                        {
                            tran.ClearDate = null;
                            tran.Cleared   = false;
                            CATrans.Update(tran);
                        }
                    }
                    TranMatch.Delete(match);
                }
                foreach (var adj in TranAdj.Select(detail.TranID))
                {
                    TranAdj.Delete(adj);
                }
                foreach (var split in CABankTranSplits.Select(detail.TranID))
                {
                    CABankTranSplits.Delete(split);
                }
                CABankTransactionsMaint.ClearFields(detail);
                Details.Cache.SetDefaultExt <CABankTran.curyApplAmt>(detail);
                Details.Cache.SetDefaultExt <CABankTran.curyApplAmtCA>(detail);
                Details.Update(detail);
            }
            return(adapter.Get());
        }
        protected virtual void CABankTran_TranDate_FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
        {
            CABankTran       row = e.Row as CABankTran;
            CABankTranHeader doc = this.Header.Current;

            if (row != null && doc != null)
            {
                e.NewValue = doc.TranMaxDate.HasValue ? doc.TranMaxDate : doc.DocDate;
                e.Cancel   = true;
            }
        }
        protected virtual IEnumerable result()
        {
            PXSelectBase <CABankTran> cmd = new PXSelectJoin <CABankTran, LeftJoin <CABankTranMatch,
                                                                                    On <CABankTranMatch.tranID, Equal <CABankTran.tranID>,
                                                                                        And <CABankTranMatch.tranType, Equal <CABankTran.tranType> > >,
                                                                                    LeftJoin <CATran, On <CATran.tranID, Equal <CABankTranMatch.cATranID> > > >,
                                                              Where <CABankTran.cashAccountID, Equal <Current <Filter.cashAccountID> >,
                                                                     And <CABankTran.tranDate, GreaterEqual <Current <Filter.startDate> >,
                                                                          And <CABankTran.tranDate, LessEqual <Current <Filter.endDate> >,
                                                                               And <CABankTran.tranType, Equal <Current <Filter.tranType> >,
                                                                                    And <CABankTran.processed, Equal <True>,
                                                                                         And <Where <CABankTran.headerRefNbr, Equal <Current <Filter.headerRefNbr> >, Or <Current <Filter.headerRefNbr>, IsNull> > > > > > > > >(this);

            foreach (PXResult <CABankTran, CABankTranMatch, CATran> res in cmd.Select())
            {
                CABankTran      tran  = (CABankTran)res;
                CABankTranMatch match = (CABankTranMatch)res;
                tran.MatchedToInvoice = CABankTranStatus.IsMatchedToInvoice(tran, match);
                CATran catran = (CATran)res;
                if (catran.OrigModule == null)
                {
                    catran.OrigModule = match.DocModule;
                }
                if (catran.OrigTranType == null)
                {
                    catran.OrigTranType = match.DocType;
                }
                if (catran.OrigRefNbr == null)
                {
                    catran.OrigRefNbr = match.DocRefNbr;
                }
                if (catran.ReferenceID == null)
                {
                    catran.ReferenceID = tran.BAccountID;
                }
                if (catran.OrigModule == null)
                {
                    catran.OrigModule = match.DocModule;
                }
                if (catran.OrigTranType == null)
                {
                    catran.OrigTranType = match.DocType;
                }
                if (catran.OrigRefNbr == null)
                {
                    catran.OrigRefNbr = match.DocRefNbr;
                }
                if (catran.ReferenceID == null)
                {
                    catran.ReferenceID = tran.BAccountID;
                }
                yield return(res);
            }
        }
        public virtual IEnumerable Unhide(PXAdapter adapter)
        {
            CABankTran detail = Details.Current;

            if (detail.Hidden == true)
            {
                detail.Hidden    = false;
                detail.Processed = false;
                detail.RuleID    = null;
                Details.Update(detail);
            }
            return(adapter.Get());
        }
        public bool IsAlreadyImported(int?aCashAccountID, string aExtTranID, out string aRefNbr)
        {
            aRefNbr = null;
            CABankTran detail = PXSelectReadonly <CABankTran,
                                                  Where <CABankTran.tranType, Equal <Current <CABankTranHeader.tranType> >,
                                                         And <CABankTran.cashAccountID, Equal <Required <CABankTran.cashAccountID> >,
                                                              And <CABankTran.extTranID, Equal <Required <CABankTran.extTranID> > > > > > .Select(this, aCashAccountID, aExtTranID);

            if (detail != null)
            {
                aRefNbr = detail.TranID.ToString();
            }
            return(detail != null);
        }
        protected virtual void CABankTran_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            CABankTran row = e.Row as CABankTran;

            if (row == null)
            {
                return;
            }
            PXUIFieldAttribute.SetEnabled(sender, row, !(row.Processed == true || row.DocumentMatched == true));

            PXUIFieldAttribute.SetEnabled <CABankTran.processed>(sender, row, false);
            PXUIFieldAttribute.SetEnabled <CABankTran.documentMatched>(sender, row, false);
            PXUIFieldAttribute.SetEnabled <CABankTran.hidden>(sender, row, false);
            PXUIFieldAttribute.SetEnabled <CABankTran.ruleID>(sender, row, false);
        }
        public virtual IEnumerable ViewDoc(PXAdapter adapter)
        {
            CABankTran detail = Details.Current;

            if (detail.DocumentMatched == true)
            {
                CABankTranMatch match = PXSelect <CABankTranMatch, Where <CABankTranMatch.tranID, Equal <Required <CABankTran.tranID> >, And <CABankTranMatch.tranType, Equal <Required <CABankTran.tranType> > > > > .Select(this, detail.TranID, detail.TranType);

                if (match != null)
                {
                    CABankTranMatch.Redirect(this, match);
                }
            }
            return(adapter.Get());
        }
        public virtual IEnumerable Unmatch(PXAdapter adapter)
        {
            this.Save.Press();
            CABankTran detail = Details.Current;

            if (AskToUnmatchProcessedBankTransaction(detail))
            {
                PXLongOperation.StartOperation(this, delegate()
                {
                    CABankTransactionsImport cABankTransactionsImport = PXGraph.CreateInstance <CABankTransactionsImport>();
                    cABankTransactionsImport.UnmatchBankTran(detail, false);
                });
            }
            return(adapter.Get());
        }
 private bool AskToUnmatchProcessedBankTransaction(CABankTran detail, bool unmatchAll = false)
 {
     if (detail != null && detail.DocumentMatched == true)
     {
         if (detail.Processed == true)
         {
             var unmatchHeader  = unmatchAll ? Messages.ClearMatchAll : Messages.ClearMatch;
             var unmatchMessage = unmatchAll ? Messages.UnmatchAllTranMsg : Messages.UnmatchTranMsg;
             return(Details.Ask(unmatchHeader, unmatchMessage, MessageButtons.OKCancel) == WebDialogResult.OK);
         }
         else
         {
             return(true);
         }
     }
     return(false);
 }
        protected virtual void CABankTran_RowDeleted(PXCache sender, PXRowDeletedEventArgs e)
        {
            CABankTran       row    = e.Row as CABankTran;
            CABankTranHeader parent = this.Header.Current;

            if (parent != null && Header.Cache.GetStatus(parent) != PXEntryStatus.Deleted && parent.TranMaxDate.HasValue)
            {
                if (parent.TranMaxDate == row.TranDate.Value)
                {
                    CABankTran latest = PXSelect <CABankTran, Where <CABankTran.cashAccountID, Equal <Required <CABankTran.cashAccountID> >,
                                                                     And <CABankTran.headerRefNbr, Equal <Required <CABankTran.headerRefNbr> > > >, OrderBy <Desc <CABankTran.tranDate> > > .Select(this, parent.CashAccountID, parent.RefNbr);

                    parent.TranMaxDate = (latest != null ? latest.TranDate : null);
                    this.Header.Update(parent);
                }
            }
        }
        protected virtual void CABankTran_CuryID_FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
        {
            CABankTran row = e.Row as CABankTran;

            if (row == null)
            {
                return;
            }
            if (Header.Current != null)
            {
                CashAccount acct = PXSelect <CashAccount, Where <CashAccount.cashAccountID, Equal <Required <CashAccount.cashAccountID> > > > .Select(this, Header.Current.CashAccountID);

                if (acct != null)
                {
                    e.NewValue = acct.CuryID;
                }
            }
        }
        public virtual IEnumerable UnmatchAll(PXAdapter adapter)
        {
            this.Save.Press();
            CABankTranHeader cABankTranHeader = Header.Current;
            CABankTran       cABankTran       = PXSelect <CABankTran, Where <CABankTran.headerRefNbr, Equal <Required <CABankTranHeader.refNbr> >,
                                                                             And <CABankTran.tranType, Equal <Required <CABankTranHeader.tranType> >,
                                                                                  And <CABankTran.processed, Equal <True>, And <CABankTran.documentMatched, Equal <True> > > > > > .Select(this, cABankTranHeader.RefNbr, cABankTranHeader.TranType);

            if (AskToUnmatchProcessedBankTransaction(cABankTran, unmatchAll: true))
            {
                PXLongOperation.StartOperation(this, delegate()
                {
                    CABankTransactionsImport cABankTransactionsImport = PXGraph.CreateInstance <CABankTransactionsImport>();
                    cABankTransactionsImport.Header.Current           = cABankTranHeader;
                    cABankTransactionsImport.UnmatchAllProcess();
                });
            }
            return(adapter.Get());
        }
        private void UnmatchBankTran(CABankTran origTran, bool isMassRelease)
        {
            if (origTran.DocumentMatched != true)
            {
                return;
            }

            CABankTran copy = (CABankTran)Details.Cache.CreateCopy(origTran);

            copy.Processed = false;
            foreach (CABankTranMatch match in TranMatch.Select(copy.TranID))
            {
                if (match.DocModule == GL.BatchModule.AP && match.DocType == CATranType.CABatch)
                {
                    foreach (CATran tran in CATransInBatch.Select(match.DocRefNbr))
                    {
                        if (tran != null && tran.TranID != null && tran.ReconNbr == null)
                        {
                            tran.ClearDate = null;
                            tran.Cleared   = false;
                            CATransInBatch.Update(tran);
                        }
                    }
                }
                else
                {
                    CATran tran = CATrans.Select(match.CATranID);
                    if (tran != null && tran.TranID != null && tran.ReconNbr == null)
                    {
                        tran.ClearDate = null;
                        tran.Cleared   = false;
                        CATrans.Update(tran);
                    }
                }

                if (CABankTransactionsMaint.IsMatchedToExpenseReceipt(match))
                {
                    EPExpenseClaimDetails receipt =
                        PXSelect <EPExpenseClaimDetails,
                                  Where <EPExpenseClaimDetails.claimDetailCD,
                                         Equal <Required <EPExpenseClaimDetails.claimDetailCD> > > >
                        .Select(this, match.DocRefNbr);

                    receipt.BankTranDate = null;

                    ExpenseReceipts.Update(receipt);
                }

                TranMatch.Delete(match);
            }
            foreach (var adj in TranAdj.Select(copy.TranID))
            {
                TranAdj.Delete(adj);
            }
            foreach (var split in CABankTranSplits.Select(copy.TranID))
            {
                CABankTranSplits.Delete(split);
            }
            CABankTransactionsMaint.ClearFields(copy);
            Details.Cache.SetDefaultExt <CABankTran.curyApplAmt>(copy);
            Details.Cache.SetDefaultExt <CABankTran.curyApplAmtCA>(copy);
            Details.Cache.SetDefaultExt <CABankTran.curyApplAmtMatch>(copy);
            Details.Update(copy);
            if (isMassRelease == false)
            {
                this.Save.Press();
            }
        }
예제 #18
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);
        }