Esempio n. 1
0
        protected void ARInvoice_RowPersisting(PXCache sender, PXRowPersistingEventArgs e, PXRowPersisting del)
        {
            ARInvoice invoice = (ARInvoice)e.Row;

            if (invoice != null)
            {
                ARRegisterExt ext = PXCache <PX.Objects.AR.ARRegister> .GetExtension <ARRegisterExt>((PX.Objects.AR.ARInvoice) e.Row);

                //Validate fields
                if ((e.Operation & PXDBOperation.Command) != PXDBOperation.Delete && ext != null)
                {
                    if (ext.UsrContractTypeID == null)
                    {
                        throw new PXSetPropertyException <ARRegisterExt.usrContractTypeID>(
                                  "Enter a Contract Type.", PXErrorLevel.Error);
                    }
                    if (ext.UsrLineofBusiness == null)
                    {
                        throw new PXSetPropertyException <ARRegisterExt.usrLineofBusiness>(
                                  "Enter a Line of Business.", PXErrorLevel.Error);
                    }
                    if (invoice.DocType == ARDocType.DebitMemo ||
                        invoice.DocType == ARDocType.CreditMemo ||
                        invoice.DocType == ARDocType.SmallCreditWO)
                    {
                        if (ext.UsrReasonCodeID == null)
                        {
                            throw new PXSetPropertyException <ARRegisterExt.usrReasonCodeID>(
                                      "Enter a Reason Code.", PXErrorLevel.Error);
                        }
                    }
                }
                /* Document level discount */
                // Initializing the data view
                PXSelectBase <ARTran> select = new PXSelect <ARTran, Where <ARTran.tranType, Equal <Current <ARInvoice.docType> >,
                                                                            And <ARTran.refNbr, Equal <Current <ARInvoice.refNbr> >,
                                                                                 And <ARTran.deferredCode, IsNotNull> > >,
                                                             OrderBy <Asc <ARTran.tranType, Asc <ARTran.refNbr, Asc <ARTran.lineNbr> > > > >(Base);
                // Executing the data view
                PX.Objects.AR.ARTran trandeferredCode = select.SelectWindowed(0, 1, null);
                // Set the defferral code to first line item
                if (trandeferredCode != null)
                {
                    foreach (ARTran tran in Base.Discount_Row.Select())
                    {
                        Base.Discount_Row.Current = tran;
                        Base.Discount_Row.Current.DeferredCode = trandeferredCode.DeferredCode;
                        Base.Discount_Row.Update(Base.Discount_Row.Current);
                    }
                }
            }
            del(sender, e);
        }
Esempio n. 2
0
        public virtual IAddressBase GetToAddress(ARInvoice invoice, ARTran tran)
        {
            if (invoice.OrigModule == BatchModule.SO)
            {
                var soLine =
                    PXSelectJoin <SOAddress,
                                  InnerJoin <SOOrder, On <SOOrder.shipAddressID, Equal <SOAddress.addressID> >,
                                             LeftJoin <SOLine, On <SOLine.orderType, Equal <SOOrder.orderType>,
                                                                   And <SOLine.orderNbr, Equal <SOOrder.orderNbr> > >,
                                                       LeftJoin <Carrier, On <Carrier.carrierID, Equal <SOOrder.shipVia> > > > >,
                                  Where <SOOrder.orderType, Equal <Current <ARTran.sOOrderType> >,
                                         And <SOOrder.orderNbr, Equal <Current <ARTran.sOOrderNbr> >,
                                              And <Where <Current2 <ARTran.sOOrderLineNbr>, IsNull,
                                                          Or <Current2 <ARTran.sOOrderLineNbr>, Equal <SOLine.lineNbr> > > > > > >
                    .SelectSingleBound(Base, new[] { tran }).AsEnumerable()
                    .Cast <PXResult <SOAddress, SOOrder, SOLine, Carrier> >()
                    .FirstOrDefault();

                var dropShipAddress = GetDropShipDestinationAddress(tran, soLine);
                if (dropShipAddress != null)
                {
                    return(dropShipAddress);
                }

                var shipLine =
                    PXSelectJoin <SOAddress,
                                  InnerJoin <SOShipment, On <SOShipment.shipAddressID, Equal <SOAddress.addressID> >,
                                             LeftJoin <SOShipLine, On <SOShipLine.shipmentType, Equal <SOShipment.shipmentType>,
                                                                       And <SOShipLine.shipmentNbr, Equal <SOShipment.shipmentNbr> > >,
                                                       LeftJoin <Carrier, On <Carrier.carrierID, Equal <SOShipment.shipVia> > > > >,
                                  Where <SOShipment.shipmentType, Equal <Current <ARTran.sOShipmentType> >,
                                         And <SOShipment.shipmentNbr, Equal <Current <ARTran.sOShipmentNbr> >,
                                              And <Where <Current2 <ARTran.sOShipmentLineNbr>, IsNull,
                                                          Or <Current2 <ARTran.sOShipmentLineNbr>, Equal <SOShipLine.lineNbr> > > > > > >
                    .SelectSingleBound(Base, new[] { tran }).AsEnumerable()
                    .Cast <PXResult <SOAddress, SOShipment, SOShipLine, Carrier> >()
                    .FirstOrDefault();

                bool isCommonCarrier = shipLine == null
                                        ? ((Carrier)soLine)?.IsCommonCarrier == true
                                        : ((Carrier)shipLine)?.IsCommonCarrier == true;
                if (tran.SiteID != null && isCommonCarrier == false)
                {
                    return(GetFromAddress(invoice, tran));
                }

                return((tran.LineType == SOLineType.Freight || tran.SOShipmentLineNbr != null ? (SOAddress)shipLine : null).With(ValidAddressFrom <SOShipment.shipAddressID>)
                       ?? (tran.LineType == SOLineType.Freight || tran.SOOrderLineNbr != null ? (SOAddress)soLine : null).With(ValidAddressFrom <SOOrder.shipAddressID>)
                       ?? GetToAddress(invoice));
            }

            return(GetToAddress(invoice));
        }
