Esempio n. 1
0
        public static void AssignNumbersWithNoAdditionalProcessing(APPaymentEntry pe, APPayment doc)
        {
            PaymentMethod method = pe.paymenttype.Select(doc.PaymentMethodID);

            if (method == null || method.PrintOrExport == true)
            {
                // To persist the manual changes from "Release Checks" screen (AC-94830)
                pe.Document.Cache.MarkUpdated(doc);
                return;
            }

            pe.RowPersisting.RemoveHandler <APAdjust>(pe.APAdjust_RowPersisting);
            pe.Clear();
            pe.Document.Current = pe.Document.Search <APPayment.refNbr>(doc.RefNbr, doc.DocType);
            PaymentMethodAccount det = pe.cashaccountdetail.Select();

            pe.Document.Current.StubCntr  = 1;
            pe.Document.Current.BillCntr  = 0;
            pe.Document.Current.ExtRefNbr = doc.ExtRefNbr;

            foreach (APAdjust adj in pe.Adjustments_print.Select())
            {
                pe.Document.Current.BillCntr++;
                SetAdjustmentStubNumber(pe, doc, adj, doc.ExtRefNbr);
            }

            det.APLastRefNbr = doc.ExtRefNbr;
            pe.cashaccountdetail.Update(det);

            pe.Document.Current.Printed = true;
            pe.Document.Current.Hold    = false;
            pe.Document.Update(pe.Document.Current);
        }
Esempio n. 2
0
        public virtual void StoreStubNumber(APPaymentEntry pe, APPayment doc, PaymentMethodAccount det, string StubNbr, int stubOrdinal)
        {
            if (doc.VoidAppl == true || StubNbr == null)
            {
                return;
            }

            pe.CACheck.Insert(new CashAccountCheck
            {
                AccountID       = doc.CashAccountID,
                PaymentMethodID = doc.PaymentMethodID,
                CheckNbr        = StubNbr,
                DocType         = doc.DocType,
                RefNbr          = doc.RefNbr,
                FinPeriodID     = doc.FinPeriodID,
                DocDate         = doc.DocDate,
                VendorID        = doc.VendorID
            });

            det.APLastRefNbr = StubNbr;
        }
Esempio n. 3
0
        public virtual void AssignNumbers(ARPaymentEntryExt pe, ARPayment doc, ref string NextCheckNbr)
        {
            pe.RowPersisting.RemoveHandler <ARAdjust>(pe.ARAdjust_RowPersisting);
            pe.Clear(PXClearOption.PreserveTimeStamp);
            doc = pe.Document.Current = pe.Document.Search <ARPayment.refNbr>(doc.RefNbr, doc.DocType);
            PaymentMethodAccount det = pe.cashaccountdetail.Select();

            var payExt = PXCache <ARPayment> .GetExtension <ARPaymentExt>(pe.Document.Current);

            if (!string.IsNullOrEmpty(NextCheckNbr))
            {
                if (String.IsNullOrEmpty(pe.Document.Current.ExtRefNbr))
                {
                    payExt.StubCntr = 1;
                    payExt.BillCntr = 0;
                    pe.Document.Current.ExtRefNbr = NextCheckNbr;
                    if (String.IsNullOrEmpty(NextCheckNbr))
                    {
                        throw new PXException(AP.Messages.NextCheckNumberIsRequiredForProcessing);
                    }

                    pe.cashaccountdetail.Update(det); // det.APLastRefNumber was modified in StoreStubNumber method

                    NextCheckNbr                         = AutoNumberAttribute.NextNumber(NextCheckNbr);
                    payExt.Printed                       = true;
                    pe.Document.Current.Hold             = false;
                    pe.Document.Current.UpdateNextNumber = true;
                    pe.Document.Update(pe.Document.Current);
                }
                else
                {
                    if (payExt.Printed != true || pe.Document.Current.Hold != false)
                    {
                        payExt.Printed           = true;
                        pe.Document.Current.Hold = false;
                        pe.Document.Update(pe.Document.Current);
                    }
                }
            }
        }
