protected ContractProcessing(int? contractID)
        {
            if (contractID > 0)
            {
                this.graph = PXGraph.CreateInstance<ARInvoiceEntry>();
                graph.FieldVerifying.AddHandler<ARInvoice.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
                this.contract = PXSelect<Contract, Where<Contract.contractID, Equal<Required<Contract.contractID>>>>.Select(graph, contractID);

                this.insetup = PXSelect<INSetup>.Select(graph);
                this.template = PXSelect<Contract, Where<Contract.contractID, Equal<Required<Contract.contractID>>>>.Select(graph, contract.TemplateID);
                this.schedule = PXSelect<ContractBillingSchedule>.Search<ContractBillingSchedule.contractID>(graph, contract.ContractID);
                if (contract.CustomerID != null)
                {
                    if (schedule != null && schedule.AccountID != null)
                    {
                        customer = PXSelect<Customer, Where<Customer.bAccountID, Equal<Required<ContractBillingSchedule.accountID>>>>.Select(graph, schedule.AccountID);
                        if (schedule.LocationID != null)
                        {
                            location = PXSelect<Location, Where<Location.bAccountID, Equal<Required<ContractBillingSchedule.accountID>>, And<Location.locationID, Equal<Required<ContractBillingSchedule.locationID>>>>>.Select(graph, customer.BAccountID, schedule.LocationID);
                        }
                        else
                        {
                            location = PXSelect<Location, Where<Location.locationID, Equal<Required<Customer.defLocationID>>>>.Select(graph, customer.DefLocationID);
                        }
                    }
                    else
                    {
                        customer = PXSelect<Customer, Where<Customer.bAccountID, Equal<Required<Customer.bAccountID>>>>.Select(graph, contract.CustomerID);
                        if (contract.LocationID != null)
                        {
                            location = PXSelect<Location, Where<Location.bAccountID, Equal<Required<ContractBillingSchedule.accountID>>, And<Location.locationID, Equal<Required<ContractBillingSchedule.locationID>>>>>.Select(graph, customer.BAccountID, contract.LocationID);
                        }
                        else
                        {
                            location = PXSelect<Location, Where<Location.locationID, Equal<Required<Customer.defLocationID>>>>.Select(graph, customer.DefLocationID);
                        }
                    }
                }

                SetupGraph();
            }
        }
Esempio n. 2
0
        private static ARInvoice CreatePPDCreditMemo(ARInvoiceEntry ie, ARPPDCreditMemoParameters filter, ARSetup setup, List <PendingPPDCreditMemoApp> list)
        {
            int       index = 0;
            ARInvoice invoice;

            try
            {
                ie.Clear(PXClearOption.ClearAll);
                PXUIFieldAttribute.SetError(ie.Document.Cache, null, null, null);

                Customer customer = null;
                invoice = (ARInvoice)ie.Document.Cache.CreateInstance();

                bool firstApp = true;
                foreach (PendingPPDCreditMemoApp doc in list)
                {
                    if (firstApp)
                    {
                        firstApp = false;
                        index    = doc.Index;

                        customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(ie, doc.AdjdCustomerID);

                        CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(ie, doc.InvCuryInfoID);

                        info.CuryInfoID = null;
                        info            = ie.currencyinfo.Insert(info);

                        invoice.DocType     = ARDocType.CreditMemo;
                        invoice.DocDate     = filter.GenerateOnePerCustomer == true ? filter.CreditMemoDate : doc.AdjgDocDate;
                        invoice.FinPeriodID = filter.GenerateOnePerCustomer == true ? filter.FinPeriodID : doc.AdjgFinPeriodID;
                        invoice             = PXCache <ARInvoice> .CreateCopy(ie.Document.Insert(invoice));

                        invoice.CustomerID         = doc.AdjdCustomerID;
                        invoice.CustomerLocationID = doc.InvCustomerLocationID;
                        invoice.CuryInfoID         = info.CuryInfoID;
                        invoice.CuryID             = info.CuryID;
                        invoice.DocDesc            = setup.PPDCreditMemoDescr;
                        invoice.BranchID           = doc.AdjdBranchID;
                        invoice.ARAccountID        = doc.AdjdARAcct;
                        invoice.ARSubID            = doc.AdjdARSub;
                        invoice.TaxZoneID          = doc.InvTaxZoneID;
                        invoice.Hold       = false;
                        invoice.PendingPPD = true;

                        invoice = ie.Document.Update(invoice);

                        invoice.DontPrint = true;
                        invoice.DontEmail = true;
                    }

                    AddTaxesAndApplications(ie, doc, customer, invoice);
                }

                ie.ARDiscountDetails.Select().RowCast <ARInvoiceDiscountDetail>().
                ForEach(discountDetail => ie.ARDiscountDetails.Cache.Delete(discountDetail));

                if (setup.RequireControlTotal == true)
                {
                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    ie.Document.Cache.Update(invoice);
                }

                ie.Save.Press();
                string refNbr = invoice.RefNbr;
                list.ForEach(doc => PXUpdate <Set <ARAdjust.pPDCrMemoRefNbr, Required <ARAdjust.pPDCrMemoRefNbr> >, ARAdjust,
                                              Where <ARAdjust.adjdDocType, Equal <Required <ARAdjust.adjdDocType> >,
                                                     And <ARAdjust.adjdRefNbr, Equal <Required <ARAdjust.adjdRefNbr> >,
                                                          And <ARAdjust.adjgDocType, Equal <Required <ARAdjust.adjgDocType> >,
                                                               And <ARAdjust.adjgRefNbr, Equal <Required <ARAdjust.adjgRefNbr> >,
                                                                    And <ARAdjust.released, Equal <True>,
                                                                         And <ARAdjust.voided, NotEqual <True>,
                                                                              And <ARAdjust.pendingPPD, Equal <True> > > > > > > > >
                             .Update(ie, refNbr, doc.AdjdDocType, doc.AdjdRefNbr, doc.AdjgDocType, doc.AdjgRefNbr));
                PXProcessing <PendingPPDCreditMemoApp> .SetInfo(index, ActionsMessages.RecordProcessed);
            }
            catch (Exception e)
            {
                PXProcessing <PendingPPDCreditMemoApp> .SetError(index, e);

                invoice = null;
            }

            return(invoice);
        }