Esempio n. 3
0
        protected virtual IEnumerable documentList()
        {
            foreach (ARInvoiceExt doc in PXSelect <ARInvoiceExt> .Select(this))
            {
                bool hasUnreleasedDocument = false;

                foreach (PXResult <ARRetainageInvoice, ARTran> res in PXSelectJoin <ARRetainageInvoice,
                                                                                    LeftJoin <ARTran, On <ARRetainageInvoice.paymentsByLinesAllowed, Equal <True>,
                                                                                                          And <ARTran.tranType, Equal <ARRetainageInvoice.docType>,
                                                                                                               And <ARTran.refNbr, Equal <ARRetainageInvoice.refNbr>,
                                                                                                                    And <ARTran.origLineNbr, Equal <Required <ARTran.origLineNbr> > > > > > >,
                                                                                    Where <ARRetainageInvoice.isRetainageDocument, Equal <True>,
                                                                                           And <ARRetainageInvoice.origDocType, Equal <Required <ARInvoice.docType> >,
                                                                                                And <ARRetainageInvoice.origRefNbr, Equal <Required <ARInvoice.refNbr> >,
                                                                                                     And <ARRetainageInvoice.released, NotEqual <True> > > > > >
                         .SelectSingleBound(this, null, doc.ARTranLineNbr, doc.DocType, doc.RefNbr))
                {
                    ARRetainageInvoice invoice = res;
                    ARTran             tran    = res;

                    if (invoice.PaymentsByLinesAllowed != true ||
                        tran.LineNbr != null)
                    {
                        hasUnreleasedDocument = true;
                    }
                }

                if (!hasUnreleasedDocument)
                {
                    ARRetainageFilter filter   = Filter.Current;
                    bool hasProjectTransaction = true;

                    if (doc.PaymentsByLinesAllowed != true &&
                        (filter.ProjectTaskID != null ||
                         filter.AccountGroupID != null ||
                         filter.CostCodeID != null ||
                         filter.InventoryID != null))
                    {
                        ARTran projectTran = SearchProjectTransaction(doc);
                        hasProjectTransaction = projectTran != null;
                    }

                    if (hasProjectTransaction)
                    {
                        yield return(doc);
                    }
                }
            }
        }