Esempio n. 4
0
        public static void ReleasePayments(List <APPayment> list, string Action)
        {
            APReleaseChecks releaseChecksGraph = CreateInstance <APReleaseChecks>();
            APPaymentEntry  pe        = CreateInstance <APPaymentEntry>();
            CABatchEntry    be        = CreateInstance <CABatchEntry>();
            bool            failed    = false;
            bool            successed = false;

            List <APRegister> docs = new List <APRegister>(list.Count);

            foreach (APPayment payment in list)
            {
                if (payment.Passed == true)
                {
                    releaseChecksGraph.TimeStamp = pe.TimeStamp = payment.tstamp;
                }

                switch (Action)
                {
                case ReleaseChecksFilter.action.ReleaseChecks:
                    payment.Printed = true;
                    break;

                case ReleaseChecksFilter.action.ReprintChecks:
                case ReleaseChecksFilter.action.VoidAndReprintChecks:
                    payment.ExtRefNbr = null;
                    payment.Printed   = false;
                    break;

                default:
                    continue;
                }

                PXProcessing <APPayment> .SetCurrentItem(payment);

                if (Action == ReleaseChecksFilter.action.ReleaseChecks)
                {
                    try
                    {
                        pe.Document.Current = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType);
                        if (pe.Document.Current?.ExtRefNbr != payment.ExtRefNbr)
                        {
                            APPayment payment_copy = PXCache <APPayment> .CreateCopy(pe.Document.Current);

                            payment_copy.ExtRefNbr = payment.ExtRefNbr;
                            pe.Document.Update(payment_copy);
                        }

                        if (PaymentRefAttribute.PaymentRefMustBeUnique(pe.paymenttype.Current) && string.IsNullOrEmpty(payment.ExtRefNbr))
                        {
                            throw new PXException(ErrorMessages.FieldIsEmpty, typeof(APPayment.extRefNbr).Name);
                        }

                        payment.IsReleaseCheckProcess = true;

                        APPrintChecks.AssignNumbersWithNoAdditionalProcessing(pe, payment);
                        pe.Save.Press();

                        object[] persisted = PXTimeStampScope.GetPersisted(pe.Document.Cache, pe.Document.Current);
                        if (persisted == null || persisted.Length == 0)
                        {
                            //preserve timestamp which will be @@dbts after last record committed to db on previous Persist().
                            //otherwise another process updated APAdjust.
                            docs.Add(payment);
                        }
                        else
                        {
                            if (payment.Passed == true)
                            {
                                pe.Document.Current.Passed = true;
                            }
                            docs.Add(pe.Document.Current);
                        }
                        successed = true;
                    }
                    catch (PXException e)
                    {
                        PXProcessing <APPayment> .SetError(e);

                        docs.Add(null);
                        failed = true;
                    }
                }

                if (Action == ReleaseChecksFilter.action.ReprintChecks || Action == ReleaseChecksFilter.action.VoidAndReprintChecks)
                {
                    try
                    {
                        payment.IsPrintingProcess = true;
                        using (PXTransactionScope transactionScope = new PXTransactionScope())
                        {
                            #region Update CABatch if ReprintChecks
                            CABatch caBatch = PXSelectJoin <CABatch,
                                                            InnerJoin <CABatchDetail, On <CABatch.batchNbr, Equal <CABatchDetail.batchNbr> > >,
                                                            Where <CABatchDetail.origModule, Equal <Required <APPayment.origModule> >,
                                                                   And <CABatchDetail.origDocType, Equal <Required <APPayment.docType> >,
                                                                        And <CABatchDetail.origRefNbr, Equal <Required <APPayment.refNbr> > > > > > .
                                              Select(be, payment.OrigModule, payment.DocType, payment.RefNbr);

                            if (caBatch != null)
                            {
                                be.Document.Current = caBatch;
                                int           DetailCount = be.Details.Select().Count;                       // load
                                CABatchDetail detail      = be.Details.Locate(new CABatchDetail()
                                {
                                    BatchNbr    = be.Document.Current.BatchNbr,
                                    OrigModule  = payment.OrigModule,
                                    OrigDocType = payment.DocType,
                                    OrigRefNbr  = payment.RefNbr,
                                    OrigLineNbr = CABatchDetail.origLineNbr.DefaultValue,
                                });
                                if (detail != null)
                                {
                                    // payment.Status is recalculated in CABatchEntry.Delete
                                    if (DetailCount == 1)
                                    {
                                        be.Document.Delete(be.Document.Current);                                         // Details will delete by PXParent
                                    }
                                    else
                                    {
                                        be.Details.Delete(detail);                                          // recalculated batch totals
                                    }
                                }
                                be.Save.Press();
                            }
                            else
                            {
                                PXCache cacheAPPayment = releaseChecksGraph.APPaymentList.Cache;

                                cacheAPPayment.SetValueExt <APPayment.printed>(payment, false);
                                cacheAPPayment.SetValueExt <APPayment.hold>(payment, false);
                                cacheAPPayment.SetValueExt <APPayment.extRefNbr>(payment, null);
                                // APPayment.Status is recalculated by SetStatusCheckAttribute
                                cacheAPPayment.MarkUpdated(payment);

                                cacheAPPayment.PersistUpdated(payment);
                                cacheAPPayment.Persisted(false);
                            }
                            #endregion
                            // TODO: Need to rework. Use legal CRUD methods of caches!
                            releaseChecksGraph.TimeStamp = PXDatabase.SelectTimeStamp();

                            // delete check numbers only if Reprint (not Void and Reprint)
                            PaymentMethod pm = pe.paymenttype.Select(payment.PaymentMethodID);
                            if (pm.APPrintChecks == true && Action == ReleaseChecksFilter.action.ReprintChecks)
                            {
                                APPayment doc = payment;
                                new HashSet <string>(pe.Adjustments_Raw.Select(doc.DocType, doc.RefNbr)
                                                     .RowCast <APAdjust>()
                                                     .Select(adj => adj.StubNbr))
                                .ForEach(nbr => PaymentRefAttribute.DeleteCheck((int)doc.CashAccountID, doc.PaymentMethodID, nbr));

                                // sync PaymentMethodAccount.APLastRefNbr with actual last CashAccountCheck number
                                PaymentMethodAccount det = releaseChecksGraph.cashaccountdetail.SelectSingle(payment.CashAccountID, payment.PaymentMethodID);
                                PaymentRefAttribute.LastCashAccountCheckSelect.Clear(releaseChecksGraph);
                                CashAccountCheck cacheck = PaymentRefAttribute.LastCashAccountCheckSelect.SelectSingleBound(releaseChecksGraph, new object[] { det });
                                det.APLastRefNbr = cacheck?.CheckNbr;
                                releaseChecksGraph.cashaccountdetail.Cache.PersistUpdated(det);
                                releaseChecksGraph.cashaccountdetail.Cache.Persisted(false);
                            }
                            // END TODO
                            if (string.IsNullOrEmpty(payment.ExtRefNbr))
                            {
                                //try to get next number
                                releaseChecksGraph.APPaymentList.Cache.SetDefaultExt <APPayment.extRefNbr>(payment);
                            }
                            transactionScope.Complete();
                        }
                    }
                    catch (PXException e)
                    {
                        PXProcessing <APPayment> .SetError(e);
                    }
                    docs.Add(null);
                }
            }
            if (successed)
            {
                APDocumentRelease.ReleaseDoc(docs, true);
            }

            if (failed)
            {
                throw new PXOperationCompletedWithErrorException(GL.Messages.DocumentsNotReleased);
            }
        }