Esempio n. 3
0
        public static void ReleaseProcess(ARDunningLetterMaint graph, ARDunningLetter doc)
        {
            if (doc != null && doc.Released != true && doc.Voided != true)
            {
                graph.Document.Current = doc;
                doc.DunningLetterLevel = 0;
                foreach (ARDunningLetterDetail detail in graph.Details.Select())
                {
                    doc.DunningLetterLevel = Math.Max(doc.DunningLetterLevel ?? 0, detail.DunningLetterLevel ?? 0);
                }

                if (doc.DunningLetterLevel == 0)
                {
                    throw new PXException(Messages.DunningLetterZeroLevel);
                }

                ARSetup setup = PXSelect <ARSetup> .Select(graph);

                ARDunningSetup dunningSetup = PXSelect <ARDunningSetup, Where <ARDunningSetup.dunningLetterLevel, Equal <Required <ARDunningLetter.dunningLetterLevel> > > > .Select(graph, doc.DunningLetterLevel);

                ARInvoiceEntry invGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
                if (dunningSetup.DunningFee.HasValue && dunningSetup.DunningFee != 0m)
                {
                    if (setup.DunningFeeInventoryID == null)
                    {
                        throw new PXException(Messages.DunningLetterEmptyInventory);
                    }

                    Customer  customer   = graph.CurrentCustomer.Select();
                    ARInvoice feeInvoice = new ARInvoice
                    {
                        Released   = false,
                        Hold       = false,
                        Voided     = false,
                        BranchID   = doc.BranchID,
                        DocDate    = doc.DunningLetterDate,
                        CustomerID = doc.BAccountID
                    };

                    invGraph.Document.Current     = feeInvoice;
                    feeInvoice.CustomerLocationID = customer.DefLocationID;
                    invGraph.Document.Update(feeInvoice);

                    feeInvoice.CuryID = customer.AllowOverrideCury == false && customer.CuryID != null
                                                ? customer.CuryID
                                                : ((GL.Company)PXSelect <GL.Company> .Select(invGraph)).BaseCuryID;
                    invGraph.Document.SetValueExt <ARInvoice.curyID>(invGraph.Document.Current, feeInvoice.CuryID);
                    invGraph.Document.Update(feeInvoice);

                    feeInvoice.DocDesc = Messages.DunningLetterFee;
                    feeInvoice.Hold    = false;
                    invGraph.Document.Update(feeInvoice);

                    decimal curyVal;
                    var     curyInfo = invGraph.currencyinfo.Select();
                    PXCurrencyAttribute.PXCurrencyHelper.CuryConvCury(invGraph.Caches[typeof(CurrencyInfo)], curyInfo, dunningSetup.DunningFee ?? 0m, out curyVal);

                    IN.InventoryItem item = PXSelect <IN.InventoryItem,
                                                      Where <IN.InventoryItem.inventoryID, Equal <Required <ARSetup.dunningFeeInventoryID> > > > .Select(graph, setup.DunningFeeInventoryID);

                    if (item == null)
                    {
                        throw new PXException(Messages.DunningLetterEmptyInventory);
                    }

                    if (item.SalesAcctID == null)
                    {
                        throw new PXException(Messages.DunningProcessFeeEmptySalesAccount);
                    }

                    ARTran detail = new ARTran
                    {
                        BranchID      = doc.BranchID,
                        Qty           = 1,
                        CuryUnitPrice = curyVal,
                        InventoryID   = setup.DunningFeeInventoryID,
                        AccountID     = item.SalesAcctID,
                        SubID         = item.SalesSubID
                    };
                    invGraph.Transactions.Insert(detail);

                    feeInvoice = PXCache <ARInvoice> .CreateCopy(invGraph.Document.Current);

                    feeInvoice.OrigDocAmt     = feeInvoice.DocBal;
                    feeInvoice.CuryOrigDocAmt = feeInvoice.CuryDocBal;
                    invGraph.Document.Update(feeInvoice);
                    invGraph.Save.Press();

                    if (setup.AutoReleaseDunningFee == true)
                    {
                        invGraph.release.Press();
                    }
                    doc.FeeRefNbr  = invGraph.Document.Current.RefNbr;
                    doc.FeeDocType = invGraph.Document.Current.DocType;
                }

                graph.Details.AllowUpdate = true;
                foreach (ARDunningLetterDetail detail in graph.Details.Select())
                {
                    detail.Released = true;
                    graph.Details.Update(detail);
                }

                doc.Released = true;
                graph.Document.Update(doc);
                graph.Save.Press();
            }
        }
Esempio n. 4
0
        public static void CreatePPDCreditMemos(PXCache cache, ARPPDCreditMemoParameters filter, ARSetup setup, List <PendingPPDCreditMemoApp> docs)
        {
            int  i      = 0;
            bool failed = false;

            List <ARRegister> toRelease = new List <ARRegister>();
            ARInvoiceEntry    ie        = PXGraph.CreateInstance <ARInvoiceEntry>();

            if (filter.GenerateOnePerCustomer == true)
            {
                if (filter.CreditMemoDate == null)
                {
                    throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat,
                                                     PXUIFieldAttribute.GetDisplayName <ARPPDCreditMemoParameters.creditMemoDate>(cache));
                }

                if (filter.FinPeriodID == null)
                {
                    throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat,
                                                     PXUIFieldAttribute.GetDisplayName <ARPPDCreditMemoParameters.finPeriodID>(cache));
                }

                Dictionary <PPDCreditMemoKey, List <PendingPPDCreditMemoApp> > dict = new Dictionary <PPDCreditMemoKey, List <PendingPPDCreditMemoApp> >();
                foreach (PendingPPDCreditMemoApp doc in docs)
                {
                    CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(ie, doc.InvCuryInfoID);

                    PPDCreditMemoKey key = new PPDCreditMemoKey();
                    doc.Index              = i++;
                    key.BranchID           = doc.AdjdBranchID;
                    key.CustomerID         = doc.AdjdCustomerID;
                    key.CustomerLocationID = doc.InvCustomerLocationID;
                    key.CuryID             = info.CuryID;
                    key.CuryRate           = info.CuryRate;
                    key.ARAccountID        = doc.AdjdARAcct;
                    key.ARSubID            = doc.AdjdARSub;
                    key.TaxZoneID          = doc.InvTaxZoneID;

                    List <PendingPPDCreditMemoApp> list;
                    if (!dict.TryGetValue(key, out list))
                    {
                        dict[key] = list = new List <PendingPPDCreditMemoApp>();
                    }

                    list.Add(doc);
                }

                foreach (List <PendingPPDCreditMemoApp> list in dict.Values)
                {
                    ARInvoice invoice = CreatePPDCreditMemo(ie, filter, setup, list);
                    if (invoice != null)
                    {
                        toRelease.Add(invoice);
                    }
                    else
                    {
                        failed = true;
                    }
                }
            }
            else
            {
                foreach (PendingPPDCreditMemoApp doc in docs)
                {
                    List <PendingPPDCreditMemoApp> list = new List <PendingPPDCreditMemoApp>(1);
                    doc.Index = i++;
                    list.Add(doc);

                    ARInvoice invoice = CreatePPDCreditMemo(ie, filter, setup, list);
                    if (invoice != null)
                    {
                        toRelease.Add(invoice);
                    }
                    else
                    {
                        failed = true;
                    }
                }
            }

            if (setup.AutoReleasePPDCreditMemo == true && toRelease.Count > 0)
            {
                using (new PXTimeStampScope(null))
                {
                    ARDocumentRelease.ReleaseDoc(toRelease, true);
                }
            }

            if (failed)
            {
                throw new PXException(GL.Messages.DocumentsNotReleased);
            }
        }
Esempio n. 5
0
 public static bool IsNeedBalancing(ARInvoiceEntry graph, string balanceOn) => IsNeedBalancing(graph, null, balanceOn);