Esempio n. 4
0
        protected void buyPlasticBag()
        {
            ARTran aRTran = Base.Transactions.Cache.CreateInstance() as ARTran;

            TWNGUIPreferences GUIPreferences = SelectFrom <TWNGUIPreferences> .View.Select(Base);

            if (GUIPreferences.PlasticBag == null)
            {
                throw new MissingMemberException(TWMessages.NoPlasticBag);
            }

            aRTran.InventoryID = GUIPreferences.PlasticBag;
            aRTran.Qty         = 1;

            Base.Transactions.Cache.Insert(aRTran);
        }
        protected virtual void InsertDetails(ARInvoiceEntry invoiceEntry, ARInvoice scheduledInvoice, ARInvoice newInvoice)
        {
            foreach (ARTran originalLine in PXSelect <
                         ARTran,
                         Where <
                             ARTran.tranType, Equal <Required <ARTran.tranType> >,
                             And <ARTran.refNbr, Equal <Required <ARTran.refNbr> >,
                                  And <Where <
                                           ARTran.lineType, IsNull,
                                           Or <ARTran.lineType, NotEqual <SOLineType.discount> > > > > > >
                     .Select(invoiceEntry, scheduledInvoice.DocType, scheduledInvoice.RefNbr))
            {
                ARTran newLine = PXCache <ARTran> .CreateCopy(originalLine);

                newLine.FinPeriodID  = null;
                newLine.TranPeriodID = null;
                newLine.RefNbr       = null;
                newLine.CuryInfoID   = null;
                newLine.ManualPrice  = true;
                newLine.ManualDisc   = true;
                newLine.NoteID       = null;

                newLine = invoiceEntry.Transactions.Insert(newLine);

                PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(ARTran)], originalLine, invoiceEntry.Transactions.Cache, newLine);
            }

            foreach (ARInvoiceDiscountDetail originalDiscountDetail in PXSelect <
                         ARInvoiceDiscountDetail,
                         Where <
                             ARInvoiceDiscountDetail.docType, Equal <Required <ARInvoiceDiscountDetail.docType> >,
                             And <ARInvoiceDiscountDetail.refNbr, Equal <Required <ARInvoiceDiscountDetail.refNbr> > > > >
                     .Select(invoiceEntry, scheduledInvoice.DocType, scheduledInvoice.RefNbr))
            {
                ARInvoiceDiscountDetail newDiscountDetail =
                    PXCache <ARInvoiceDiscountDetail> .CreateCopy(originalDiscountDetail);

                newDiscountDetail.RefNbr     = null;
                newDiscountDetail.CuryInfoID = null;
                newDiscountDetail.IsManual   = true;

                DiscountEngineProvider.GetEngineFor <ARTran, ARInvoiceDiscountDetail>().InsertDiscountDetail(invoiceEntry.ARDiscountDetails.Cache, invoiceEntry.ARDiscountDetails, newDiscountDetail);
            }
        }
        protected virtual IAddressBase GetFromAddress(ARInvoice invoice, ARTran tran)
        {
            if (invoice.OrigModule == BatchModule.SO)
            {
                var soLine =
                    PXSelectJoin <Address,
                                  InnerJoin <INSite, On <INSite.addressID, Equal <Address.addressID> >,
                                             InnerJoin <SOLine, On <SOLine.siteID, Equal <INSite.siteID> > > >,
                                  Where <SOLine.orderType, Equal <Current <ARTran.sOOrderType> >,
                                         And <SOLine.orderNbr, Equal <Current <ARTran.sOOrderNbr> >,
                                              And <SOLine.lineNbr, Equal <Current <ARTran.sOOrderLineNbr> > > > > >
                    .SelectSingleBound(Base, new[] { tran })
                    .Cast <PXResult <Address, INSite, SOLine> >()
                    .FirstOrDefault();

                return(GetDropShipOriginAddress(tran, soLine)
                       ?? PXSelectJoin <Address,
                                        InnerJoin <INSite, On <INSite.addressID, Equal <Address.addressID> >,
                                                   InnerJoin <SOShipLine, On <SOShipLine.siteID, Equal <INSite.siteID>,
                                                                              And <SOShipLine.shipmentType, Equal <Current <ARTran.sOShipmentType> > > > > >,
                                        Where <SOShipLine.shipmentNbr, Equal <Current <ARTran.sOShipmentNbr> >,
                                               And <SOShipLine.lineNbr, Equal <Current <ARTran.sOShipmentLineNbr> > > > >
                       .SelectSingleBound(Base, new[] { tran })
                       .RowCast <Address>()
                       .FirstOrDefault()
                       .With(ValidAddressFrom <INSite.addressID>)
                       ?? (tran.LineType == SOLineType.Freight
                                                ? PXSelectJoin <Address,
                                                                InnerJoin <INSite, On <INSite.addressID, Equal <Address.addressID> >,
                                                                           InnerJoin <SOShipment, On <SOShipment.siteID, Equal <INSite.siteID> > > >,
                                                                Where <SOShipment.shipmentType, Equal <Current <ARTran.sOShipmentType> >,
                                                                       And <SOShipment.shipmentNbr, Equal <Current <ARTran.sOShipmentNbr> > > > >
                           .SelectSingleBound(Base, new[] { tran })
                           .RowCast <Address>()
                           .FirstOrDefault()
                           .With(ValidAddressFrom <INSite.addressID>)
                                                : null)
                       ?? ((Address)soLine).With(ValidAddressFrom <INSite.addressID>)
                       ?? GetFromAddress(invoice));                 // branch address
            }
            return(GetFromAddress(invoice));
        }
        private IAddressBase GetDropShipOriginAddress(ARTran tran, SOLine soLine)
        {
            if (soLine != null && tran.SOOrderLineNbr != null)
            {
                Boolean isDropShip    = soLine.POCreate == true && soLine.POSource == INReplenishmentSource.DropShipToOrder;
                Address vendorAddress = isDropShip
                                        ? PXSelectJoin <Address,
                                                        InnerJoin <Location, On <Location.defAddressID, Equal <Address.addressID> >,
                                                                   InnerJoin <PO.POReceipt, On <PO.POReceipt.vendorLocationID, Equal <Location.locationID> > > >,
                                                        Where <PO.POReceipt.receiptNbr, Equal <Current <ARTran.sOShipmentNbr> > > >
                                        .SelectSingleBound(Base, new[] { tran })
                                        .RowCast <Address>()
                                        .FirstOrDefault()
                                        : null;

                if (vendorAddress != null)
                {
                    return(vendorAddress.With(ValidAddressFrom <PO.POReceipt.vendorLocationID>));
                }
            }
            return(null);
        }
        private IAddressBase GetDropShipDestinationAddress(ARTran tran, SOLine soLine)
        {
            if (soLine != null && tran.SOOrderLineNbr != null)
            {
                Boolean      isDropShip      = soLine.POCreate == true && soLine.POSource == INReplenishmentSource.DropShipToOrder;
                IAddressBase dropShipAddress = isDropShip
                                        ? PXSelectJoin <PO.POAddress,
                                                        InnerJoin <PO.POOrder, On <PO.POOrder.shipAddressID, Equal <PO.POAddress.addressID> >,
                                                                   InnerJoin <PO.POReceiptLine, On <PO.POReceiptLine.pOType, Equal <PO.POOrder.orderType>,
                                                                                                    And <PO.POReceiptLine.pONbr, Equal <PO.POOrder.orderNbr> > > > >,
                                                        Where <PO.POReceiptLine.receiptNbr, Equal <Current <ARTran.sOShipmentNbr> >,
                                                               And <PO.POReceiptLine.lineNbr, Equal <Current <ARTran.sOShipmentLineNbr> > > > >
                                               .SelectSingleBound(Base, new[] { tran })
                                               .RowCast <PO.POAddress>()
                                               .FirstOrDefault()
                                        : null;

                if (dropShipAddress != null)
                {
                    return(dropShipAddress.With(ValidAddressFrom <PO.POOrder.shipAddressID>));
                }
            }
            return(null);
        }