Esempio n. 5
0
        public virtual void AssignNumbers(APPaymentEntry pe, APPayment doc, ref string NextCheckNbr, bool skipStubs = false)
        {
            pe.RowPersisting.RemoveHandler <APAdjust>(pe.APAdjust_RowPersisting);
            pe.Clear();
            doc = pe.Document.Current = pe.Document.Search <APPayment.refNbr>(doc.RefNbr, doc.DocType);
            PaymentMethodAccount det = pe.cashaccountdetail.Select();

            doc.IsPrintingProcess = true;             // indicates that the payment under printing process (to prevent update by PaymentRefAttribute)

            if (string.IsNullOrEmpty(NextCheckNbr))
            {
                throw new PXException(Messages.NextCheckNumberIsRequiredForProcessing);
            }

            if (string.IsNullOrEmpty(pe.Document.Current.ExtRefNbr))
            {
                pe.Document.Current.StubCntr  = 1;
                pe.Document.Current.BillCntr  = 0;
                pe.Document.Current.ExtRefNbr = NextCheckNbr;

                if (pe.Document.Current.DocType == APDocType.QuickCheck && pe.Document.Current.CuryOrigDocAmt <= 0m)
                {
                    throw new PXException(Messages.ZeroCheck_CannotPrint);
                }

                if (!skipStubs)                         // print check
                {
                    APAdjust[]    adjustments = pe.Adjustments_print.Select().RowCast <APAdjust>().ToArray();
                    PaymentMethod pt          = pe.paymenttype.Select();
                    int           stubCount   = (int)Math.Ceiling(adjustments.Length / (decimal)(pt.APStubLines ?? 1));
                    if (stubCount > 1 && pt.APPrintRemittance != true)
                    {
                        string   endNumber  = AutoNumberAttribute.NextNumber(NextCheckNbr, stubCount - 1);
                        string[] duplicates = PXSelect <CashAccountCheck,
                                                        Where <CashAccountCheck.accountID, Equal <Required <PrintChecksFilter.payAccountID> >,
                                                               And <CashAccountCheck.paymentMethodID, Equal <Required <PrintChecksFilter.payTypeID> >,
                                                                    And <CashAccountCheck.checkNbr, GreaterEqual <Required <PrintChecksFilter.nextCheckNbr> >,
                                                                         And <CashAccountCheck.checkNbr, LessEqual <Required <PrintChecksFilter.nextCheckNbr> > > > > > >
                                              .Select(this, det.CashAccountID, det.PaymentMethodID, NextCheckNbr, endNumber)
                                              .RowCast <CashAccountCheck>()
                                              .Select(check => check.CheckNbr)
                                              .ToArray();

                        if (duplicates.Any())
                        {
                            throw new PXException(
                                      Messages.TooSmallCheckNumbersGap,
                                      stubCount,
                                      NextCheckNbr,
                                      endNumber,
                                      string.Join(",", duplicates));
                        }
                    }

                    short ordinalInStub = 0;
                    int   stubOrdinal   = 0;
                    foreach (APAdjust adj in adjustments)
                    {
                        pe.Document.Current.BillCntr++;

                        if (ordinalInStub > pt.APStubLines - 1)
                        {
                            //AssignCheckNumber only for first StubLines in check, other/all lines will be printed on remittance report
                            if (pt.APPrintRemittance == true)
                            {
                                adj.StubNbr = null;
                                pe.Adjustments.Cache.Update(adj);
                                continue;
                            }
                            NextCheckNbr = AutoNumberAttribute.NextNumber(NextCheckNbr);

                            pe.Document.Current.StubCntr++;
                            ordinalInStub = 0;
                            stubOrdinal++;
                        }

                        SetAdjustmentStubNumber(pe, doc, adj, NextCheckNbr);
                        StoreStubNumber(pe, doc, det, NextCheckNbr, stubOrdinal);

                        ordinalInStub++;
                    }
                }
                else                         // create batch payment
                {
                    //Update last number
                    det.APLastRefNbr = NextCheckNbr;
                }

                pe.cashaccountdetail.Update(det);                         // det.APLastRefNumber was modified in StoreStubNumber method

                NextCheckNbr = AutoNumberAttribute.NextNumber(NextCheckNbr);
                pe.Document.Current.Printed = true;
                pe.Document.Current.Hold    = false;
                pe.Document.Update(pe.Document.Current);
            }
            else
            {
                if (pe.Document.Current.Printed != true || pe.Document.Current.Hold == true)
                {
                    pe.Document.Current.Printed = true;
                    pe.Document.Current.Hold    = false;
                    pe.Document.Update(pe.Document.Current);
                }
            }
        }