Esempio n. 6
0
        private static void CreateMemo(ARInvoiceEntry graph, ARRegister doc, RUTROT rutrot, string docType, bool OnRelease = false)
        {
            DuplicateFilter filter = PXCache <DuplicateFilter> .CreateCopy(graph.duplicatefilter.Current);

            foreach (PXResult <ARInvoice, CurrencyInfo, Terms, Customer> res in ARInvoice_CurrencyInfo_Terms_Customer.Select(graph, (object)doc.DocType, doc.RefNbr, doc.CustomerID))
            {
                CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy((CurrencyInfo)res);

                info.CuryInfoID = null;
                info.IsReadOnly = false;
                info            = PXCache <CurrencyInfo> .CreateCopy(graph.currencyinfo.Insert(info));

                ARInvoice invoice = (ARInvoice)graph.Document.Cache.CreateInstance();

                if (docType == ARDocType.CreditMemo)
                {
                    invoice.DueDate     = null;
                    invoice.DiscDate    = null;
                    invoice.CustomerID  = doc.CustomerID;
                    invoice.ARAccountID = doc.ARAccountID;
                    invoice.ARSubID     = doc.ARSubID;
                }

                if (docType == ARInvoiceType.DebitMemo)
                {
                    invoice.DueDate  = ((ARInvoice)res).DueDate;
                    invoice.DiscDate = ((ARInvoice)res).DiscDate;

                    BranchRUTROT branchRUTROT = GetBranchRUTROT(graph);

                    invoice.CustomerID  = branchRUTROT.TaxAgencyAccountID;
                    invoice.ARAccountID = null;
                    invoice.ARSubID     = null;
                }

                ARInvoiceRUTROT invoiceRUTROT = RUTROTHelper.GetExtensionNullable <ARInvoice, ARInvoiceRUTROT>(invoice);
                invoiceRUTROT.IsRUTROTDeductible = false;

                invoice.CuryInfoID = info.CuryInfoID;
                invoice.DocType    = docType;
                invoice.OrigModule = GL.BatchModule.AR;
                invoice.RefNbr     = null;
                invoice.OrigModule = GL.BatchModule.AR;
                invoice.DocDesc    = PXLocalizer.LocalizeFormat(RUTROTMessages.MemoDescription, doc.RefNbr);

                invoice.OpenDoc    = true;
                invoice.Released   = false;
                invoice.Hold       = false;
                invoice.Printed    = false;
                invoice.Emailed    = false;
                invoice.BatchNbr   = null;
                invoice.ScheduleID = null;
                invoice.Scheduled  = false;
                invoice.NoteID     = null;
                invoice.RefNoteID  = null;

                invoice.TermsID             = null;
                invoice.InstallmentCntr     = null;
                invoice.InstallmentNbr      = null;
                invoice.CuryOrigDiscAmt     = 0m;
                invoice.FinPeriodID         = doc.FinPeriodID;
                invoice.OrigDocDate         = invoice.DocDate;
                invoice.CuryLineTotal       = 0m;
                invoice.IsTaxPosted         = false;
                invoice.IsTaxValid          = false;
                invoice.CuryVatTaxableTotal = 0m;
                invoice.CuryVatExemptTotal  = 0m;
                invoice.StatementDate       = null;
                invoice.PendingPPD          = false;
                invoice.CustomerLocationID  = null;

                if (!string.IsNullOrEmpty(invoice.PaymentMethodID))
                {
                    CA.PaymentMethod pm = null;

                    if (invoice.CashAccountID.HasValue)
                    {
                        CA.PaymentMethodAccount pmAccount = null;
                        PXResult <CA.PaymentMethod, CA.PaymentMethodAccount> pmResult = (PXResult <CA.PaymentMethod, CA.PaymentMethodAccount>)
                                                                                        PXSelectJoin <CA.PaymentMethod,
                                                                                                      LeftJoin <
                                                                                                          CA.PaymentMethodAccount, On <CA.PaymentMethod.paymentMethodID, Equal <CA.PaymentMethodAccount.paymentMethodID> > >,
                                                                                                      Where <
                                                                                                          CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> >,
                                                                                                          And <CA.PaymentMethodAccount.cashAccountID, Equal <Required <CA.PaymentMethodAccount.cashAccountID> > > > > .
                                                                                        Select(graph, invoice.PaymentMethodID, invoice.CashAccountID);

                        pm        = pmResult;
                        pmAccount = pmResult;

                        if (pm == null || pm.UseForAR == false || pm.IsActive == false)
                        {
                            invoice.PaymentMethodID = null;
                            invoice.CashAccountID   = null;
                        }
                        else if (pmAccount == null || pmAccount.CashAccountID == null || pmAccount.UseForAR != true)
                        {
                            invoice.CashAccountID = null;
                        }
                    }
                    else
                    {
                        pm = PXSelect <CA.PaymentMethod,
                                       Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > >
                             .Select(graph, invoice.PaymentMethodID);

                        if (pm == null || pm.UseForAR == false || pm.IsActive == false)
                        {
                            invoice.PaymentMethodID = null;
                            invoice.CashAccountID   = null;
                            invoice.PMInstanceID    = null;
                        }
                    }

                    if (invoice.PMInstanceID.HasValue)
                    {
                        CustomerPaymentMethod cpm = PXSelect <CustomerPaymentMethod,
                                                              Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .
                                                    Select(graph, invoice.PMInstanceID);

                        if (string.IsNullOrEmpty(invoice.PaymentMethodID) || cpm == null || cpm.IsActive == false || cpm.PaymentMethodID != invoice.PaymentMethodID)
                        {
                            invoice.PMInstanceID = null;
                        }
                    }
                }
                else
                {
                    invoice.CashAccountID = null;
                    invoice.PMInstanceID  = null;
                }

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARInvoice.salesPersonID>(graph.Document.Cache, invoice);

                if (sp == null || sp.IsActive == false)
                {
                    invoice.SalesPersonID = null;
                }

                invoice = graph.Document.Insert(invoice);
            }

            TX.TaxAttribute.SetTaxCalc <ARTran.taxCategoryID>(graph.Transactions.Cache, null, TX.TaxCalc.ManualCalc);

            graph.FieldDefaulting.AddHandler <ARTran.salesPersonID>((sender, e) =>
            {
                e.NewValue = null;
                e.Cancel   = true;
            });

            decimal roundedTotalDistributedLinesAmt = 0m;

            foreach (ARTran srcTran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >,
                                                                And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr))
            {
                ARTran tran = PXCache <ARTran> .CreateCopy(srcTran);

                ARTranRUTROT tranRR = RUTROTHelper.GetExtensionNullable <ARTran, ARTranRUTROT>(tran);

                if (tranRR.IsRUTROTDeductible != true)
                {
                    continue;
                }

                tran.TranType = graph.Document.Current.DocType;
                tran.RefNbr   = graph.Document.Current.RefNbr;
                string origDrCr = tran.DrCr;
                tran.DrCr                        = null;
                tran.Released                    = null;
                tran.CuryInfoID                  = null;
                tran.SOOrderNbr                  = null;
                tran.SOShipmentNbr               = null;
                tran.OrigInvoiceDate             = tran.TranDate;
                tran.NoteID                      = null;
                tran.ManualPrice                 = true;
                tran.CuryTranAmt                 = Math.Floor(tranRR.CuryRUTROTAvailableAmt ?? 0m);
                roundedTotalDistributedLinesAmt += tran.CuryTranAmt ?? 0m;
                tranRR.IsRUTROTDeductible        = false;

                if (!string.IsNullOrEmpty(tran.DeferredCode))
                {
                    DRSchedule schedule = PXSelect <DRSchedule,
                                                    Where <DRSchedule.module, Equal <BQLConstants.moduleAR>,
                                                           And <DRSchedule.docType, Equal <Required <DRSchedule.docType> >,
                                                                And <DRSchedule.refNbr, Equal <Required <DRSchedule.refNbr> >,
                                                                     And <DRSchedule.lineNbr, Equal <Required <DRSchedule.lineNbr> > > > > > > .
                                          Select(graph, doc.DocType, doc.RefNbr, tran.LineNbr);

                    if (schedule != null)
                    {
                        tran.DefScheduleID = schedule.ScheduleID;
                    }
                }

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARTran.salesPersonID>(graph.Transactions.Cache, tran);

                if (sp == null || sp.IsActive == false)
                {
                    tran.SalesPersonID = null;
                }

                ARTran insertedTran = graph.Transactions.Insert(tran);
                PXNoteAttribute.CopyNoteAndFiles(graph.Transactions.Cache, srcTran, graph.Transactions.Cache, insertedTran);

                insertedTran.ManualDisc = true;

                insertedTran.TaxCategoryID = null;
                graph.Transactions.Update(insertedTran);
            }

            decimal distributedFee = (rutrot.CuryDistributedAmt ?? 0m) - roundedTotalDistributedLinesAmt;

            if (distributedFee != 0m)
            {
                foreach (ARTran artran in graph.Transactions.Cache.Inserted)
                {
                    if (Math.Round(distributedFee) == 0m)
                    {
                        break;
                    }
                    if (artran.CuryTranAmt != 0m)
                    {
                        artran.CuryTranAmt += Math.Sign(distributedFee);
                        distributedFee     -= Math.Sign(distributedFee);
                    }

                    graph.Transactions.Update(artran);
                }
            }

            graph.Document.Current.CuryOrigDocAmt = graph.Document.Current.CuryDocBal;
            graph.Document.Cache.Update(graph.Document.Current);

            graph.RowInserting.AddHandler <ARSalesPerTran>((sender, e) => { e.Cancel = true; });

            foreach (ARSalesPerTran salespertran in PXSelect <ARSalesPerTran, Where <ARSalesPerTran.docType, Equal <Required <ARSalesPerTran.docType> >,
                                                                                     And <ARSalesPerTran.refNbr, Equal <Required <ARSalesPerTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr))
            {
                ARSalesPerTran newtran = PXCache <ARSalesPerTran> .CreateCopy(salespertran);

                newtran.DocType         = graph.Document.Current.DocType;
                newtran.RefNbr          = graph.Document.Current.RefNbr;
                newtran.Released        = false;
                newtran.CuryInfoID      = null;
                newtran.CuryCommnblAmt *= -1m;
                newtran.CuryCommnAmt   *= -1m;

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARSalesPerTran.salespersonID>(graph.salesPerTrans.Cache, newtran);

                if (!(sp == null || sp.IsActive == false))
                {
                    graph.salesPerTrans.Update(newtran);
                }
            }

            var discountDetailsSet = PXSelect <ARInvoiceDiscountDetail,
                                               Where <ARInvoiceDiscountDetail.docType, Equal <Required <ARInvoice.docType> >,
                                                      And <ARInvoiceDiscountDetail.refNbr, Equal <Required <ARInvoice.refNbr> > > >,
                                               OrderBy <Asc <ARInvoiceDiscountDetail.docType,
                                                             Asc <ARInvoiceDiscountDetail.refNbr> > > >
                                     .Select(graph, doc.DocType, doc.RefNbr);

            foreach (ARInvoiceDiscountDetail discountDetail in discountDetailsSet)
            {
                ARInvoiceDiscountDetail newDiscountDetail = PXCache <ARInvoiceDiscountDetail> .CreateCopy(discountDetail);

                newDiscountDetail.DocType  = graph.Document.Current.DocType;
                newDiscountDetail.RefNbr   = graph.Document.Current.RefNbr;
                newDiscountDetail.IsManual = true;
                DiscountEngineProvider.GetEngineFor <ARTran, ARInvoiceDiscountDetail>().UpdateDiscountDetail(graph.ARDiscountDetails.Cache, graph.ARDiscountDetails, newDiscountDetail);
            }

            graph.Save.Press();

            if (docType == ARDocType.CreditMemo && !OnRelease)
            {
                CreateAdjustment(graph, doc, graph.Document.Current);
            }
        }
        public virtual List <Balance> Run(PMTask task)
        {
            if (task.BillingID == null)
            {
                throw new PXException(Messages.BillingIDIsNotDefined);
            }

            Dictionary <string, Balance> balances = new Dictionary <string, Balance>();

            DateTime?     lastDate;
            List <PMTran> expenseTrans   = CreateExpenseTransactions(task, out lastDate);
            List <long>   expenseTranIds = new List <long>();

            Debug.Print("Created Expense Transactions:");
            Debug.Indent();
            foreach (PMTran tran in expenseTrans)
            {
                expenseTranIds.Add(tran.TranID.Value);
                Debug.Print("TranID:{0} AccountGroup:{1}, InventoryID={2}, Qty={3}, Amt={4}, Allocated={5}, Released={6}, Billed={7}, Date={8}", tran.TranID, AccountGroupFromID(tran.AccountGroupID), InventoryFromID(tran.InventoryID), tran.Qty, tran.Amount, tran.Allocated, tran.Released, tran.Billed, tran.Date);
            }
            Debug.Unindent();

            if (expenseTrans.Count == 0)
            {
                PXTrace.WriteError(Messages.FailedToEmulateExpenses, task.TaskCD);
                return(new List <Balance>());
            }

            PMAllocator ae = PXGraph.CreateInstance <PMAllocator>();

            ae.SourceTransactions = expenseTrans;
            foreach (PMTran tran in expenseTrans)
            {
                ae.Transactions.Insert(tran);
            }
            ae.OverrideAllocationDate = lastDate;
            ae.Execute(task);
            Debug.Print("After Allocation:");
            Debug.Indent();
            foreach (PMTran tran in ae.Transactions.Cache.Inserted)
            {
                tran.Released = true;
                Transactions.Cache.Update(tran);

                if (expenseTranIds.Contains(tran.TranID.Value))
                {
                    continue;
                }

                int    inventoryID = tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID;
                string key         = string.Format("{0}.{1}", tran.AccountGroupID, inventoryID);

                if (!balances.ContainsKey(key))
                {
                    Balance b = new Balance();
                    b.AccountGroupID = tran.AccountGroupID.Value;
                    b.InventoryID    = inventoryID;

                    balances.Add(key, b);
                }

                Debug.Print("TranID:{0} AccountGroup:{1}, InventoryID={2}, Qty={3}, Amt={4}, Allocated={5}, Released={6}, Billed={7}, Date={8}", tran.TranID, AccountGroupFromID(tran.AccountGroupID), InventoryFromID(tran.InventoryID), tran.Qty, tran.Amount, tran.Allocated, tran.Released, tran.Billed, tran.Date);
            }
            Debug.Unindent();

            DateTime billingDate = lastDate.Value.AddDays(1);

            //Get ARTrans for Bill:
            Debug.Print("Bill using the following Billing date={0}", billingDate);

            PMBillEngine engine = PXGraph.CreateInstance <PMBillEngine>();

            engine.IsEmulation = true;
            engine.FieldVerifying.AddHandler <PMTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
            engine.FieldVerifying.AddHandler <PMTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
            Debug.Print("Transactions passed to BillTask:");
            Debug.Indent();
            foreach (PMTran tran in Transactions.Cache.Cached)
            {
                if (expenseTranIds.Contains(tran.TranID.Value))
                {
                    continue;
                }
                engine.Transactions.Insert(tran);
                Debug.Print("TranID:{0} AccountGroup:{1}, InventoryID={2}, Qty={3}, Amt={4}, Allocated={5}, Released={6}, Billed={7}, Date={8}", tran.TranID, AccountGroupFromID(tran.AccountGroupID), InventoryFromID(tran.InventoryID), tran.Qty, tran.Amount, tran.Allocated, tran.Released, tran.Billed, tran.Date);
            }
            Debug.Unindent();

            List <PMBillEngine.BillingData> arTrans = engine.BillTask(task, billingDate);

            //Create ARInvoice to DEFAULT Accounts and SubAccounts.
            ARInvoiceEntry invoiceEntry = PXGraph.CreateInstance <ARInvoiceEntry>();

            //Project and Task is in Planning State - thus suppress verification:
            invoiceEntry.FieldVerifying.AddHandler <ARInvoice.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
            invoiceEntry.FieldVerifying.AddHandler <ARTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
            invoiceEntry.FieldVerifying.AddHandler <ARTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
            ARInvoice invoice = new ARInvoice();

            invoice.DocType = ARDocType.Invoice;

            invoice = PXCache <ARInvoice> .CreateCopy(invoiceEntry.Document.Insert(invoice));

            invoice.DocDate            = billingDate;
            invoice.CustomerID         = task.CustomerID;
            invoice.CustomerLocationID = task.LocationID;
            invoice.ProjectID          = task.ProjectID;
            invoice = (ARInvoice)invoiceEntry.Document.Update(invoice);

            CurrencyInfo curyinfo = (CurrencyInfo)invoiceEntry.Caches[typeof(CurrencyInfo)].Current;

            foreach (PMBillEngine.BillingData data in arTrans)
            {
                decimal curyamount;
                PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, (data.Tran.UnitPrice ?? 0), out curyamount);
                data.Tran.CuryUnitPrice = curyamount;
                PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, (data.Tran.ExtPrice ?? 0), out curyamount);
                data.Tran.CuryExtPrice     = curyamount;
                data.Tran.CuryTranAmt      = data.Tran.CuryExtPrice;
                data.Tran.FreezeManualDisc = true;
                ARTran newTran = (ARTran)invoiceEntry.Caches[typeof(ARTran)].Insert(data.Tran);
            }

            ARInvoice oldInvoice = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].CreateCopy(invoice);

            invoice.CuryOrigDocAmt = invoice.CuryDocBal;
            invoiceEntry.Caches[typeof(ARInvoice)].RaiseRowUpdated(invoice, oldInvoice);

            Debug.Print("AR Trans:");
            Debug.Indent();

            foreach (ARTran tran in invoiceEntry.Transactions.Select())
            {
                if (tran.TaskID == task.TaskID)
                {
                    Debug.Print("InventoryID={0}, Qty={1}, Amt={2}", InventoryFromID(tran.InventoryID), tran.Qty, tran.TranAmt);

                    Account acct = PXSelect <Account, Where <Account.accountID, Equal <Required <Account.accountID> > > > .Select(invoiceEntry, tran.AccountID);

                    if (acct.AccountGroupID == null)
                    {
                        throw new PXException("Failed to emulate billing. The Sales Account in the Invoice is not mapped to any Account Group.");
                    }

                    string key = string.Format("{0}.{1}", acct.AccountGroupID, tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID);

                    if (balances.ContainsKey(key))
                    {
                        balances[key].Amount   += tran.TranAmt ?? 0;
                        balances[key].Quantity += tran.Qty ?? 0;
                    }
                    else
                    {
                        Balance b = new Balance();
                        b.AccountGroupID = acct.AccountGroupID.Value;
                        b.InventoryID    = tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID;
                        b.Amount         = tran.TranAmt ?? 0;
                        b.Quantity       = tran.Qty ?? 0;

                        balances.Add(key, b);
                    }
                }
            }

            return(new List <Balance>(balances.Values));
        }