Esempio n. 9
0
        public virtual CommitTaxRequest BuildCommitTaxRequestWithFrt(ARInvoice invoice)
        {
            if (invoice == null)
            {
                throw new PXArgumentException(nameof(invoice), ErrorMessages.ArgumentNullException);
            }

            Customer cust = (Customer)Base.customer.View.SelectSingleBound(new object[] { invoice });

            CR.Location loc = (CR.Location)Base.location.View.SelectSingleBound(new object[] { invoice });

            CommitTaxRequest request = new CommitTaxRequest();

            request.CompanyCode       = Base1.CompanyCodeFromBranch(invoice.TaxZoneID, invoice.BranchID);
            request.CurrencyCode      = invoice.CuryID;
            request.CustomerCode      = cust.AcctCD;
            request.TaxRegistrationID = loc?.TaxRegistrationID;
            IAddressBase fromAddress = Base1.GetFromAddress(invoice);
            IAddressBase toAddress   = Base1.GetToAddress(invoice);

            if (fromAddress == null)
            {
                throw new PXException(Messages.FailedGetFrom);
            }

            if (toAddress == null)
            {
                throw new PXException(Messages.FailedGetTo);
            }

            request.OriginAddress      = AddressConverter.ConvertTaxAddress(fromAddress);
            request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
            request.DocCode            = $"AR.{invoice.DocType}.{invoice.RefNbr}";
            request.DocDate            = invoice.DocDate.GetValueOrDefault();
            request.LocationCode       = GetExternalTaxProviderLocationCode <ARTran, ARTran.FK.Invoice.SameAsCurrent, ARTran.siteID>(invoice);
            request.CustomerUsageType  = invoice.AvalaraCustomerUsageType;

            if (!string.IsNullOrEmpty(invoice.ExternalTaxExemptionNumber))
            {
                request.ExemptionNo = invoice.ExternalTaxExemptionNumber;
            }

            request.DocType = Base1.GetTaxDocumentType(invoice);
            Sign sign = Base1.GetDocumentSign(invoice);

            PXSelectBase <ARTran> select = new PXSelectJoin <ARTran, LeftJoin <InventoryItem, On <InventoryItem.inventoryID, Equal <ARTran.inventoryID> >,
                                                                               LeftJoin <Account, On <Account.accountID, Equal <ARTran.accountID> > > >,
                                                             Where <ARTran.tranType, Equal <Current <ARInvoice.docType> >,
                                                                    And <ARTran.refNbr, Equal <Current <ARInvoice.refNbr> >,
                                                                         And <Where <ARTran.lineType, NotEqual <SOLineType.discount>, Or <ARTran.lineType, IsNull> > > > >,
                                                             OrderBy <Asc <ARTran.tranType, Asc <ARTran.refNbr, Asc <ARTran.lineNbr> > > > >(Base);

            request.Discount = Base.Document.Current.CuryDiscTot.GetValueOrDefault();
            DateTime?taxDate = invoice.OrigDocDate;

            bool applyRetainage = Base.ARSetup.Current?.RetainTaxes != true && invoice.IsOriginalRetainageDocument();

            /// <summary>
            /// Add the following condition and logic per Jira [IP-23]
            /// </summary>>
            string taxCategory = (Base as SOInvoiceEntry).FreightDetails.Current?.TaxCategoryID;

            if (invoice.CuryFreightTot > 0 && GL.Branch.PK.Find(Base, Base.Accessinfo.BranchID).CountryID == Country_US && invoice.TaxZoneID == TaxCloud && !string.IsNullOrEmpty(taxCategory))
            {
                var line = new TaxCartItem();
                line.Index              = short.MinValue;
                line.Quantity           = 1;
                line.UOM                = "EA";
                line.Amount             = sign * invoice.CuryFreightTot.GetValueOrDefault();
                line.Description        = PXMessages.LocalizeNoPrefix(SO.Messages.FreightDesc);
                line.DestinationAddress = request.DestinationAddress;
                line.OriginAddress      = request.OriginAddress;
                line.ItemCode           = "N/A";
                line.Discounted         = false;
                line.TaxCode            = taxCategory;

                request.CartItems.Add(line);
            }

            foreach (PXResult <ARTran, InventoryItem, Account> res in select.View.SelectMultiBound(new object[] { invoice }))
            {
                ARTran        tran         = (ARTran)res;
                InventoryItem item         = (InventoryItem)res;
                Account       salesAccount = (Account)res;

                var line = new TaxCartItem();
                line.Index              = tran.LineNbr ?? 0;
                line.Amount             = sign * (tran.CuryTranAmt.GetValueOrDefault() + (applyRetainage ? tran.CuryRetainageAmt.GetValueOrDefault() : 0m));
                line.Description        = tran.TranDesc;
                line.DestinationAddress = AddressConverter.ConvertTaxAddress(Base1.GetToAddress(invoice, tran));
                line.OriginAddress      = AddressConverter.ConvertTaxAddress(Base1.GetFromAddress(invoice, tran));
                line.ItemCode           = item.InventoryCD;
                line.Quantity           = Math.Abs(tran.Qty.GetValueOrDefault());
                line.UOM        = tran.UOM;
                line.Discounted = tran.LineType != SOLineType.Freight && request.Discount > 0;
                line.RevAcct    = salesAccount.AccountCD;

                line.TaxCode           = tran.TaxCategoryID;
                line.CustomerUsageType = tran.AvalaraCustomerUsageType;

                if (tran.OrigInvoiceDate != null)
                {
                    taxDate = tran.OrigInvoiceDate;
                }

                request.CartItems.Add(line);
            }

            if (applyRetainage)
            {
                var line = new TaxCartItem();
                line.Index              = invoice.LineCntr.GetValueOrDefault() + 1;
                line.Amount             = Sign.Minus * sign * invoice.CuryLineRetainageTotal.GetValueOrDefault();
                line.Description        = PXMessages.LocalizeFormatNoPrefix(AP.Messages.RetainageForTransactionDescription, GetLabel.For <ARDocType>(invoice.DocType), invoice.RefNbr);
                line.DestinationAddress = request.DestinationAddress;
                line.OriginAddress      = request.OriginAddress;
                line.ItemCode           = "Retainage";
                line.Discounted         = false;
                line.NonTaxable         = true;

                request.CartItems.Add(line);
            }

            if ((invoice.DocType == ARDocType.CreditMemo || invoice.DocType == ARDocType.CashReturn) && invoice.OrigDocDate != null)
            {
                request.TaxOverride.Reason          = Messages.ReturnReason;
                request.TaxOverride.TaxDate         = taxDate.Value;
                request.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
                sign = Sign.Minus;
            }

            return(request);
        }
        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. 11