Esempio n. 6
0
        public static void ReleasePayments(List <APPayment> list, string Action)
        {
            APReleaseChecks graph     = PXGraph.CreateInstance <APReleaseChecks>();
            APPaymentEntry  pe        = PXGraph.CreateInstance <APPaymentEntry>();
            bool            failed    = false;
            bool            successed = false;

            string NextCheckNbr = null;

            List <APRegister>        docs    = new List <APRegister>(list.Count);
            List <string>            numbers = new List <string>();
            Dictionary <string, int> stubs   = new Dictionary <string, int>();

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Passed == true)
                {
                    graph.TimeStamp = pe.TimeStamp = list[i].tstamp;
                }

                switch (Action)
                {
                case "R":
                    list[i].Printed = true;
                    break;

                case "D":
                    PaymentMethodAccount det = PXSelect <PaymentMethodAccount, Where <PaymentMethodAccount.cashAccountID, Equal <Required <PaymentMethodAccount.cashAccountID> >, And <PaymentMethodAccount.paymentMethodID, Equal <Required <PaymentMethodAccount.paymentMethodID> > > > > .Select(graph, list[i].CashAccountID, list[i].PaymentMethodID);

                    if (det == null || det.APAutoNextNbr == false)
                    {
                        numbers.Add(list[i].ExtRefNbr);
                        stubs[list[i].ExtRefNbr] = (int)list[i].StubCntr;
                        //null out Check Number and delete used check number if StubCounter == 1
                        list[i].ExtRefNbr = null;
                    }
                    list[i].Printed = false;
                    break;

                case "V":
                    //null out Check Number but do not delete it
                    list[i].StubCntr  = -1;
                    list[i].ExtRefNbr = null;
                    list[i].Printed   = false;
                    break;

                default:
                    continue;
                }

                if ((bool)list[i].Printed)
                {
                    try
                    {
                        APPrintChecks.AssignNumbers(pe, list[i], ref NextCheckNbr);
                        pe.Save.Press();

                        object[] persisted = PXTimeStampScope.GetPersisted(pe.Document.Cache, pe.Document.Current);
                        if (persisted == null || persisted.Length == 0)
                        {
                            //preserve timestamp which will be @@dbts after last record committed to db on previous Persist().
                            //otherwise another process updated APAdjust.
                            docs.Add(list[i]);
                        }
                        else
                        {
                            if (list[i].Passed == true)
                            {
                                pe.Document.Current.Passed = true;
                            }
                            docs.Add(pe.Document.Current);
                        }
                        successed = true;
                    }
                    catch (Exception e)
                    {
                        PXProcessing <APPayment> .SetError(i, e);

                        docs.Add(null);
                        failed = true;
                    }
                }
                else
                {
                    try
                    {
                        list[i].Hold = true;

                        graph.APPaymentList.Cache.PersistUpdated(list[i]);
                        graph.APPaymentList.Cache.Persisted(false);

                        graph.TimeStamp = PXDatabase.SelectTimeStamp();

                        if (string.IsNullOrEmpty(list[i].ExtRefNbr))
                        {
                            //try to get next number
                            graph.APPaymentList.Cache.SetDefaultExt <APPayment.extRefNbr>(list[i]);
                            if (string.IsNullOrEmpty(list[i].ExtRefNbr) == false)
                            {
                                list[i].StubCntr = 1;
                                graph.APPaymentList.Cache.PersistUpdated(list[i]);
                                graph.APPaymentList.Cache.Persisted(false);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        PXProcessing <APPayment> .SetError(i, e);
                    }
                    docs.Add(null);
                }
            }
            if (successed)
            {
                APDocumentRelease.ReleaseDoc(docs, true);
            }

            numbers.Sort();
            for (int i = numbers.Count - 1; i >= 0; i--)
            {
                PaymentMethodAccount det = PXSelect <PaymentMethodAccount, Where <PaymentMethodAccount.cashAccountID, Equal <Required <PaymentMethodAccount.cashAccountID> >, And <PaymentMethodAccount.paymentMethodID, Equal <Required <PaymentMethodAccount.paymentMethodID> > > > > .Select(graph, list[0].CashAccountID, list[0].PaymentMethodID);

                string lastnumber = AutoNumberAttribute.NextNumber(numbers[i], stubs[numbers[i]] - 1);

                if (string.Equals(lastnumber, det.APLastRefNbr))
                {
                    det.APLastRefNbr = AutoNumberAttribute.NextNumber(det.APLastRefNbr, -stubs[numbers[i]]);
                    graph.cashaccountdetail.Cache.PersistUpdated(det);
                    graph.cashaccountdetail.Cache.Persisted(false);
                }
            }

            if (failed)
            {
                throw new PXException(GL.Messages.DocumentsNotReleased);
            }
        }