Esempio n. 8
0
        public static BranchRUTROT GetBranchRUTROT(ARInvoiceEntry graph)
        {
            GL.Branch branch = PXSelect <GL.Branch, Where <GL.Branch.branchID, Equal <Current <AccessInfo.branchID> > > > .Select(graph);

            return(RUTROTHelper.GetExtensionNullable <GL.Branch, BranchRUTROT>(branch));
        }
Esempio n. 9
0
        public virtual void GenerateProc(Schedule s, short Times, DateTime runDate)
        {
            List <ScheduleDet> sd = GL.ScheduleProcess.MakeSchedule(this, s, Times, runDate);

            ARInvoiceEntry docgraph = CreateGraph();

            foreach (ScheduleDet sdet in sd)
            {
                foreach (PXResult <ARInvoice, Customer, CurrencyInfo> res in PXSelectJoin <ARInvoice, InnerJoin <Customer, On <Customer.bAccountID, Equal <ARInvoice.customerID> >, InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <ARInvoice.curyInfoID> > > >, Where <ARInvoice.scheduleID, Equal <Required <ARInvoice.scheduleID> >, And <ARInvoice.scheduled, Equal <boolTrue> > > > .Select(this, s.ScheduleID))
                {
                    docgraph.Clear();
                    docgraph.customer.Current = (Customer)res;
                    ARInvoice    apdoc = (ARInvoice)res;
                    CurrencyInfo info  = (CurrencyInfo)res;

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

                    new_info.CuryInfoID = null;
                    new_info            = docgraph.currencyinfo.Insert(new_info);

                    ARInvoice new_ardoc = PXCache <ARInvoice> .CreateCopy(apdoc);

                    new_ardoc.CuryInfoID          = new_info.CuryInfoID;
                    new_ardoc.DocDate             = sdet.ScheduledDate;
                    new_ardoc.FinPeriodID         = sdet.ScheduledPeriod;
                    new_ardoc.TranPeriodID        = null;
                    new_ardoc.DueDate             = null;
                    new_ardoc.DiscDate            = null;
                    new_ardoc.CuryOrigDiscAmt     = null;
                    new_ardoc.OrigDiscAmt         = null;
                    new_ardoc.RefNbr              = null;
                    new_ardoc.Scheduled           = false;
                    new_ardoc.CuryLineTotal       = 0m;
                    new_ardoc.CuryVatTaxableTotal = 0m;
                    new_ardoc.CuryVatExemptTotal  = 0m;
                    new_ardoc.NoteID              = null;
                    bool forceClear = false;
                    bool clearPM    = false;
                    if (new_ardoc.PMInstanceID.HasValue)
                    {
                        PXResult <CustomerPaymentMethod, CA.PaymentMethod> pmiResult = (PXResult <CustomerPaymentMethod, CA.PaymentMethod>) PXSelectJoin <CustomerPaymentMethod, InnerJoin <CA.PaymentMethod, On <CA.PaymentMethod.paymentMethodID, Equal <CustomerPaymentMethod.paymentMethodID> > >, Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .Select(docgraph, new_ardoc.PMInstanceID);

                        if (pmiResult != null)
                        {
                            CustomerPaymentMethod pmInstance    = pmiResult;
                            CA.PaymentMethod      paymentMethod = pmiResult;
                            if (pmInstance == null || pmInstance.IsActive != true || paymentMethod.IsActive != true || paymentMethod.UseForAR != true)
                            {
                                clearPM    = true;
                                forceClear = true;
                            }
                        }
                        else
                        {
                            clearPM    = true;
                            forceClear = true;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(new_ardoc.PaymentMethodID) == false)
                        {
                            CA.PaymentMethod pm = PXSelect <CA.PaymentMethod, Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > > .Select(docgraph, new_ardoc.PaymentMethodID);

                            if (pm == null || pm.IsActive != true || pm.UseForAR != true)
                            {
                                clearPM    = true;
                                forceClear = true;
                            }
                        }
                    }

                    if (clearPM)
                    {
                        new_ardoc.PMInstanceID    = null;
                        new_ardoc.PaymentMethodID = null;
                        new_ardoc.CashAccountID   = null;
                    }

                    new_ardoc = docgraph.Document.Insert(new_ardoc);

                    //force creditrule back
                    docgraph.customer.Current = (Customer)res;

                    if (forceClear == true)
                    {
                        ARInvoice copy = PXCache <ARInvoice> .CreateCopy(new_ardoc);

                        copy.PMInstanceID    = null;
                        copy.PaymentMethodID = null;
                        copy.CashAccountID   = null;
                        new_ardoc            = docgraph.Document.Update(copy);
                    }
                    AddressAttribute.CopyRecord <ARInvoice.billAddressID>(docgraph.Document.Cache, new_ardoc, apdoc, false);
                    ContactAttribute.CopyRecord <ARInvoice.billContactID>(docgraph.Document.Cache, new_ardoc, apdoc, false);

                    TaxAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    PXNoteAttribute.SetNote(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetNote(Caches[typeof(ARInvoice)], apdoc));
                    PXNoteAttribute.SetFileNotes(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetFileNotes(Caches[typeof(ARInvoice)], apdoc));

                    foreach (ARTran aptran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >, And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        ARTran new_aptran = PXCache <ARTran> .CreateCopy(aptran);

                        new_aptran.RefNbr     = null;
                        new_aptran.CuryInfoID = null;
                        docgraph.Transactions.Insert(new_aptran);
                    }

                    foreach (ARTaxTran tax in PXSelect <ARTaxTran, Where <ARTaxTran.tranType, Equal <Required <ARTaxTran.tranType> >, And <ARTaxTran.refNbr, Equal <Required <ARTaxTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        ARTaxTran new_artax = new ARTaxTran();
                        new_artax.TaxID = tax.TaxID;

                        new_artax = docgraph.Taxes.Insert(new_artax);

                        if (new_artax != null)
                        {
                            new_artax = PXCache <ARTaxTran> .CreateCopy(new_artax);

                            new_artax.TaxRate        = tax.TaxRate;
                            new_artax.CuryTaxableAmt = tax.CuryTaxableAmt;
                            new_artax.CuryTaxAmt     = tax.CuryTaxAmt;
                            new_artax = docgraph.Taxes.Update(new_artax);
                        }
                    }

                    docgraph.Save.Press();
                }
                s.LastRunDate = sdet.ScheduledDate;
                Running_Schedule.Cache.Update(s);
            }

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                Running_Schedule.Cache.Persist(PXDBOperation.Update);
                ts.Complete(this);
            }
            Running_Schedule.Cache.Persisted(false);
        }