0
        private static ARInvoice InsertFeeInvoice(ARDunningLetter doc, decimal dunningFee)
        {
            ARInvoiceEntry invGraph = PXGraph.CreateInstance <ARInvoiceEntry>();

            int?   organizationID = PXAccess.GetParentOrganizationID(doc.BranchID);
            string finPeriodID    = invGraph.GetService <IFinPeriodRepository>().GetPeriodIDFromDate(doc.DunningLetterDate, organizationID);

            invGraph.GetService <IFinPeriodUtils>().ValidateFinPeriod(doc.SingleToArray(), m => finPeriodID, m => m.BranchID.SingleToArray());

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

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

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

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

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

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


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

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

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

            invGraph.Document.Update(feeInvoice);


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

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

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

            invGraph.Transactions.Insert(detail);


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

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

            if (setup.AutoReleaseDunningFee == true)
            {
                invGraph.release.Press();
            }
            return(invGraph.Document.Current);
        }
        protected virtual GetTaxRequest BuildGetTaxRequest(ARCashSale invoice)
        {
            if (invoice == null)
            {
                throw new PXArgumentException(nameof(invoice), ErrorMessages.ArgumentNullException);
            }

            Customer cust = (Customer)Base.customer.View.SelectSingleBound(new object[] { invoice });
            Location loc  = (Location)Base.location.View.SelectSingleBound(new object[] { invoice });

            GetTaxRequest request = new GetTaxRequest();

            request.CompanyCode  = CompanyCodeFromBranch(invoice.TaxZoneID, invoice.BranchID);
            request.CurrencyCode = invoice.CuryID;
            request.CustomerCode = cust.AcctCD;
            IAddressBase fromAddress = GetFromAddress(invoice);
            IAddressBase toAddress   = GetToAddress(invoice);

            if (fromAddress == null)
            {
                throw new PXException(Messages.FailedGetFrom);
            }

            if (toAddress == null)
            {
                throw new PXException(Messages.FailedGetTo);
            }

            request.OriginAddress      = AddressConverter.ConvertTaxAddress(fromAddress);
            request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
            request.DocCode            = $"AR.{invoice.DocType}.{invoice.RefNbr}";
            request.DocDate            = invoice.DocDate.GetValueOrDefault();
            request.LocationCode       = GetExternalTaxProviderLocationCode(invoice);
            request.CustomerUsageType  = invoice.AvalaraCustomerUsageType;
            if (!string.IsNullOrEmpty(loc.CAvalaraExemptionNumber))
            {
                request.ExemptionNo = loc.CAvalaraExemptionNumber;
            }

            request.DocType = GetTaxDocumentType(invoice);
            Sign sign = GetDocumentSign(invoice);

            PXSelectBase <ARTran> select = new PXSelectJoin <ARTran,
                                                             LeftJoin <InventoryItem, On <InventoryItem.inventoryID, Equal <ARTran.inventoryID> >,
                                                                       LeftJoin <Account, On <Account.accountID, Equal <ARTran.accountID> > > >,
                                                             Where <ARTran.tranType, Equal <Current <ARCashSale.docType> >,
                                                                    And <ARTran.refNbr, Equal <Current <ARCashSale.refNbr> >,
                                                                         And <Where <ARTran.lineType, NotEqual <SOLineType.discount>, Or <ARTran.lineType, IsNull> > > > >,
                                                             OrderBy <Asc <ARTran.tranType, Asc <ARTran.refNbr, Asc <ARTran.lineNbr> > > > >(Base);

            request.Discount = GetDocDiscount().GetValueOrDefault();
            DateTime?taxDate = invoice.OrigDocDate;

            foreach (PXResult <ARTran, InventoryItem, Account> res in select.View.SelectMultiBound(new object[] { invoice }))
            {
                ARTran        tran         = (ARTran)res;
                InventoryItem item         = (InventoryItem)res;
                Account       salesAccount = (Account)res;

                var line = new TaxCartItem();
                line.Index              = tran.LineNbr ?? 0;
                line.Amount             = sign * tran.CuryTranAmt.GetValueOrDefault();
                line.Description        = tran.TranDesc;
                line.DestinationAddress = request.DestinationAddress;
                line.OriginAddress      = request.OriginAddress;
                line.ItemCode           = item.InventoryCD;
                line.Quantity           = Math.Abs(tran.Qty.GetValueOrDefault());
                line.Discounted         = request.Discount > 0;
                line.RevAcct            = salesAccount.AccountCD;
                line.TaxCode            = tran.TaxCategoryID;

                if (tran.OrigInvoiceDate != null)
                {
                    taxDate = tran.OrigInvoiceDate;
                }

                request.CartItems.Add(line);
            }

            if (invoice.DocType == ARDocType.CashReturn && invoice.OrigDocDate != null)
            {
                request.TaxOverride.Reason          = Messages.ReturnReason;
                request.TaxOverride.TaxDate         = taxDate.Value;
                request.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
            }

            return(request);
        }