Esempio n. 7
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);
        }
        public static void ReleasePayments(List <APPayment> list, string Action)
        {
            APReleaseChecks releaseChecksGraph = CreateInstance <APReleaseChecks>();
            APPaymentEntry  pe        = CreateInstance <APPaymentEntry>();
            bool            failed    = false;
            bool            successed = false;

            List <APRegister> docs = new List <APRegister>(list.Count);

            foreach (APPayment payment in list)
            {
                if (payment.Passed == true)
                {
                    releaseChecksGraph.TimeStamp = pe.TimeStamp = payment.tstamp;
                }

                switch (Action)
                {
                case ReleaseChecksFilter.action.ReleaseChecks:
                    payment.Printed = true;
                    break;

                case ReleaseChecksFilter.action.ReprintChecks:
                case ReleaseChecksFilter.action.VoidAndReprintChecks:
                    payment.ExtRefNbr = null;
                    payment.Printed   = false;
                    break;

                default:
                    continue;
                }

                PXProcessing <APPayment> .SetCurrentItem(payment);

                if (Action == ReleaseChecksFilter.action.ReleaseChecks)
                {
                    try
                    {
                        pe.Document.Current = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType);
                        if (PaymentRefAttribute.PaymentRefMustBeUnique(pe.paymenttype.Current) && string.IsNullOrEmpty(payment.ExtRefNbr))
                        {
                            throw new PXException(ErrorMessages.FieldIsEmpty, typeof(APPayment.extRefNbr).Name);
                        }

                        payment.IsReleaseCheckProcess = true;

                        APPrintChecks.AssignNumbersWithNoAdditionalProcessing(pe, payment);
                        pe.Save.Press();

                        object[] persisted = PXTimeStampScope.GetPersisted(pe.Document.Cache, pe.Document.Current);
                        if (persisted == null || persisted.Length == 0)
                        {
                            //preserve timestamp which will be @@dbts after last record committed to db on previous Persist().
                            //otherwise another process updated APAdjust.
                            docs.Add(payment);
                        }
                        else
                        {
                            if (payment.Passed == true)
                            {
                                pe.Document.Current.Passed = true;
                            }
                            docs.Add(pe.Document.Current);
                        }
                        successed = true;
                    }
                    catch (PXException e)
                    {
                        PXProcessing <APPayment> .SetError(e);

                        docs.Add(null);
                        failed = true;
                    }
                }

                if (Action == ReleaseChecksFilter.action.ReprintChecks || Action == ReleaseChecksFilter.action.VoidAndReprintChecks)
                {
                    try
                    {
                        payment.IsPrintingProcess = true;

                        releaseChecksGraph.APPaymentList.Cache.SetValueExt <APPayment.printed>(payment, false);
                        releaseChecksGraph.APPaymentList.Cache.SetValueExt <APPayment.hold>(payment, false);
                        releaseChecksGraph.APPaymentList.Cache.SetValueExt <APPayment.extRefNbr>(payment, null);

                        releaseChecksGraph.APPaymentList.Cache.RaiseRowSelected(payment);                         //We need payment's status to be set correctly before persisting
                        // TODO: Need to rework. Use legal CRUD methods of caches!
                        releaseChecksGraph.APPaymentList.Cache.PersistUpdated(payment);
                        releaseChecksGraph.APPaymentList.Cache.Persisted(false);

                        releaseChecksGraph.TimeStamp = PXDatabase.SelectTimeStamp();

                        // delete check numbers only if Reprint (not Void and Reprint)
                        PaymentMethod pm = pe.paymenttype.Select(payment.PaymentMethodID);
                        if (pm.APPrintChecks == true && Action == ReleaseChecksFilter.action.ReprintChecks)
                        {
                            APPayment doc = payment;
                            new HashSet <string>(pe.Adjustments_Raw.Select(doc.DocType, doc.RefNbr)
                                                 .RowCast <APAdjust>()
                                                 .Select(adj => adj.StubNbr))
                            .ForEach(nbr => PaymentRefAttribute.DeleteCheck((int)doc.CashAccountID, doc.PaymentMethodID, nbr));

                            // sync PaymentMethodAccount.APLastRefNbr with actual last CashAccountCheck number
                            PaymentMethodAccount det = releaseChecksGraph.cashaccountdetail.SelectSingle(payment.CashAccountID, payment.PaymentMethodID);
                            PaymentRefAttribute.LastCashAccountCheckSelect.Clear(releaseChecksGraph);
                            CashAccountCheck cacheck = PaymentRefAttribute.LastCashAccountCheckSelect.SelectSingleBound(releaseChecksGraph, new object[] { det });
                            det.APLastRefNbr = cacheck?.CheckNbr;
                            releaseChecksGraph.cashaccountdetail.Cache.PersistUpdated(det);
                            releaseChecksGraph.cashaccountdetail.Cache.Persisted(false);
                        }
                        // END TODO
                        if (string.IsNullOrEmpty(payment.ExtRefNbr))
                        {
                            //try to get next number
                            releaseChecksGraph.APPaymentList.Cache.SetDefaultExt <APPayment.extRefNbr>(payment);
                        }
                    }
                    catch (PXException e)
                    {
                        PXProcessing <APPayment> .SetError(e);
                    }
                    docs.Add(null);
                }
            }
            if (successed)
            {
                APDocumentRelease.ReleaseDoc(docs, true);
            }

            if (failed)
            {
                throw new PXOperationCompletedWithErrorException(GL.Messages.DocumentsNotReleased);
            }
        }
        public static void ReleasePayments(List <APPayment> list, string Action)
        {
            APReleaseChecks graph     = CreateInstance <APReleaseChecks>();
            APPaymentEntry  pe        = CreateInstance <APPaymentEntry>();
            bool            failed    = false;
            bool            successed = false;

            List <APRegister> docs = new List <APRegister>(list.Count);

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Passed == true)
                {
                    graph.TimeStamp = pe.TimeStamp = list[i].tstamp;
                }

                switch (Action)
                {
                case "R":
                    list[i].Printed = true;
                    break;

                case "D":
                case "V":
                    list[i].ExtRefNbr = null;
                    list[i].Printed   = false;
                    break;

                default:
                    continue;
                }

                if ((bool)list[i].Printed)
                {
                    try
                    {
                        APPrintChecks.AssignNumbersWithNoAdditionalProcessing(pe, list[i]);
                        pe.Save.Press();

                        object[] persisted = PXTimeStampScope.GetPersisted(pe.Document.Cache, pe.Document.Current);
                        if (persisted == null || persisted.Length == 0)
                        {
                            //preserve timestamp which will be @@dbts after last record committed to db on previous Persist().
                            //otherwise another process updated APAdjust.
                            docs.Add(list[i]);
                        }
                        else
                        {
                            if (list[i].Passed == true)
                            {
                                pe.Document.Current.Passed = true;
                            }
                            docs.Add(pe.Document.Current);
                        }
                        successed = true;
                    }
                    catch (Exception e)
                    {
                        PXProcessing <APPayment> .SetError(i, e);

                        docs.Add(null);
                        failed = true;
                    }
                }
                else
                {
                    try
                    {
                        list[i].Hold = true;
                        // TODO: Need to rework. Use legal CRUD methods of caches!
                        graph.APPaymentList.Cache.PersistUpdated(list[i]);
                        graph.APPaymentList.Cache.Persisted(false);

                        graph.TimeStamp = PXDatabase.SelectTimeStamp();

                        // delete check numbers only if Reprint (not Void and Reprint)
                        PaymentMethod pm = pe.paymenttype.Select(list[i].PaymentMethodID);
                        if (pm.APPrintChecks == true && Action == "D")
                        {
                            APPayment doc = list[i];
                            new HashSet <string>(pe.Adjustments_Raw.Select(doc.DocType, doc.RefNbr, doc.LineCntr)
                                                 .RowCast <APAdjust>()
                                                 .Select(adj => adj.StubNbr))
                            .ForEach(nbr => PaymentRefAttribute.DeleteCheck((int)doc.CashAccountID, doc.PaymentMethodID, nbr));

                            // sync PaymentMethodAccount.APLastRefNbr with actual last CashAccountCheck number
                            PaymentMethodAccount det = graph.cashaccountdetail.SelectSingle(list[i].CashAccountID, list[i].PaymentMethodID);
                            PaymentRefAttribute.LastCashAccountCheckSelect.Clear(graph);
                            CashAccountCheck cacheck = PaymentRefAttribute.LastCashAccountCheckSelect.SelectSingleBound(graph, new object[] { det });
                            det.APLastRefNbr = cacheck == null ? null : cacheck.CheckNbr;
                            graph.cashaccountdetail.Cache.PersistUpdated(det);
                            graph.cashaccountdetail.Cache.Persisted(false);
                        }
                        // END TODO
                        if (string.IsNullOrEmpty(list[i].ExtRefNbr))
                        {
                            //try to get next number
                            graph.APPaymentList.Cache.SetDefaultExt <APPayment.extRefNbr>(list[i]);
                        }
                    }
                    catch (Exception e)
                    {
                        PXProcessing <APPayment> .SetError(i, e);
                    }
                    docs.Add(null);
                }
            }
            if (successed)
            {
                APDocumentRelease.ReleaseDoc(docs, true);
            }

            if (failed)
            {
                throw new PXException(GL.Messages.DocumentsNotReleased);
            }
        }