Esempio n. 10
0
        public virtual void openDocument()
        {
            FSCreatedDoc postingBatchDetailRow = BatchDetailsInfo.Current;

            if (postingBatchDetailRow.PostTo == ID.Batch_PostTo.SO)
            {
                if (PXAccess.FeatureInstalled <FeaturesSet.distributionModule>())
                {
                    SOOrderEntry graphSOOrderEntry = PXGraph.CreateInstance <SOOrderEntry>();
                    graphSOOrderEntry.Document.Current = graphSOOrderEntry.Document.Search <SOOrder.orderNbr>(postingBatchDetailRow.CreatedRefNbr, postingBatchDetailRow.CreatedDocType);
                    throw new PXRedirectRequiredException(graphSOOrderEntry, null)
                          {
                              Mode = PXBaseRedirectException.WindowMode.NewWindow
                          };
                }
            }
            else if (postingBatchDetailRow.PostTo == ID.Batch_PostTo.AR)
            {
                ARInvoiceEntry graphARInvoiceEntry = PXGraph.CreateInstance <ARInvoiceEntry>();
                graphARInvoiceEntry.Document.Current = graphARInvoiceEntry.Document.Search <ARInvoice.refNbr>(postingBatchDetailRow.CreatedRefNbr, postingBatchDetailRow.CreatedDocType);
                throw new PXRedirectRequiredException(graphARInvoiceEntry, null)
                      {
                          Mode = PXBaseRedirectException.WindowMode.NewWindow
                      };
            }
            else if (postingBatchDetailRow.PostTo == ID.Batch_PostTo.SI)
            {
                SOInvoiceEntry graphSOInvoiceEntry = PXGraph.CreateInstance <SOInvoiceEntry>();
                graphSOInvoiceEntry.Document.Current = graphSOInvoiceEntry.Document.Search <ARInvoice.refNbr>(postingBatchDetailRow.CreatedRefNbr, postingBatchDetailRow.CreatedDocType);
                throw new PXRedirectRequiredException(graphSOInvoiceEntry, null)
                      {
                          Mode = PXBaseRedirectException.WindowMode.NewWindow
                      };
            }
            else if (postingBatchDetailRow.PostTo == ID.Batch_PostTo.AP)
            {
                APInvoiceEntry graphAPInvoiceEntry = PXGraph.CreateInstance <APInvoiceEntry>();
                graphAPInvoiceEntry.Document.Current = graphAPInvoiceEntry.Document.Search <APInvoice.refNbr>(postingBatchDetailRow.CreatedRefNbr, postingBatchDetailRow.CreatedDocType);
                throw new PXRedirectRequiredException(graphAPInvoiceEntry, null)
                      {
                          Mode = PXBaseRedirectException.WindowMode.NewWindow
                      };
            }
            else if (postingBatchDetailRow.PostTo == ID.Batch_PostTo.IN)
            {
                INIssueEntry graphINIssueEntry = PXGraph.CreateInstance <INIssueEntry>();
                graphINIssueEntry.issue.Current = graphINIssueEntry.issue.Search <INRegister.refNbr>(postingBatchDetailRow.CreatedRefNbr, postingBatchDetailRow.CreatedDocType);
                throw new PXRedirectRequiredException(graphINIssueEntry, null)
                      {
                          Mode = PXBaseRedirectException.WindowMode.NewWindow
                      };
            }
            else if (postingBatchDetailRow.PostTo == ID.Batch_PostTo.PM)
            {
                RegisterEntry graphRegisterEntry = PXGraph.CreateInstance <RegisterEntry>();
                graphRegisterEntry.Document.Current = graphRegisterEntry.Document.Search <PMRegister.refNbr>(postingBatchDetailRow.CreatedRefNbr, postingBatchDetailRow.CreatedDocType);
                throw new PXRedirectRequiredException(graphRegisterEntry, null)
                      {
                          Mode = PXBaseRedirectException.WindowMode.NewWindow
                      };
            }
        }
        private static ARInvoice InsertFeeInvoice(ARDunningLetter doc, decimal dunningFee)
        {
            ARInvoiceEntry invGraph = PXGraph.CreateInstance <ARInvoiceEntry>();

            int?   organizationID = PXAccess.GetParentOrganizationID(doc.BranchID);
            string finPeriodID    = invGraph.FinPeriodRepository.GetPeriodIDFromDate(doc.DunningLetterDate, organizationID);

            invGraph.FinPeriodUtils.ValidateFinPeriod(doc.SingleToArray(), m => finPeriodID, m => m.BranchID.SingleToArray());

            ARSetup setup = PXSelect <ARSetup> .Select(invGraph);

            Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <ARDunningLetter.bAccountID> > > > .Select(invGraph, doc.BAccountID);

            CS.Numbering numbering = PXSelect <CS.Numbering,
                                               Where <CS.Numbering.numberingID, Equal <Required <ARSetup.dunningFeeNumberingID> > > > .Select(invGraph, setup.DunningFeeNumberingID);

            if (setup.DunningFeeInventoryID == null)
            {
                throw new PXException(Messages.DunningLetterEmptyInventory);
            }

            IN.InventoryItem item = PXSelect <IN.InventoryItem,
                                              Where <IN.InventoryItem.inventoryID, Equal <Required <ARSetup.dunningFeeInventoryID> > > > .Select(invGraph, setup.DunningFeeInventoryID);

            if (item == null)
            {
                throw new PXException(Messages.DunningLetterEmptyInventory);
            }
            if (item.SalesAcctID == null)
            {
                throw new PXException(Messages.DunningProcessFeeEmptySalesAccount);
            }


            ARInvoice feeInvoice = new ARInvoice
            {
                DocType = ARDocType.Invoice
            };

            if (numbering != null)
            {
                CS.AutoNumberAttribute.SetNumberingId <ARInvoice.refNbr>(invGraph.Document.Cache, feeInvoice.DocType, numbering.NumberingID);
            }
            feeInvoice = (ARInvoice)invGraph.Document.Cache.CreateCopy(invGraph.Document.Insert(feeInvoice));

            feeInvoice.Released           = false;
            feeInvoice.Voided             = false;
            feeInvoice.BranchID           = doc.BranchID;
            feeInvoice.DocDate            = doc.DunningLetterDate;
            feeInvoice.CustomerID         = customer.BAccountID;
            feeInvoice.DocDesc            = Messages.DunningLetterFee;
            feeInvoice.CustomerLocationID = customer.DefLocationID;
            feeInvoice.CuryID             = customer.AllowOverrideCury == false && customer.CuryID != null
                                ? customer.CuryID
                                : ((GL.Company)PXSelect <GL.Company> .Select(invGraph)).BaseCuryID;

            if (setup.DunningFeeTermID != null)
            {
                feeInvoice.TermsID = setup.DunningFeeTermID;
            }


            invGraph.Document.Update(feeInvoice);


            decimal      curyVal;
            CurrencyInfo curyInfo = invGraph.currencyinfo.Select();

            PXCurrencyAttribute.PXCurrencyHelper.CuryConvCury(invGraph.Caches[typeof(CurrencyInfo)], curyInfo, dunningFee, out curyVal);

            ARTran detail = new ARTran
            {
                BranchID      = doc.BranchID,
                Qty           = 1,
                CuryUnitPrice = curyVal,
                InventoryID   = setup.DunningFeeInventoryID,
                AccountID     = item.SalesAcctID,
                SubID         = item.SalesSubID
            };

            invGraph.Transactions.Insert(detail);

            feeInvoice = PXCache <ARInvoice> .CreateCopy(invGraph.Document.Current);

            feeInvoice.OrigDocAmt     = feeInvoice.DocBal;
            feeInvoice.CuryOrigDocAmt = feeInvoice.CuryDocBal;
            feeInvoice.Hold           = false;
            invGraph.Document.Update(feeInvoice);
            invGraph.Save.Press();

            if (setup.AutoReleaseDunningFee == true)
            {
                invGraph.release.Press();
            }
            return(invGraph.Document.Current);
        }