Esempio n. 13
0
        private static void AddTaxesAndApplications(ARInvoiceEntry ie, PendingPPDCreditMemoApp doc, Customer customer, ARInvoice invoice)
        {
            ARTaxTran artaxMax               = null;
            decimal?  TaxTotal               = 0m;
            decimal?  InclusiveTotal         = 0m;
            decimal?  DiscountedTaxableTotal = 0m;
            decimal?  DiscountedPriceTotal   = 0m;
            decimal   CashDiscPercent        = (decimal)(doc.CuryAdjdPPDAmt / doc.InvCuryOrigDocAmt);

            PXResultset <ARTaxTran> taxes = PXSelectJoin <ARTaxTran,
                                                          InnerJoin <Tax, On <Tax.taxID, Equal <ARTaxTran.taxID> > >,
                                                          Where <ARTaxTran.module, Equal <BatchModule.moduleAR>,
                                                                 And <ARTaxTran.tranType, Equal <Required <ARTaxTran.tranType> >,
                                                                      And <ARTaxTran.refNbr, Equal <Required <ARTaxTran.refNbr> > > > > > .Select(ie, doc.AdjdDocType, doc.AdjdRefNbr);

            //add taxes
            foreach (PXResult <ARTaxTran, Tax> res in taxes)
            {
                Tax       tax   = res;
                ARTaxTran artax = PXCache <ARTaxTran> .CreateCopy(res);

                ARTaxTran artaxNew = ie.Taxes.Search <ARTaxTran.taxID>(artax.TaxID);

                if (artaxNew == null)
                {
                    artax.TranType    = null;
                    artax.RefNbr      = null;
                    artax.TaxPeriodID = null;
                    artax.Released    = false;
                    artax.Voided      = false;
                    artax.CuryInfoID  = invoice.CuryInfoID;

                    TaxBaseAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(ie.Transactions.Cache, null, TaxCalc.NoCalc);
                    artaxNew = ie.Taxes.Insert(artax);

                    artaxNew.CuryTaxableAmt = 0m;
                    artaxNew.CuryTaxAmt     = 0m;
                    artaxNew.TaxRate        = artax.TaxRate;
                }

                bool isTaxable = CalculateDiscountedTaxes(ie.Taxes.Cache, artax, CashDiscPercent);
                DiscountedPriceTotal += artax.CuryDiscountedPrice;

                decimal?CuryTaxableAmt = artax.CuryTaxableAmt - artax.CuryDiscountedTaxableAmt;
                decimal?CuryTaxAmt     = artax.CuryTaxAmt - artax.CuryDiscountedPrice;

                artaxNew.CuryTaxableAmt += CuryTaxableAmt;
                artaxNew.CuryTaxAmt     += CuryTaxAmt;

                TaxBaseAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(ie.Transactions.Cache, null, TaxCalc.ManualCalc);
                ie.Taxes.Update(artaxNew);

                if (isTaxable)
                {
                    DiscountedTaxableTotal += artax.CuryDiscountedTaxableAmt;
                    if (artaxMax == null || artaxNew.CuryTaxableAmt > artaxMax.CuryTaxableAmt)
                    {
                        artaxMax = artaxNew;
                    }
                }

                if (tax.TaxCalcLevel == CSTaxCalcLevel.Inclusive)
                {
                    InclusiveTotal += CuryTaxAmt;
                }
                else
                {
                    TaxTotal += CuryTaxAmt;
                }
            }

            //adjust taxes according to parent ARInvoice
            decimal?DiscountedInvTotal = doc.InvCuryOrigDocAmt - doc.InvCuryOrigDiscAmt;
            decimal?DiscountedDocTotal = DiscountedTaxableTotal + DiscountedPriceTotal;

            if (doc.InvCuryOrigDiscAmt == doc.CuryAdjdPPDAmt &&
                artaxMax != null &&
                doc.InvCuryVatTaxableTotal + doc.InvCuryTaxTotal == doc.InvCuryOrigDocAmt &&
                DiscountedDocTotal != DiscountedInvTotal)
            {
                artaxMax.CuryTaxableAmt += DiscountedDocTotal - DiscountedInvTotal;
                TaxBaseAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(ie.Transactions.Cache, null, TaxCalc.ManualCalc);
                ie.Taxes.Update(artaxMax);
            }

            //add document details
            ARTran tranNew = ie.Transactions.Insert();

            tranNew.BranchID = doc.AdjdBranchID;
            using (new PXLocaleScope(customer.LocaleName))
                tranNew.TranDesc = string.Format("{0} {1}, {2} {3}", PXMessages.LocalizeNoPrefix(DocTypes[doc.AdjdDocType]), doc.AdjdRefNbr, PXMessages.LocalizeNoPrefix(Messages.Payment), doc.AdjgRefNbr);
            tranNew.CuryExtPrice         = doc.CuryAdjdPPDAmt - TaxTotal;
            tranNew.CuryTaxableAmt       = tranNew.CuryExtPrice - InclusiveTotal;
            tranNew.CuryTaxAmt           = TaxTotal + InclusiveTotal;
            tranNew.AccountID            = customer.DiscTakenAcctID;
            tranNew.SubID                = customer.DiscTakenSubID;
            tranNew.TaxCategoryID        = null;
            tranNew.IsFree               = true;
            tranNew.ManualDisc           = true;
            tranNew.CuryDiscAmt          = 0m;
            tranNew.DiscPct              = 0m;
            tranNew.GroupDiscountRate    = 1m;
            tranNew.DocumentDiscountRate = 1m;

            if (taxes.Count == 1)
            {
                ARTaxTran artax  = taxes[0];
                ARTran    artran = PXSelectJoin <ARTran,
                                                 InnerJoin <ARTax, On <ARTax.tranType, Equal <ARTran.tranType>,
                                                                       And <ARTax.refNbr, Equal <ARTran.refNbr>,
                                                                            And <ARTax.lineNbr, Equal <ARTran.lineNbr> > > > >,
                                                 Where <ARTax.tranType, Equal <Required <ARTax.tranType> >,
                                                        And <ARTax.refNbr, Equal <Required <ARTax.refNbr> >,
                                                             And <ARTax.taxID, Equal <Required <ARTax.taxID> > > > >,
                                                 OrderBy <Asc <ARTran.lineNbr> > > .SelectSingleBound(ie, null, artax.TranType, artax.RefNbr, artax.TaxID);

                if (artran != null)
                {
                    tranNew.TaxCategoryID = artran.TaxCategoryID;
                }
            }

            ie.Transactions.Update(tranNew);

            //add applications
            ARAdjust adj = new ARAdjust();

            adj.AdjdDocType = doc.AdjdDocType;
            adj.AdjdRefNbr  = doc.AdjdRefNbr;
            adj             = ie.Adjustments_1.Insert(adj);

            adj.CuryAdjgAmt = doc.InvCuryDocBal;
            ie.Adjustments_1.Update(adj);
        }