Esempio n. 10
0
        public static void AssignNumbers(APPaymentEntry pe, APPayment doc, ref string NextCheckNbr, bool skipStubs)
        {
            pe.RowPersisting.RemoveHandler <APAdjust>(pe.APAdjust_RowPersisting);
            pe.Clear(PXClearOption.PreserveTimeStamp);
            pe.Document.Current = (APPayment)pe.Document.Search <APPayment.refNbr>(doc.RefNbr, doc.DocType);
            if (String.IsNullOrEmpty(NextCheckNbr) == false)
            {
                if (String.IsNullOrEmpty(pe.Document.Current.ExtRefNbr))
                {
                    pe.Document.Current.StubCntr  = 1;
                    pe.Document.Current.BillCntr  = 0;
                    pe.Document.Current.ExtRefNbr = NextCheckNbr;
                    if (String.IsNullOrEmpty(NextCheckNbr))
                    {
                        throw new PXException(Messages.NextCheckNumberIsRequiredForProcessing);
                    }

                    if (pe.Document.Current.DocType == APDocType.QuickCheck && pe.Document.Current.CuryOrigDocAmt <= 0m)
                    {
                        throw new PXException(Messages.ZeroCheck_CannotPrint);
                    }

                    if (!skipStubs)
                    {
                        short j = 0;
                        foreach (PXResult <APAdjust> res in pe.Adjustments_print.Select())
                        {
                            pe.Document.Current.BillCntr++;

                            APAdjust             adj = (APAdjust)res;
                            PaymentMethod        pt  = pe.paymenttype.Select();
                            PaymentMethodAccount det = pe.cashaccountdetail.Select();
                            if (j > pt.APStubLines - 1)
                            {
                                //AssignCheckNumber only for first StubLines in check, other/all lines will be printed on remittance report
                                if (pt.APPrintRemittance == true)
                                {
                                    adj.StubNbr = null;
                                    pe.Adjustments.Cache.Update(adj);
                                    continue;
                                }
                                NextCheckNbr = AutoNumberAttribute.NextNumber(NextCheckNbr);
                                pe.Document.Current.StubCntr++;
                                j = 0;
                            }
                            adj.StubNbr = NextCheckNbr;
                            pe.Adjustments.Cache.Update(adj);
                            det.APLastRefNbr = NextCheckNbr;
                            pe.cashaccountdetail.Update(det);
                            j++;
                        }
                    }
                    NextCheckNbr = AutoNumberAttribute.NextNumber(NextCheckNbr);
                    pe.Document.Current.Printed          = true;
                    pe.Document.Current.Hold             = false;
                    pe.Document.Current.UpdateNextNumber = true;
                    pe.Document.Update(pe.Document.Current);
                }
                else
                {
                    if (pe.Document.Current.Printed != true || pe.Document.Current.Hold != false)
                    {
                        pe.Document.Current.Printed = true;
                        pe.Document.Current.Hold    = false;
                        pe.Document.Update(pe.Document.Current);
                    }
                }
            }
            else
            {
                PaymentMethod        method = pe.paymenttype.Select();
                PaymentMethodAccount det    = pe.cashaccountdetail.Select();
                //if (method != null && (method.PrintOrExport == false || det.APAutoNextNbr == true))
                {
                    if (pe.Document.Current.DocType == APDocType.QuickCheck && pe.Document.Current.CuryOrigDocAmt <= 0m)
                    {
                        throw new PXException(Messages.ZeroCheck_CannotPrint);
                    }

                    pe.Document.Current.StubCntr  = 1;
                    pe.Document.Current.BillCntr  = 0;
                    pe.Document.Current.ExtRefNbr = doc.ExtRefNbr;
                    if (!skipStubs)
                    {
                        foreach (PXResult <APAdjust> res in pe.Adjustments_print.Select())
                        {
                            pe.Document.Current.BillCntr++;

                            APAdjust adj = (APAdjust)res;
                            adj.StubNbr = doc.ExtRefNbr;
                            pe.Adjustments.Cache.Update(adj);
                        }
                    }
                    pe.Document.Current.Printed = true;
                    pe.Document.Current.Hold    = false;
                    pe.Document.Update(pe.Document.Current);
                }
            }
        }