Esempio n. 12
0
        protected virtual void InsertARTran(ARInvoiceEntry arGraph, EPExpenseClaimDetails row, decimal signOperation, decimal tipQty = 1m, bool isTipTransaction = false)
        {
            CurrencyInfo curyInfo = PXSelect <CurrencyInfo> .Search <CurrencyInfo.curyInfoID>(arGraph, row.CuryInfoID);

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


            ARTran tran = arGraph.Transactions.Insert();

            if (isTipTransaction)
            {
                IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                     Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(arGraph, epsetup.NonTaxableTipItem);

                tran.InventoryID = epsetup.NonTaxableTipItem;
                tran.Qty         = tipQty;
                tran.UOM         = tipItem.BaseUnit;
                tran.TranDesc    = tipItem.Descr;

                SetAmount(arGraph, row.CuryTipAmt, row.TipAmt, tipQty, signOperation, curyInfo, tran);
                tran = arGraph.Transactions.Update(tran);

                if (epsetup.UseReceiptAccountForTips == true)
                {
                    tran.AccountID = row.SalesAccountID;
                    tran.SubID     = row.SalesSubID;
                }
                else
                {
                    Location companyloc = (Location)PXSelectJoin <Location,
                                                                  InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                            And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                             InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                  Where <GL.Branch.branchID, Equal <Current <ARTran.branchID> > > > .Select(arGraph);

                    Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <Contract.contractID> > > > .Select(this, row.ContractID);

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

                    EPEmployee employee = (EPEmployee)PXSelect <EPEmployee> .Search <EPEmployee.bAccountID>(this, row != null?row.EmployeeID : null);

                    Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(arGraph.Caches[typeof(EPExpenseClaimDetails)], row);

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

                    object value = SubAccountMaskAttribute.MakeSub <EPSetup.salesSubMask>(arGraph, epsetup.SalesSubMask,
                                                                                          new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                          new Type[] { typeof(EPEmployee.salesSubID), typeof(IN.InventoryItem.salesSubID), typeof(Location.cSalesSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                    arGraph.Caches[typeof(ARTran)].RaiseFieldUpdating <ARTran.subID>(tran, ref value);
                    tran.SubID = (int?)value;
                }
            }
            else
            {
                tran.InventoryID = row.InventoryID;
                tran.Qty         = row.Qty * signOperation;
                tran.UOM         = row.UOM;
                tran             = arGraph.Transactions.Update(tran);
                tran.AccountID   = row.SalesAccountID;
                tran.SubID       = row.SalesSubID;
                tran.TranDesc    = row.TranDesc;

                //For gross taxes we can't put tranAmt. So we should use taxable amount
                EPTaxTran firstLevelTaxTran = null;
                foreach (EPTaxTran taxRow in PXSelect <EPTaxTran,
                                                       Where <EPTaxTran.claimDetailID, Equal <Required <EPTaxTran.claimDetailID> >,
                                                              And <EPTaxTran.isTipTax, Equal <False> > > > .Select(this, row.ClaimDetailID))
                {
                    if (firstLevelTaxTran == null || Math.Abs(firstLevelTaxTran.CuryTaxableAmt ?? 0m) > Math.Abs(taxRow.CuryTaxableAmt ?? 0m))
                    {
                        firstLevelTaxTran = taxRow;
                    }
                }
                decimal?curyAmt = firstLevelTaxTran?.CuryTaxableAmt ?? row.CuryTaxableAmt;
                decimal?amt     = firstLevelTaxTran?.TaxableAmt ?? row.TaxableAmt;
                SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran);
                tran = arGraph.Transactions.Update(tran);
                if (tran.CuryTaxableAmt != 0 && tran.CuryTaxableAmt != curyAmt)                 // indicates that we have gross/ iclusive taxes. In this case recalculation is required
                {
                    curyAmt = row.CuryTaxableAmt;
                    amt     = row.TaxableAmt;
                    SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran);
                }
            }
            tran.Date        = row.ExpenseDate;
            tran.ManualPrice = true;
            tran             = arGraph.Transactions.Update(tran);
            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], row, arGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.ar>());
        }