Esempio n. 14
0
        public virtual ARInvoice ReleaseRetainageProc(ARInvoice doc, RetainageOptions retainageOpts, bool isAutoRelease = false)
        {
            Base.Clear(PXClearOption.PreserveTimeStamp);

            if (retainageOpts.CuryRetainageAmt <= 0 || retainageOpts.CuryRetainageAmt > doc.CuryRetainageUnreleasedAmt)
            {
                throw new PXException(AP.Messages.IncorrectRetainageAmount);
            }

            // Magic. We need to prevent rewriting of CurrencyInfo.IsReadOnly
            // by true in CurrencyInfoView
            //
            Base.CurrentDocument.Cache.AllowUpdate = true;

            PXResult <ARInvoice, CurrencyInfo, Terms, Customer> resultDoc =
                ARInvoice_CurrencyInfo_Terms_Customer
                .SelectSingleBound(Base, null, doc.DocType, doc.RefNbr, doc.CustomerID)
                .Cast <PXResult <ARInvoice, CurrencyInfo, Terms, Customer> >()
                .First();

            CurrencyInfo info        = resultDoc;
            ARInvoice    origInvoice = resultDoc;
            Customer     customer    = resultDoc;

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

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

            ARInvoice invoice = PXCache <ARInvoice> .CreateCopy(origInvoice);

            invoice.CuryInfoID = new_info.CuryInfoID;
            invoice.DocType    = ARDocType.Invoice;
            invoice.RefNbr     = null;
            invoice.LineCntr   = null;
            invoice.InvoiceNbr = origInvoice.InvoiceNbr;

            // Must be set for _RowSelected event handler
            //
            invoice.OpenDoc  = true;
            invoice.Released = false;

            Base.Document.Cache.SetDefaultExt <ARInvoice.isMigratedRecord>(invoice);
            Base.Document.Cache.SetDefaultExt <ARInvoice.hold>(invoice);
            invoice.BatchNbr   = null;
            invoice.ScheduleID = null;
            invoice.Scheduled  = false;
            invoice.NoteID     = null;

            invoice.DueDate         = null;
            invoice.DiscDate        = null;
            invoice.CuryOrigDiscAmt = 0m;
            invoice.OrigDocType     = origInvoice.DocType;
            invoice.OrigRefNbr      = origInvoice.RefNbr;
            invoice.OrigDocDate     = origInvoice.DocDate;

            invoice.CuryLineTotal       = 0m;
            invoice.IsTaxPosted         = false;
            invoice.IsTaxValid          = false;
            invoice.CuryVatTaxableTotal = 0m;
            invoice.CuryVatExemptTotal  = 0m;

            invoice.CuryDocBal     = 0m;
            invoice.CuryOrigDocAmt = retainageOpts.CuryRetainageAmt;
            invoice.Hold           = !isAutoRelease && Base.ARSetup.Current.HoldEntry == true;

            invoice.DocDate     = retainageOpts.DocDate;
            invoice.FinPeriodID = retainageOpts.FinPeriodID;

            Base.ClearRetainageSummary(invoice);
            invoice.RetainageApply      = false;
            invoice.IsRetainageDocument = true;

            invoice = Base.Document.Insert(invoice);

            if (new_info != null)
            {
                CurrencyInfo b_info = (CurrencyInfo)PXSelect <CurrencyInfo,
                                                              Where <CurrencyInfo.curyInfoID, Equal <Current <ARInvoice.curyInfoID> > > > .Select(Base);

                b_info.CuryID         = new_info.CuryID;
                b_info.CuryEffDate    = new_info.CuryEffDate;
                b_info.CuryRateTypeID = new_info.CuryRateTypeID;
                b_info.CuryRate       = new_info.CuryRate;
                b_info.RecipRate      = new_info.RecipRate;
                b_info.CuryMultDiv    = new_info.CuryMultDiv;
                Base.currencyinfo.Update(b_info);
            }

            decimal retainagePercent = (decimal)(retainageOpts.CuryRetainageAmt / doc.CuryRetainageTotal);

            PXResultset <ARTran> details = PXSelectGroupBy <ARTran,
                                                            Where <ARTran.tranType, Equal <Required <ARTran.tranType> >,
                                                                   And <ARTran.refNbr, Equal <Required <ARTran.refNbr> >,
                                                                        And <ARTran.curyRetainageAmt, NotEqual <decimal0> > > >,
                                                            Aggregate <
                                                                GroupBy <ARTran.taxCategoryID,
                                                                         Sum <ARTran.curyRetainageAmt> > > >
                                           .Select(Base, doc.DocType, doc.RefNbr);

            ARTran  tranNew       = null;
            decimal prevCuryTotal = 0m;

            TaxCalc oldTaxCalc = TaxBaseAttribute.GetTaxCalc <ARTran.taxCategoryID>(Base.Transactions.Cache, null);

            TaxBaseAttribute.SetTaxCalc <ARTran.taxCategoryID>(Base.Transactions.Cache, null, TaxCalc.ManualCalc);

            foreach (ARTran detail in details)
            {
                // Create ARTran record for chosen retainage amount,
                // clear all required fields to prevent tax calculation,
                // discount calculation and retainage calculation.
                // CuryUnitPrice = 0m and CuryExtPrice = 0m here to prevent their
                // FieldDefaulting events, because in our case default value
                // should be equal to zero.
                //
                tranNew = Base.Transactions.Insert(new ARTran
                {
                    CuryUnitPrice = 0m,
                    CuryExtPrice  = 0m
                });

                tranNew.BranchID      = origInvoice.BranchID;
                tranNew.TaxCategoryID = detail.TaxCategoryID;
                tranNew.AccountID     = origInvoice.RetainageAcctID;
                tranNew.SubID         = origInvoice.RetainageSubID;
                tranNew.ProjectID     = ProjectDefaultAttribute.NonProject();

                tranNew.Qty                  = 0m;
                tranNew.ManualDisc           = true;
                tranNew.DiscPct              = 0m;
                tranNew.CuryDiscAmt          = 0m;
                tranNew.RetainagePct         = 0m;
                tranNew.CuryRetainageAmt     = 0m;
                tranNew.CuryTaxableAmt       = 0m;
                tranNew.CuryTaxAmt           = 0;
                tranNew.GroupDiscountRate    = 1m;
                tranNew.DocumentDiscountRate = 1m;

                using (new PXLocaleScope(customer.LocaleName))
                {
                    tranNew.TranDesc = PXMessages.LocalizeFormatNoPrefix(
                        AP.Messages.RetainageForTransactionDescription,
                        ARDocTypeDict[origInvoice.DocType],
                        origInvoice.RefNbr);
                }

                prevCuryTotal        = (retainageOpts.CuryRetainageAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                tranNew.CuryExtPrice = PXCurrencyAttribute.RoundCury(Base.Transactions.Cache, tranNew, (detail.CuryRetainageAmt ?? 0m) * retainagePercent);
                tranNew = Base.Transactions.Update(tranNew);
            }

            ClearCurrentDocumentDiscountDetails();

            // We should copy all taxes from the original document
            // because it is possible to add or delete them.
            //
            foreach (ARTaxTran artaxtran in PXSelect <ARTaxTran,
                                                      Where <ARTaxTran.module, Equal <BatchModule.moduleAR>,
                                                             And <ARTaxTran.tranType, Equal <Required <ARTaxTran.tranType> >,
                                                                  And <ARTaxTran.refNbr, Equal <Required <ARTaxTran.refNbr> > > > > >
                     .Select(Base, origInvoice.DocType, origInvoice.RefNbr)
                     .RowCast <ARTaxTran>()
                     .Where(row => row.CuryRetainedTaxAmt != 0m))
            {
                ARTaxTran new_artaxtran = Base.Taxes.Insert(new ARTaxTran
                {
                    TaxID = artaxtran.TaxID
                });

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

                    new_artaxtran.TaxRate = artaxtran.TaxRate;
                    new_artaxtran         = Base.Taxes.Update(new_artaxtran);
                }
            }

            TaxBaseAttribute.SetTaxCalc <ARTran.taxCategoryID>(Base.Transactions.Cache, null, oldTaxCalc);
            decimal diff = (retainageOpts.CuryRetainageAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);

            if (tranNew != null && diff != 0m)
            {
                HashSet <string> taxList = PXSelectJoin <ARTax,
                                                         InnerJoin <Tax, On <Tax.taxID, Equal <ARTax.taxID> > >,
                                                         Where <ARTax.tranType, Equal <Required <ARTax.tranType> >,
                                                                And <ARTax.refNbr, Equal <Required <ARTax.refNbr> >,
                                                                     And <ARTax.lineNbr, Equal <Required <ARTax.lineNbr> >,
                                                                          And <Tax.taxType, NotEqual <CSTaxType.use> > > > > >
                                           .Select(Base, tranNew.TranType, tranNew.RefNbr, tranNew.LineNbr)
                                           .RowCast <ARTax>()
                                           .Select(row => row.TaxID)
                                           .ToHashSet();

                // To guarantee correct document total amount
                // we should calculate last line total,
                // including its taxes.
                //
                TaxAttribute.CalcTaxable calcClass = new TaxAttribute.CalcTaxable(false, TaxAttribute.TaxCalcLevelEnforcing.None);
                decimal curyExtPrice = calcClass.CalcTaxableFromTotalAmount(
                    Base.Transactions.Cache,
                    tranNew,
                    taxList,
                    invoice.DocDate.Value,
                    prevCuryTotal);

                tranNew.CuryExtPrice = curyExtPrice;
                tranNew = Base.Transactions.Update(tranNew);
            }

            return(invoice);
        }
Esempio n. 15
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);
        }