Esempio n. 13
0
        public virtual void Bill(CustomersList customer, EPCustomerBilling.BillingFilter filter)
        {
            ARInvoiceEntry arGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
            RegisterEntry  pmGraph = PXGraph.CreateInstance <RegisterEntry>();

            arGraph.Clear();
            pmGraph.Clear();

            PMRegister pmDoc = null;
            ARInvoice  arDoc = null;

            List <ARRegister>            doclist = new List <ARRegister>();
            List <EPExpenseClaimDetails> listOfDirectBilledClaims = new List <EPExpenseClaimDetails>();

            PXSelectBase <EPExpenseClaimDetails> select = new PXSelectJoin <EPExpenseClaimDetails,
                                                                            LeftJoin <Contract, On <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>,
                                                                                                    And <Where <Contract.baseType, Equal <CTPRType.contract>,
                                                                                                                Or <Contract.nonProject, Equal <True> > > > >,
                                                                                      LeftJoin <Account, On <EPExpenseClaimDetails.expenseAccountID, Equal <Account.accountID> > > >,
                                                                            Where <EPExpenseClaimDetails.released, Equal <boolTrue>,
                                                                                   And <EPExpenseClaimDetails.billable, Equal <boolTrue>,
                                                                                        And <EPExpenseClaimDetails.billed, Equal <boolFalse>,
                                                                                             And <EPExpenseClaimDetails.customerID, Equal <Required <EPExpenseClaimDetails.customerID> >,
                                                                                                  And <EPExpenseClaimDetails.customerLocationID, Equal <Required <EPExpenseClaimDetails.customerLocationID> >,
                                                                                                       And <EPExpenseClaimDetails.expenseDate, LessEqual <Required <EPExpenseClaimDetails.expenseDate> >,
                                                                                                            And <Where <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>,
                                                                                                                        Or <EPExpenseClaimDetails.contractID, IsNull> > > > > > > > >,
                                                                            OrderBy <Asc <EPExpenseClaimDetails.branchID> > >(this);

            arGraph.RowPersisted.AddHandler <ARInvoice>(
                delegate(PXCache sender, PXRowPersistedEventArgs e)
            {
                if (e.TranStatus == PXTranStatus.Open)
                {
                    foreach (EPExpenseClaimDetails row in listOfDirectBilledClaims.Select(claimdetail => Transactions.Locate(claimdetail)))
                    {
                        row.ARDocType = ((ARInvoice)e.Row).DocType;
                        row.ARRefNbr  = ((ARInvoice)e.Row).RefNbr;
                    }
                }
            });

            decimal signOperation = 1m;
            decimal tipQty        = 1m;

            PXResultset <EPExpenseClaimDetails> resultset = select.Select(customer.CustomerID, customer.LocationID, filter.EndDate);

            this.GetService <IFinPeriodUtils>()
            .ValidateFinPeriod <EPExpenseClaimDetails>(resultset.RowCast <EPExpenseClaimDetails>(),
                                                       m => filter.InvFinPeriodID, m => m.BranchID.SingleToArray());

            foreach (PXResult <EPExpenseClaimDetails, Contract, Account> res in resultset)
            {
                EPExpenseClaimDetails row = (EPExpenseClaimDetails)res;

                if (row.ContractID != null && !ProjectDefaultAttribute.IsNonProject(row.ContractID))
                {
                    if (pmDoc == null)
                    {
                        pmDoc             = (PMRegister)pmGraph.Document.Cache.Insert();
                        pmDoc.OrigDocType = PMOrigDocType.ExpenseClaim;
                        pmDoc.OrigDocNbr  = row.RefNbr;
                    }

                    PMTran usage = InsertPMTran(pmGraph, res);
                    if (usage.Released == true)                     //contract trans are created as released
                    {
                        UsageMaint.AddUsage(pmGraph.Transactions.Cache, usage.ProjectID, usage.InventoryID, usage.BillableQty ?? 0m, usage.UOM);
                    }
                }
                else
                {
                    if (arDoc == null || arDoc.BranchID != row.BranchID)
                    {
                        if (arDoc != null)
                        {
                            arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                            arGraph.Document.Update(arDoc);
                            arGraph.Save.Press();
                            listOfDirectBilledClaims.Clear();
                        }

                        EPExpenseClaimDetails summDetail = PXSelectJoinGroupBy <EPExpenseClaimDetails,
                                                                                LeftJoin <Contract, On <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>,
                                                                                                        And <Where <Contract.baseType, Equal <CTPRType.contract>,
                                                                                                                    Or <Contract.nonProject, Equal <True> > > > > >,
                                                                                Where <EPExpenseClaimDetails.released, Equal <boolTrue>,
                                                                                       And <EPExpenseClaimDetails.billable, Equal <boolTrue>,
                                                                                            And <EPExpenseClaimDetails.billed, Equal <boolFalse>,
                                                                                                 And <EPExpenseClaimDetails.customerID, Equal <Required <EPExpenseClaimDetails.customerID> >,
                                                                                                      And <EPExpenseClaimDetails.customerLocationID, Equal <Required <EPExpenseClaimDetails.customerLocationID> >,
                                                                                                           And <EPExpenseClaimDetails.expenseDate, LessEqual <Required <EPExpenseClaimDetails.expenseDate> >,
                                                                                                                And <EPExpenseClaimDetails.branchID, Equal <Required <EPExpenseClaimDetails.branchID> >,
                                                                                                                     And <Where <Contract.nonProject, Equal <True>,
                                                                                                                                 Or <EPExpenseClaimDetails.contractID, IsNull> > > > > > > > > >,
                                                                                Aggregate <Sum <EPExpenseClaimDetails.curyTranAmt> > >
                                                           .Select(this, customer.CustomerID, customer.LocationID, filter.EndDate, row.BranchID);

                        signOperation = summDetail.CuryTranAmt < 0 ? -1 : 1;

                        // OrigModule should be set before Insert() method
                        // to organize proper defaulting for any other fields
                        // which depend on OrigModule value.
                        //
                        arDoc            = new ARInvoice();
                        arDoc.OrigModule = BatchModule.EP;
                        arGraph.Document.Cache.SetValueExt <ARInvoice.docType>(arDoc,
                                                                               signOperation < 0 ? ARDocType.CreditMemo : ARDocType.Invoice);

                        arDoc = (ARInvoice)arGraph.Document.Cache.Insert(arDoc);

                        arGraph.Document.Cache.SetValueExt <ARInvoice.customerID>(arDoc, row.CustomerID);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.customerLocationID>(arDoc, row.CustomerLocationID);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.docDate>(arDoc, filter.InvoiceDate);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.branchID>(arDoc, row.BranchID);
                        arDoc.OrigRefNbr  = row.RefNbr;
                        arDoc             = arGraph.Document.Update(arDoc);
                        arDoc.FinPeriodID = filter.InvFinPeriodID;

                        if (Setup.Current.AutomaticReleaseAR == true)
                        {
                            arDoc.Hold = false;
                        }

                        doclist.Add(arDoc);
                    }

                    // Insert ARTran.
                    //
                    InsertARTran(arGraph, row, signOperation);
                    if ((row.CuryTipAmt ?? 0) != 0)
                    {
                        tipQty = signOperation < 0 == row.ClaimCuryTranAmtWithTaxes < 0 ? 1 : -1;
                        InsertARTran(arGraph, row, signOperation, tipQty, true);
                    }

                    listOfDirectBilledClaims.Add(row);
                }

                row.Billed = true;
                Transactions.Update(row);
            }

            if (arDoc != null)
            {
                arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                arGraph.Document.Update(arDoc);
                arGraph.Save.Press();
            }

            if (pmDoc != null)
            {
                pmGraph.Save.Press();
            }

            Persist(typeof(EPExpenseClaimDetails), PXDBOperation.Update);

            if (Setup.Current.AutomaticReleaseAR == true)
            {
                ARDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Esempio n. 14
0
        public virtual void GenerateProc(Schedule schedule, short times, DateTime runDate)
        {
            IEnumerable <ScheduleDet> occurrences = new Scheduler(this).MakeSchedule(schedule, times, runDate);

            ARInvoiceEntry invoiceEntry = CreateGraph();

            using (PXTransactionScope transactionScope = new PXTransactionScope())
            {
                foreach (ScheduleDet occurrence in occurrences)
                {
                    foreach (PXResult <ARInvoice, Customer, CurrencyInfo> scheduledInvoiceResult in PXSelectJoin <
                                 ARInvoice,
                                 InnerJoin <Customer, On <Customer.bAccountID, Equal <ARInvoice.customerID> >,
                                            InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <ARInvoice.curyInfoID> > > >,
                                 Where <
                                     ARInvoice.scheduleID, Equal <Required <ARInvoice.scheduleID> >,
                                     And <ARInvoice.scheduled, Equal <True> > > >
                             .Select(this, schedule.ScheduleID))
                    {
                        invoiceEntry.Clear();

                        invoiceEntry.customer.Current = scheduledInvoiceResult;
                        ARInvoice    scheduledInvoice             = scheduledInvoiceResult;
                        CurrencyInfo scheduledInvoiceCurrencyInfo = scheduledInvoiceResult;

                        ARInvoice newInvoice = InsertDocument(
                            invoiceEntry,
                            occurrence,
                            scheduledInvoiceResult,
                            scheduledInvoiceResult,
                            scheduledInvoiceCurrencyInfo);

                        InsertDetails(invoiceEntry, scheduledInvoice, newInvoice);

                        BalanceCalculation.ForceDocumentControlTotals(invoiceEntry, newInvoice);

                        try
                        {
                            invoiceEntry.Save.Press();
                        }
                        catch
                        {
                            if (invoiceEntry.Document.Cache.IsInsertedUpdatedDeleted)
                            {
                                throw;
                            }
                        }
                    }

                    schedule.LastRunDate = occurrence.ScheduledDate;
                    Running_Schedule.Cache.Update(schedule);
                }

                transactionScope.Complete(this);
            }

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                Running_Schedule.Cache.Persist(PXDBOperation.Update);
                ts.Complete(this);
            }

            Running_Schedule.Cache.Persisted(false);
        }
Esempio n. 15
0
        protected virtual ARInvoice InsertDocument(
            ARInvoiceEntry invoiceEntry,
            ScheduleDet occurrence,
            Customer customer,
            ARInvoice scheduledInvoice,
            CurrencyInfo scheduledInvoiceCurrencyInfo)
        {
            if (scheduledInvoice.Released == true)
            {
                throw new PXException(Messages.ScheduledDocumentAlreadyReleased);
            }

            // Cloning currency info is required because we want to preserve
            // (and not default) the currency rate type of the template document.
            // -
            CurrencyInfo newCurrencyInfo = PXCache <CurrencyInfo> .CreateCopy(scheduledInvoiceCurrencyInfo);

            newCurrencyInfo.CuryInfoID  = null;
            newCurrencyInfo.CuryRate    = null;
            newCurrencyInfo.CuryEffDate = occurrence.ScheduledDate;

            newCurrencyInfo = invoiceEntry.currencyinfo.Insert(newCurrencyInfo);

            ARInvoice newInvoice = PXCache <ARInvoice> .CreateCopy(scheduledInvoice);

            newInvoice.CuryInfoID          = newCurrencyInfo.CuryInfoID;
            newInvoice.DocDate             = occurrence.ScheduledDate;
            newInvoice.FinPeriodID         = occurrence.ScheduledPeriod;
            newInvoice.TranPeriodID        = null;
            newInvoice.DueDate             = null;
            newInvoice.DiscDate            = null;
            newInvoice.CuryOrigDiscAmt     = null;
            newInvoice.OrigDiscAmt         = null;
            newInvoice.RefNbr              = null;
            newInvoice.Scheduled           = false;
            newInvoice.CuryLineTotal       = 0m;
            newInvoice.CuryVatTaxableTotal = 0m;
            newInvoice.CuryVatExemptTotal  = 0m;
            newInvoice.NoteID              = null;
            newInvoice.IsTaxValid          = false;
            newInvoice.IsTaxPosted         = false;
            newInvoice.IsTaxSaved          = false;
            newInvoice.OrigDocType         = scheduledInvoice.DocType;
            newInvoice.OrigRefNbr          = scheduledInvoice.RefNbr;

            invoiceEntry.Document.Cache.SetDefaultExt <ARInvoice.printed>(newInvoice);
            invoiceEntry.Document.Cache.SetDefaultExt <ARInvoice.emailed>(newInvoice);

            bool forceClear         = false;
            bool clearPaymentMethod = false;

            if (newInvoice.PMInstanceID.HasValue)
            {
                PXResult <CustomerPaymentMethod, PaymentMethod> paymentMethodResult = (PXResult <CustomerPaymentMethod, PaymentMethod>)
                                                                                      PXSelectJoin <
                    CustomerPaymentMethod,
                    InnerJoin <PaymentMethod,
                               On <PaymentMethod.paymentMethodID, Equal <CustomerPaymentMethod.paymentMethodID> > >,
                    Where <
                        CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > >
                                                                                      .Select(invoiceEntry, newInvoice.PMInstanceID);

                if (paymentMethodResult != null)
                {
                    CustomerPaymentMethod customerPaymentMethod = paymentMethodResult;
                    PaymentMethod         paymentMethod         = paymentMethodResult;
                    if (customerPaymentMethod == null || customerPaymentMethod.IsActive != true || paymentMethod.IsActive != true || paymentMethod.UseForAR != true)
                    {
                        clearPaymentMethod = true;
                        forceClear         = true;
                    }
                }
                else
                {
                    clearPaymentMethod = true;
                    forceClear         = true;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(newInvoice.PaymentMethodID))
                {
                    PaymentMethod paymentMethod = PXSelect <
                        PaymentMethod,
                        Where <PaymentMethod.paymentMethodID, Equal <Required <PaymentMethod.paymentMethodID> > > >
                                                  .Select(invoiceEntry, newInvoice.PaymentMethodID);

                    if (paymentMethod == null || paymentMethod.IsActive != true || paymentMethod.UseForAR != true)
                    {
                        clearPaymentMethod = true;
                        forceClear         = true;
                    }
                }
            }

            if (clearPaymentMethod)
            {
                newInvoice.PMInstanceID    = null;
                newInvoice.PaymentMethodID = null;
                newInvoice.CashAccountID   = null;
            }

            newInvoice = invoiceEntry.Document.Insert(newInvoice);

            // Force credit rule back
            // -
            invoiceEntry.customer.Current = customer;

            if (forceClear == true)
            {
                ARInvoice copy = PXCache <ARInvoice> .CreateCopy(newInvoice);

                copy.PMInstanceID    = null;
                copy.PaymentMethodID = null;
                copy.CashAccountID   = null;
                newInvoice           = invoiceEntry.Document.Update(copy);
            }

            AddressAttribute.CopyRecord <ARInvoice.billAddressID>(invoiceEntry.Document.Cache, newInvoice, scheduledInvoice, false);
            ContactAttribute.CopyRecord <ARInvoice.billContactID>(invoiceEntry.Document.Cache, newInvoice, scheduledInvoice, false);

            CurrencyInfoAttribute.SetEffectiveDate <ARInvoice.docDate>(
                invoiceEntry.Document.Cache,
                new PXFieldUpdatedEventArgs(newInvoice, null, false));

            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(ARInvoice)], scheduledInvoice, invoiceEntry.Document.Cache, newInvoice);

            return(newInvoice);
        }