private static void ApplyPayment(ARPaymentEntry graph, ARAutoApplyParameters filter, ARPayment payment, List <ARInvoice> arInvoiceList, List <ARRegister> toRelease)
        {
            if (arInvoiceList.Any() == false)
            {
                return;
            }

            int invoiceIndex = 0;
            var paymentsViewIntoInvoiceList = new List <ARInvoice>(arInvoiceList);

            graph.Clear();
            graph.Document.Current = payment;

            bool adjustmentAdded = false;

            while (graph.Document.Current.CuryUnappliedBal > 0 && invoiceIndex < paymentsViewIntoInvoiceList.Count)
            {
                if (graph.Document.Current.CuryApplAmt == null)
                {
                    object curyapplamt = graph.Document.Cache.GetValueExt <ARPayment.curyApplAmt>(graph.Document.Current);
                    if (curyapplamt is PXFieldState)
                    {
                        curyapplamt = ((PXFieldState)curyapplamt).Value;
                    }
                    graph.Document.Current.CuryApplAmt = (decimal?)curyapplamt;
                }
                graph.Document.Current.AdjDate        = filter.ApplicationDate;
                graph.Document.Current.AdjFinPeriodID = filter.FinPeriodID;
                graph.Document.Cache.Update(graph.Document.Current);

                ARInvoice invoice = paymentsViewIntoInvoiceList[invoiceIndex];

                ARAdjust adj = new ARAdjust();
                adj.AdjdDocType = invoice.DocType;
                adj.AdjdRefNbr  = invoice.RefNbr;

                graph.AutoPaymentApp = true;
                adj = graph.Adjustments.Insert(adj);
                if (adj == null)
                {
                    invoiceIndex++;
                    continue;
                }
                adjustmentAdded = true;
                if (adj.CuryDocBal <= 0m)
                {
                    arInvoiceList.Remove(invoice);
                }

                invoiceIndex++;
            }
            if (adjustmentAdded)
            {
                graph.Save.Press();
                if (filter.ReleaseBatchWhenFinished == true)
                {
                    toRelease.Add(graph.Document.Current);
                }
            }
        }
        protected override decimal?GetDocumentBalance(PXCache cache, object Row)
        {
            ARInvoice row = Document.Cache.GetMain((Document)Row) as ARInvoice;

            decimal?   DocumentBal = 0m;
            ARBalances accumbal    = cache.Current as ARBalances;

            if (accumbal != null && cache.GetStatus(accumbal) == PXEntryStatus.Inserted)
            {
                //get balance only from PXAccumulator
                DocumentBal = accumbal.UnreleasedBal;
            }

            PXCache sender = cache.Graph.Caches[typeof(ARInvoice)];

            if (DocumentBal > 0m && row.ApprovedCredit == true)
            {
                if (row.ApprovedCreditAmt >= row.OrigDocAmt)
                {
                    DocumentBal = 0m;
                }
            }

            return(DocumentBal);
        }
        protected static void Accumulate(ARStatement aDest, ARRegister aSrc1, ARStatementCycle aSrc2, bool isNewDoc, bool aAgeCredits)
        {
            ARInvoice inv = aSrc1 as ARInvoice;

            Copy(aDest, aSrc2);
            if (isNewDoc)
            {
                aDest.EndBalance     = (aDest.EndBalance ?? Decimal.Zero) + ((aSrc1.Payable ?? false) ? aSrc1.OrigDocAmt : (-aSrc1.OrigDocAmt));
                aDest.CuryEndBalance = (aDest.CuryEndBalance ?? Decimal.Zero) + ((aSrc1.Payable ?? false) ? aSrc1.CuryOrigDocAmt : (-aSrc1.CuryOrigDocAmt));
            }
            //ARDocType.SmallCreditWO - is an invoice, but it must be processed as payment
            int days = 0;

            if (inv != null && inv.DocType != ARDocType.SmallCreditWO)
            {
                TimeSpan diff = (aDest.StatementDate.Value.Subtract(inv.DueDate.Value));
                days = diff.Days;
            }
            else
            {
                TimeSpan diff = (aDest.StatementDate.Value.Subtract(aSrc1.DocDate.Value));
                days = diff.Days;
            }
            if ((inv != null && inv.DocType != ARDocType.SmallCreditWO) || aAgeCredits)
            {
                Decimal docBal     = ((bool)aSrc1.Paying) ? -aSrc1.DocBal.Value : aSrc1.DocBal.Value;
                Decimal curyDocBal = ((bool)aSrc1.Paying) ? -aSrc1.CuryDocBal.Value : aSrc1.CuryDocBal.Value;
                if (days <= 0)
                {
                    aDest.AgeBalance00     = (aDest.AgeBalance00 ?? Decimal.Zero) + docBal;
                    aDest.CuryAgeBalance00 = (aDest.CuryAgeBalance00 ?? Decimal.Zero) + curyDocBal;
                }
                else if (!aSrc2.AgeDays00.HasValue || days <= aSrc2.AgeDays00)
                {
                    aDest.AgeBalance01     = (aDest.AgeBalance01 ?? Decimal.Zero) + docBal;
                    aDest.CuryAgeBalance01 = (aDest.CuryAgeBalance01 ?? Decimal.Zero) + curyDocBal;
                }
                else if (!aSrc2.AgeDays01.HasValue || days <= aSrc2.AgeDays01)
                {
                    aDest.AgeBalance02     = (aDest.AgeBalance02 ?? Decimal.Zero) + docBal;
                    aDest.CuryAgeBalance02 = (aDest.CuryAgeBalance02 ?? Decimal.Zero) + curyDocBal;
                }
                else if (!aSrc2.AgeDays02.HasValue || days <= aSrc2.AgeDays02)
                {
                    aDest.AgeBalance03     = (aDest.AgeBalance03 ?? Decimal.Zero) + docBal;
                    aDest.CuryAgeBalance03 = (aDest.CuryAgeBalance03 ?? Decimal.Zero) + curyDocBal;
                }
                else
                {
                    aDest.AgeBalance04     = (aDest.AgeBalance04 ?? Decimal.Zero) + docBal;
                    aDest.CuryAgeBalance04 = (aDest.CuryAgeBalance04 ?? Decimal.Zero) + curyDocBal;
                }
            }
            else
            {
                //Payments, when credits are not aged
                aDest.AgeBalance04     = aDest.AgeBalance04 - aSrc1.DocBal;             //After completion we must apply resedual payments to previous buckets
                aDest.CuryAgeBalance04 = aDest.CuryAgeBalance04 - aSrc1.CuryDocBal;
            }
        }
Example #4
0
        private static void VoidProcess(ARDunningLetter doc)
        {
            ARDunningLetterMaint graph = PXGraph.CreateInstance <ARDunningLetterMaint>();

            graph.Document.Current    = doc;
            graph.Details.AllowUpdate = true;
            foreach (ARDunningLetterDetail detail in graph.Details.Select())
            {
                ARDunningLetterProcess.ARInvoiceWithDL invoice = PXSelect <ARDunningLetterProcess.ARInvoiceWithDL, Where <ARDunningLetterProcess.ARInvoiceWithDL.refNbr, Equal <Required <ARInvoice.refNbr> >, And <ARDunningLetterProcess.ARInvoiceWithDL.docType, Equal <Required <ARInvoice.docType> > > > > .Select(graph, detail.RefNbr, detail.DocType);

                if (invoice != null && invoice.DunningLetterLevel > detail.DunningLetterLevel)
                {
                    throw new PXException(Messages.DunningLetterHigherLevelExists);
                }
            }
            ARInvoice feeInvoice = PXSelect <ARInvoice, Where <ARInvoice.refNbr, Equal <Required <ARInvoice.refNbr> >, And <ARInvoice.docType, Equal <Required <ARInvoice.docType> > > > > .Select(graph, doc.FeeRefNbr, doc.FeeDocType);

            if (feeInvoice != null && feeInvoice.Voided == false)
            {
                ARInvoiceEntry invoiceGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
                invoiceGraph.Document.Current = feeInvoice;
                if (feeInvoice.Released == false)
                {
                    invoiceGraph.Delete.Press();
                }
                else if (feeInvoice.Released == true && feeInvoice.OpenDoc == true)
                {
                    if (feeInvoice.CuryOrigDocAmt != feeInvoice.CuryDocBal)
                    {
                        throw new PXException(Messages.DunningLetterHavePaidFee);
                    }
                    invoiceGraph.reverseInvoice.Press();                     // replace by reverse & attach in 2017R2
                    invoiceGraph.Document.Current.Hold = false;
                    invoiceGraph.Document.Update(invoiceGraph.Document.Current);
                    invoiceGraph.release.Press();
                    ARPaymentEntry paymentGraph = PXGraph.CreateInstance <ARPaymentEntry>();
                    paymentGraph.Document.Current = PXSelect <ARPayment, Where <ARPayment.refNbr, Equal <Required <ARPayment.refNbr> >, And <ARPayment.docType, Equal <Required <ARPayment.docType> > > > > .Select(paymentGraph, invoiceGraph.Document.Current.RefNbr, invoiceGraph.Document.Current.DocType);

                    ARAdjust adj = new ARAdjust();
                    paymentGraph.Adjustments.Insert(adj);
                    adj.AdjdRefNbr  = feeInvoice.RefNbr;
                    adj.AdjdDocType = feeInvoice.DocType;
                    paymentGraph.Adjustments.Update(adj);
                    paymentGraph.release.Press();
                }
                else
                {
                    throw new PXException(Messages.DunningLetterHavePaidFee);
                }
            }
            foreach (ARDunningLetterDetail detail in graph.Details.Select())
            {
                detail.Voided = true;
                graph.Details.Update(detail);
            }

            doc.Voided = true;
            graph.Document.Update(doc);
            graph.Save.Press();
        }
Example #5
0
        protected virtual void DRSchedule_RefNbr_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            DRSchedule row = e.Row as DRSchedule;

            if (row != null)
            {
                if (row.Module == BatchModule.AR)
                {
                    ARInvoice invoice = PXSelect <ARInvoice, Where <ARInvoice.docType, Equal <Current <DRSchedule.docType> >, And <ARInvoice.refNbr, Equal <Current <DRSchedule.refNbr> > > > > .Select(this);

                    if (invoice != null)
                    {
                        object oldRow = sender.CreateCopy(row);
                        row.BAccountID = invoice.CustomerID;
                        sender.RaiseFieldUpdated <DRSchedule.bAccountID>(row, oldRow);
                    }
                }
                else if (row.Module == BatchModule.AP)
                {
                    APInvoice bill = PXSelect <APInvoice, Where <APInvoice.docType, Equal <Current <DRSchedule.docType> >, And <APInvoice.refNbr, Equal <Current <DRSchedule.refNbr> > > > > .Select(this);

                    if (bill != null)
                    {
                        object oldRow = sender.CreateCopy(row);
                        row.BAccountID = bill.VendorID;
                        sender.RaiseFieldUpdated <DRSchedule.bAccountID>(row, oldRow);
                    }
                }
            }
        }
Example #6
0
        public virtual void CreatePayment(ARInvoice ardoc)
        {
            Base.CreatePayment(ardoc, null, null, null, true);
            RUTROT rowRR = PXSelect <RUTROT, Where <RUTROT.docType, Equal <Required <ARInvoice.docType> >,
                                                    And <RUTROT.refNbr, Equal <Required <ARInvoice.refNbr> > > > > .Select(this.Base, ardoc.DocType, ardoc.RefNbr);

            if (PXAccess.FeatureInstalled <FeaturesSet.rutRotDeduction>() &&
                ardoc != null &&
                PXCache <ARInvoice> .GetExtension <ARInvoiceRUTROT>(ardoc)?.IsRUTROTDeductible == true &&
                Base.Document.Current.DocType == ARDocType.Payment)
            {
                bool isInvoiceBalanced = rowRR.BalancingCreditMemoRefNbr != null && rowRR.BalancingDebitMemoRefNbr != null;

                if (rowRR.IsClaimed != true)
                {
                    decimal curyDistributedAmt = 0m;

                    if (isInvoiceBalanced == false)
                    {
                        PXCache rUTROTCache = Base.Caches[typeof(RUTROT)];
                        CM.PXCurrencyAttribute.CuryConvCury <ARPayment.curyInfoID>(Base.Document.Cache, Base.Document.Current, rowRR.DistributedAmt ?? 0m, out curyDistributedAmt);
                        rUTROTCache.SetValue <RUTROT.curyDistributedAmt>(rowRR, curyDistributedAmt);
                    }

                    SetPaymentAmount(Math.Max((Base.Document.Current.CuryDocBal - curyDistributedAmt) ?? 0m, 0m));
                }
            }
        }
Example #7
0
        private void CalcBalances(object row, bool isCalcRGOL, bool DiscOnDiscDate)
        {
            ARAdjust adj = (ARAdjust)row;

            PXCache cache = Caches[typeof(ARAdjust)];

            ARInvoice invoice = (ARInvoice)ARInvoice_CustomerID_DocType_RefNbr.Select(adj.AdjdCustomerID, adj.AdjdDocType, adj.AdjdRefNbr);

            if (invoice == null)
            {
                return;
            }

            PaymentEntry.CalcBalances <ARInvoice, ARAdjust>(CurrencyInfo_CuryInfoID, adj.AdjgCuryInfoID, adj.AdjdCuryInfoID, invoice, adj);

            if (DiscOnDiscDate)
            {
                PaymentEntry.CalcDiscount <ARInvoice, ARAdjust>(adj.AdjgDocDate, invoice, adj);
            }

            PaymentEntry.AdjustBalance <ARAdjust>(CurrencyInfo_CuryInfoID, adj);
            if (isCalcRGOL)
            {
                PaymentEntry.CalcRGOL <ARInvoice, ARAdjust>(CurrencyInfo_CuryInfoID, invoice, adj);
                adj.RGOLAmt = (bool)adj.ReverseGainLoss ? -1m * adj.RGOLAmt : adj.RGOLAmt;
            }
        }
Example #8
0
        public virtual ARInvoiceState GetDocumentState(PXCache cache, ARInvoice doc, Func <PXCache, ARInvoice, ARInvoiceState> baseMethod)
        {
            ARInvoiceState state = baseMethod(cache, doc);

            state.IsCancellationDocument             = doc.IsCancellation == true;
            state.IsCorrectionDocument               = doc.IsCorrection == true;
            state.ShouldDisableHeader               |= state.IsCancellationDocument;
            state.IsTaxZoneIDEnabled                &= !state.IsCancellationDocument;
            state.IsAvalaraCustomerUsageTypeEnabled &= !state.IsCancellationDocument;
            state.IsAssignmentEnabled               &= !state.IsCancellationDocument;
            state.AllowDeleteDocument               |= state.IsCancellationDocument && !state.IsDocumentReleased;
            state.DocumentHoldEnabled               |= state.IsCancellationDocument && !state.IsDocumentReleased;
            state.DocumentDateEnabled               |= state.IsCancellationDocument && !state.IsDocumentReleased;
            state.DocumentDescrEnabled              |= state.IsCancellationDocument && !state.IsDocumentReleased;

            state.BalanceBaseCalc         |= state.IsCancellationDocument && !state.IsDocumentReleased;
            state.AllowDeleteTransactions &= !state.IsCancellationDocument && !state.IsCorrectionDocument;
            state.AllowUpdateTransactions &= !state.IsCancellationDocument;
            state.AllowInsertTransactions &= !state.IsCancellationDocument && !state.IsCorrectionDocument;
            state.AllowDeleteTaxes        &= !state.IsCancellationDocument;
            state.AllowUpdateTaxes        &= !state.IsCancellationDocument;
            state.AllowInsertTaxes        &= !state.IsCancellationDocument;
            state.AllowDeleteDiscounts    &= !state.IsCancellationDocument;
            state.AllowUpdateDiscounts    &= !state.IsCancellationDocument;
            state.AllowInsertDiscounts    &= !state.IsCancellationDocument;

            return(state);
        }
Example #9
0
        public ActionResult ARInvoice(string documentNo)
        {
            ARInvoice arInvoice = null;

            if (documentNo == Utility.NEWRECORD)
            {
                arInvoice = new ARInvoice();
                //arInvoice.DocumentDate = Convert.ToDateTime(DateTime.Now.Date.ToString("dd-MM-yyyy"));
                arInvoice.DocumentDate     = DateTime.UtcNow.ThaiTime();
                arInvoice.ARInvoiceDetails = new List <ARInvoiceDetail>();
            }
            else
            {
                if (documentNo != null && documentNo != "" && documentNo != "null")
                {
                    arInvoice = new NetStock.BusinessFactory.ARInvoiceBO().GetARInvoice(new ARInvoice {
                        DocumentNo = documentNo
                    });
                }
                else
                {
                    arInvoice = new ARInvoice();
                    arInvoice.DocumentDate     = DateTime.Today.Date;
                    arInvoice.ARInvoiceDetails = new List <ARInvoiceDetail>();
                }
            }

            arInvoice.DebtorList       = Utility.GetDebtorList();
            arInvoice.DiscountTypeList = Utility.GetDiscountList();
            arInvoice.CurrencyCodeList = Utility.GetCurrencyItemList();
            arInvoice.AccountCodeList  = Utility.GetAccountCodeItemList();


            return(View("ARInvoice", arInvoice));
        }
        public virtual FSCreatedDoc PressSave(int batchID, List <DocLineExt> docLines, BeforeSaveDelegate beforeSave)
        {
            if (Base.Document.Current == null)
            {
                throw new SharedClasses.TransactionScopeException();
            }

            if (beforeSave != null)
            {
                beforeSave(Base);
            }

            Base.SelectTimeStamp();
            Base.Save.Press();

            ARInvoice arInvoice = Base.Document.Current;

            var fsCreatedDocRow = new FSCreatedDoc()
            {
                BatchID        = batchID,
                PostTo         = ID.Batch_PostTo.SI,
                CreatedDocType = arInvoice.DocType,
                CreatedRefNbr  = arInvoice.RefNbr
            };

            return(fsCreatedDocRow);
        }
        public virtual ARInvoice InsertDocument(ARInvoiceEntry docgraph, ScheduleDet sdet, Customer customer, ARInvoice ardoc, CurrencyInfo info, InsertDocumentDelegate baseMethod)
        {
            ARInvoice new_ardoc = baseMethod(docgraph, sdet, customer, ardoc, info);

            if (PXCache <ARInvoice> .GetExtension <ARInvoiceRUTROT>(ardoc)?.IsRUTROTDeductible == true)
            {
                RUTROT rutrot = PXSelect <RUTROT,
                                          Where <RUTROT.docType, Equal <Required <ARInvoice.docType> >,
                                                 And <RUTROT.refNbr, Equal <Required <ARInvoice.refNbr> > > > > .Select(docgraph, ardoc.DocType, ardoc.RefNbr);

                RUTROT new_rutrot = PXCache <RUTROT> .CreateCopy(rutrot);

                new_rutrot.CuryDistributedAmt   = 0m;
                new_rutrot.CuryTotalAmt         = 0m;
                new_rutrot.CuryUndistributedAmt = 0m;
                new_rutrot.DistributedAmt       = 0m;
                new_rutrot.TotalAmt             = 0m;
                new_rutrot.UndistributedAmt     = 0m;
                new_rutrot.WorkPrice            = 0m;
                new_rutrot.MaterialCost         = 0m;
                new_rutrot.OtherCost            = 0m;
                new_rutrot.CuryWorkPrice        = 0m;
                new_rutrot.CuryMaterialCost     = 0m;
                new_rutrot.CuryOtherCost        = 0m;
                new_rutrot.RefNbr = null;
                new_rutrot.NoteID = null;
                docgraph.Rutrots.Insert(new_rutrot);
            }
            return(new_ardoc);
        }
Example #12
0
        protected virtual IEnumerable dummyCustomAction(PXAdapter adapter)
        {
            SOShipment      shipment        = Base.Document.Current;
            SOOrderShipment soOrderShipment = PXSelect <SOOrderShipment,
                                                        Where <SOOrderShipment.shipmentNbr, Equal <Required <SOOrderShipment.shipmentNbr> > > > .
                                              Select(Base, shipment.ShipmentNbr);

            ARInvoice arInvoice = PXSelect <ARInvoice, Where <ARInvoice.refNbr, Equal <Required <ARInvoice.refNbr> >,
                                                              And <ARInvoice.docType, Equal <Required <ARInvoice.docType> > > > > .
                                  Select(Base, soOrderShipment.InvoiceNbr, "INV");

            PXLongOperation.StartOperation(Base, delegate()
            {
                SOInvoiceEntry soInvoiceGraph   = PXGraph.CreateInstance <SOInvoiceEntry>();
                SOShipmentEntry soShipmentGraph = PXGraph.CreateInstance <SOShipmentEntry>();
                //Release Sales Invoice
                soInvoiceGraph.Clear();
                soInvoiceGraph.Document.Current = soInvoiceGraph.Document.Search <ARInvoice.docType, ARInvoice.refNbr>(arInvoice.DocType, arInvoice.RefNbr);
                soInvoiceGraph.release.Press();
                //Update IN on Shipment
                soShipmentGraph.Clear();
                soShipmentGraph.Document.Current = soShipmentGraph.Document.Search <SOShipment.shipmentNbr>(shipment.ShipmentNbr);
                soShipmentGraph.UpdateIN.Press();
            });
            return(adapter.Get());
        }
        public virtual void ReleaseInvoiceTransactionPostProcessed(JournalEntry je, ARInvoice ardoc, ARTran n,
                                                                   Action <JournalEntry, ARInvoice, ARTran> baseMethod)
        {
            baseMethod(je, ardoc, n);

            ProcessARTranInventory(n, ardoc, je);
        }
Example #14
0
        private void UpdateInvoiceTotal(ARInvoice invoice)
        {
            if (invoice == null)
            {
                return;
            }
            invoice.CuryLineTotal = 0;

            foreach (ARTran tran in Base.Transactions.Select())
            {
                InventoryItem product = KCInventoryItem.SelectSingle(tran.InventoryID);
                if (product != null)
                {
                    InventoryItemPCExt productPCExt = product.GetExtension <InventoryItemPCExt>();
                    if (productPCExt != null)
                    {
                        if (productPCExt.UsrKNCompositeType == null)
                        {
                            invoice.CuryLineTotal += tran.CuryTranAmt;
                        }
                    }
                }
            }

            // invoice.CuryLineTotal = order?.OrderTotal ?? 0 - order?.TaxTotal ?? 0;
            invoice.CuryLineTotal += invoice.PremiumFreightAmt;
            invoice.CuryDocBal     = invoice.CuryLineTotal + invoice.TaxTotal;
            invoice.CuryOrigDocAmt = invoice.CuryDocBal;
            invoice.CuryGoodsTotal = invoice.CuryLineTotal;
            invoice.GoodsTotal     = invoice.CuryLineTotal;
        }
Example #15
0
 /// <summary>
 /// Reinicia los parámetros de búsqueda.
 /// </summary>
 private void ResetFactura()
 {
     _FactParaBuscar = new ARInvoice
     {
         SellerParty = new Party()
     };
 }
        public static void ReleaseRetainage(ARInvoiceEntry graph, ARInvoiceExt invoice, ARRetainageFilter filter, bool isAutoRelease)
        {
            graph.Clear(PXClearOption.ClearAll);
            PXUIFieldAttribute.SetError(graph.Document.Cache, null, null, null);

            RetainageOptions retainageOptions = new RetainageOptions();

            retainageOptions.DocDate          = filter.DocDate;
            retainageOptions.FinPeriodID      = filter.FinPeriodID;
            retainageOptions.CuryRetainageAmt = invoice.CuryRetainageReleasedAmt;

            ARInvoiceEntryRetainage retainageExt = graph.GetExtension <ARInvoiceEntryRetainage>();

            ARInvoice retainageInvoice = retainageExt.ReleaseRetainageProc(invoice, retainageOptions, isAutoRelease);

            graph.Save.Press();

            if (isAutoRelease)
            {
                List <ARRegister> toRelease = new List <ARRegister>()
                {
                    retainageInvoice
                };
                using (new PXTimeStampScope(null))
                {
                    ARDocumentRelease.ReleaseDoc(toRelease, true);
                }
            }
        }
Example #17
0
        /// <summary>
        /// Busqueda: Actualiza los datos del modelo
        /// con los datos actuales de la vista.
        /// </summary>
        private void BindModelBusqueda()
        {
            _FactParaBuscar = new ARInvoice();

            // Chequear datos
            DateTime issueDate;

            if (!DateTime.TryParse(txFechaBusqueda.Text, out issueDate))
            {
                MessageBox.Show("Debe introducir una fecha correcta");
                txFechaBusqueda.Focus();
                return;
            }

            // Necesitamos indicar una fecha de factura, para que se pueda calcular el ejercicio y periodo
            // que son necesarios y obligatorios para realizar esta peticiones.
            _FactParaBuscar.IssueDate = Convert.ToDateTime(issueDate);

            if (!string.IsNullOrEmpty(txNifBusqueda.Text))
            {
                _FactParaBuscar.SellerParty = new Party() // El cliente
                {
                    TaxIdentificationNumber = txNifBusqueda.Text
                };
            }

            if (!string.IsNullOrEmpty(txFactBusqueda.Text))
            {
                _FactParaBuscar.InvoiceNumber = txFactBusqueda.Text;
            }

            _PetFactEmitEnviadas.ARInvoice = _FactParaBuscar;
        }
        public virtual IAddressBase GetFromAddress(ARInvoice invoice, ARTran tran, GetFromAddressLineDelegate del)
        {
            int?SOID = GetSOIDRelated(tran);

            if (SOID != null && tran.SiteID == null)
            {
                IAddressBase returnAddress = null;

                returnAddress = PXSelectJoin <FSAddress,
                                              InnerJoin <
                                                  FSBranchLocation,
                                                  On <FSBranchLocation.branchLocationAddressID, Equal <FSAddress.addressID> >,
                                                  InnerJoin <FSServiceOrder,
                                                             On <FSServiceOrder.branchLocationID, Equal <FSBranchLocation.branchLocationID> > > >,
                                              Where <
                                                  FSServiceOrder.sOID, Equal <Required <FSServiceOrder.sOID> > > >
                                .Select(Base, SOID)
                                .RowCast <FSAddress>()
                                .FirstOrDefault();

                return(returnAddress);
            }

            return(del(invoice, tran));
        }
Example #19
0
        // Crea una consulta de facturas emitidas
        private static ARInvoicesQuery CrearConsultaFacturasEmitidas()
        {
            // Titular que realizó el envío de las facturas a consultar
            Party titular = new Party()
            {
                TaxIdentificationNumber =
                    "B12959755",
                PartyName = "IRENE SOLUTIONS SL"
            };

            // Creamos una consulta de facturas emitidas
            ARInvoicesQuery consultaFacturasEmitidas = new ARInvoicesQuery
            {
                Titular = titular
            };

            // La consulta de facturas emitidas contine un objeto factura emitida
            // que utilizaremos para pasarle los datos de filtro.
            ARInvoice facturaConDatosFiltro = consultaFacturasEmitidas.ARInvoice;

            // Filtramos por fecha de emisión.
            facturaConDatosFiltro.IssueDate = new DateTime(2017, 1, 15);

            return(consultaFacturasEmitidas);
        }
        public IEnumerable Release(PXAdapter adapter)
        {
            if (RUTROTHelper.IsNeedBalancing(Base, Base.Document.Current, RUTROTBalanceOn.Release))
            {
                Base.Save.Press();

                ARInvoice doc = Base.Document.Current;
                PXLongOperation.StartOperation(Base, delegate()
                {
                    RUTROT rutrot = PXSelect <RUTROT, Where <RUTROT.refNbr, Equal <Required <ARInvoice.refNbr> >,
                                                             And <RUTROT.docType, Equal <Required <ARInvoice.docType> > > > > .Select(Base, doc.RefNbr, doc.DocType);

                    ARInvoiceEntry invoiceEntryGraph = PXGraph.CreateInstance <ARInvoiceEntry>();

                    RUTROTHelper.BalanceARInvoiceRUTROT(invoiceEntryGraph, doc, OnRelease: true, rutrot: rutrot);

                    RUTROTHelper.CreateAdjustment(Base, doc, rutrot);

                    Base.ReleaseProcess(new List <ARRegister> {
                        doc
                    });
                });

                return(new List <ARInvoice> {
                    Base.Document.Current
                });
            }

            return(Base.Release(adapter));
        }
Example #21
0
        // Crea un lote de factura emitidas a eliminar
        private static ARInvoicesDeleteBatch CrearLoteFacturasEnviadasEliminar()
        {
            // Titular del lote
            Party titular = new Party()
            {
                TaxIdentificationNumber =
                    "B12959755",
                PartyName = "IRENE SOLUTIONS SL"
            };


            ARInvoicesDeleteBatch loteFacturasEmitidasEliminar = new ARInvoicesDeleteBatch
            {
                Titular = titular
            };

            Party emisor = titular;

            // Creamos la primera factura enviada a eliminar
            ARInvoice primeraFacturaEliminar = new ARInvoice
            {
                IssueDate     = new DateTime(2017, 1, 15),
                InvoiceNumber = "00001",
                SellerParty   = emisor
            };

            // Añadimos la factura a eliminar al lote
            loteFacturasEmitidasEliminar.ARInvoices.Add(primeraFacturaEliminar);

            return(loteFacturasEmitidasEliminar);
        }
        public virtual void InvoiceCreated(ARInvoice invoice, SOOrder source, SOInvoiceEntry.InvoiceCreatedDelegate baseMethod)
        {
            baseMethod(invoice, source);

            SOOrderRUTROT orderRR = PXCache <SOOrder> .GetExtension <SOOrderRUTROT>(source);

            if (orderRR?.IsRUTROTDeductible == true && invoice != null)
            {
                ARInvoiceRUTROT invoiceRR = PXCache <ARInvoice> .GetExtension <ARInvoiceRUTROT>(invoice);

                Base.Document.SetValueExt <ARInvoiceRUTROT.isRUTROTDeductible>(invoice, true);
                Base.Document.Update(invoice);

                RUTROT rutrot = PXSelect <RUTROT,
                                          Where <RUTROT.docType, Equal <Required <SOOrder.orderType> >,
                                                 And <RUTROT.refNbr, Equal <Required <SOOrder.orderNbr> > > > > .Select(Base, source.OrderType, source.OrderNbr);

                rutrot = RUTROTHelper.CreateCopy(Base.Rutrots.Cache, rutrot, invoice.DocType, invoice.RefNbr);
                rutrot = Base.Rutrots.Update(rutrot);

                foreach (RUTROTDistribution rutrotDetail in PXSelect <RUTROTDistribution,
                                                                      Where <RUTROTDistribution.docType, Equal <Required <SOOrder.orderType> >,
                                                                             And <RUTROTDistribution.refNbr, Equal <Required <SOOrder.orderNbr> > > > > .Select(Base, source.OrderType, source.OrderNbr))
                {
                    RUTROTDistribution new_detail = (RUTROTDistribution)Base.RRDistribution.Cache.CreateCopy(rutrotDetail);
                    new_detail.RefNbr  = null;
                    new_detail.DocType = null;
                    Base.RRDistribution.Insert(new_detail);
                }
            }
        }
Example #23
0
        public static void CreateAdjustment(ARInvoiceEntry graph, ARInvoice invoice, RUTROT rutrot)
        {
            ARPayment creditMemo = PXSelect <ARPayment, Where <ARPayment.docType, Equal <Required <RUTROT.docType> >,
                                                               And <ARPayment.refNbr, Equal <Required <RUTROT.refNbr> > > > > .Select(graph, rutrot.BalancingCreditMemoDocType, rutrot.BalancingCreditMemoRefNbr);

            ARAdjust2 applicationToCreditMemo = new ARAdjust2
            {
                AdjdDocType        = invoice.DocType,
                AdjdRefNbr         = invoice.RefNbr,
                AdjgDocType        = creditMemo.DocType,
                AdjgRefNbr         = creditMemo.RefNbr,
                AdjNbr             = creditMemo.AdjCntr,
                CustomerID         = creditMemo.CustomerID,
                AdjdCustomerID     = invoice.CustomerID,
                AdjdBranchID       = invoice.BranchID,
                AdjgBranchID       = creditMemo.BranchID,
                AdjgCuryInfoID     = creditMemo.CuryInfoID,
                AdjdOrigCuryInfoID = invoice.CuryInfoID,
                AdjdCuryInfoID     = invoice.CuryInfoID,
                CuryAdjdAmt        = creditMemo.CuryDocBal
            };

            graph.Adjustments.Insert(applicationToCreditMemo);
            graph.Save.Press();
        }
Example #24
0
        /// <summary>
        /// Busqueda: Actualiza los datos del modelo
        /// con los datos actuales de la vista.
        /// </summary>
        private bool BindModelBusqueda()
        {
            _FactParaBuscar = new ARInvoice();

            // Chequear datos

            if (!DateTime.TryParse(txFechaBusqueda.Text, out DateTime issueDate))
            {
                string _msg = "Debe introducir una fecha correcta";
                MessageBox.Show(_msg, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txFechaBusqueda.Focus();
                return(false);
            }

            _FactParaBuscar.IssueDate = Convert.ToDateTime(issueDate);

            // En este caso, necesitamos indicar el SellerParty para evitar errores. Informaremos el titular.
            _FactParaBuscar.SellerParty = _Titular;

            if (!string.IsNullOrEmpty(txFactBusqueda.Text))
            {
                _FactParaBuscar.InvoiceNumber = txFactBusqueda.Text;
            }

            _PetCobroFactEmitEnviadas.ARInvoice = _FactParaBuscar;
            return(true);
        }
        /// <summary>
        /// Removes all application records associated with the specified
        /// document. This is required in order to prevent stuck application
        /// records after a document becomes scheduled.
        /// </summary>
        private void RemoveApplications(DocumentSelection document)
        {
            ARInvoiceEntry invoiceEntry = PXGraph.CreateInstance <ARInvoiceEntry>();

            ARInvoice documentAsInvoice = PXSelect <
                ARInvoice,
                Where <
                    ARInvoice.docType, Equal <Required <ARInvoice.docType> >,
                    And <ARInvoice.refNbr, Equal <Required <ARInvoice.refNbr> > > > >
                                          .Select(invoiceEntry, document.DocType, document.RefNbr);

            invoiceEntry.Document.Current = documentAsInvoice;

            invoiceEntry.Adjustments
            .Select()
            .RowCast <ARAdjust2>()
            .Where(application => application.Released != true)
            .ForEach(application => invoiceEntry.Adjustments.Delete(application));

            invoiceEntry.Adjustments_1
            .Select()
            .RowCast <ARAdjust>()
            .Where(application => application.Released != true)
            .ForEach(application => invoiceEntry.Adjustments_1.Delete(application));

            invoiceEntry.Save.Press();
        }
        protected virtual void ARInvoice_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
        {
            if (e.Row == null || SharedFunctions.isFSSetupSet(Base) == false)
            {
                return;
            }

            ARInvoice arInvoiceRow = (ARInvoice)e.Row;

            if (e.Operation == PXDBOperation.Update &&
                (Base.Accessinfo.ScreenID != SharedFunctions.SetScreenIDToDotFormat(ID.ScreenID.INVOICE_BY_APPOINTMENT) &&
                 Base.Accessinfo.ScreenID != SharedFunctions.SetScreenIDToDotFormat(ID.ScreenID.INVOICE_BY_SERVICE_ORDER)))
            {
                FSCreatedDoc fsCreatedDocRow = PXSelectJoin <FSCreatedDoc,
                                                             InnerJoin <FSPostBatch, On <FSCreatedDoc.batchID, Equal <FSPostBatch.batchID> > >,
                                                             Where <
                                                                 FSPostBatch.status, Equal <FSPostBatch.status.temporary>,
                                                                 And <FSPostBatch.postTo, Equal <FSPostBatch.postTo.AR>,
                                                                      And <FSCreatedDoc.createdRefNbr, Equal <Required <FSCreatedDoc.createdRefNbr> >,
                                                                           And <FSCreatedDoc.createdDocType, Equal <Required <FSCreatedDoc.createdDocType> > > > > > >
                                               .Select(Base, arInvoiceRow.RefNbr, arInvoiceRow.DocType);

                if (fsCreatedDocRow != null)
                {
                    throw new PXException(TX.Error.CANNOT_UPDATE_DOCUMENT_BECAUSE_BATCH_STATUS_IS_TEMPORARY);
                }
            }
        }
Example #27
0
        /// <summary>
        /// Busqueda: Actualiza los datos del modelo
        /// con los datos actuales de la vista.
        /// </summary>
        private void BindModelBusqueda()
        {
            _FactParaBuscar = new ARInvoice();

            // Chequear datos
            DateTime issueDate;

            if (!DateTime.TryParse(txFechaBusqueda.Text, out issueDate))
            {
                MessageBox.Show("Debe introducir una fecha correcta");
                txFechaBusqueda.Focus();
                return;
            }

            _FactParaBuscar.IssueDate = Convert.ToDateTime(issueDate);

            // En este caso, necesitamos indicar el SellerParty para evitar errores. Informaremos el titular.
            _FactParaBuscar.SellerParty = _Titular;

            if (!string.IsNullOrEmpty(txFactBusqueda.Text))
            {
                _FactParaBuscar.InvoiceNumber = txFactBusqueda.Text;
            }

            _PetCobroFactEmitEnviadas.ARInvoice = _FactParaBuscar;
        }
Example #28
0
        public ActionResult SearchARInvoice(string documentNo)
        {
            if (documentNo != "0")
            {
                ARInvoice arinvoice = null;

                arinvoice = new NetStock.BusinessFactory.ARInvoiceBO().GetARInvoice(new ARInvoice {
                    DocumentNo = documentNo
                });

                if (arinvoice == null)
                {
                    arinvoice = new ARInvoice();
                    arinvoice.DocumentDate     = DateTime.Today.Date;
                    arinvoice.ARInvoiceDetails = new List <ARInvoiceDetail>();
                }

                arinvoice.DebtorList       = Utility.GetDebtorList();
                arinvoice.CurrencyCodeList = Utility.GetCurrencyItemList();


                return(RedirectToAction("ARInvoice", new { InvoiceType = "", DocumentNo = documentNo }));
            }
            else
            {
                return(RedirectToAction("ARInvoice"));
            }
        }
Example #29
0
        /// <summary>
        /// Crea un lote de facturas emitidas para su envío al SII
        /// de la aeat.
        /// </summary>
        /// <returns></returns>
        private static ARInvoicesQuery CreaLoteDeEmitidasEnviadas()
        {
            // Informamos los datos necesarios para realizar la petición
            ARInvoicesQuery LoteFactEmitEnviadas = new ARInvoicesQuery();

            // Creamos el titular del envío
            Party titular = new Party()
            {
                TaxIdentificationNumber = "V57525560",
                PartyName = "IRENE SOLUTIONS SL"
            };

            LoteFactEmitEnviadas.Titular = titular;

            // Necesitamos indicar una fecha de factura, para que se pueda calcular el ejercicio y periodo
            // que son necesarios y obligatorios para realizar esta peticiones.
            ARInvoice facturaEnviadaPrimera = new ARInvoice();

            facturaEnviadaPrimera.IssueDate = new DateTime(2017, 1, 15); // Fecha factura

            //
            // Estos campos son opcionales, de manera que los informaremos si necesitamos buscar una factura
            // en concreto o aquellas cuya fecha de expedición coincida con la indicada en la petición
            //
            //facturaEnviadaPrimera.SellerParty = new Party() // El cliente
            //{
            //    TaxIdentificationNumber = "B12756474"
            //};
            //facturaEnviadaPrimera.InvoiceNumber = "E00027"; // El número de factura

            LoteFactEmitEnviadas.ARInvoice = facturaEnviadaPrimera;


            return(LoteFactEmitEnviadas);
        }
Example #30
0
        public virtual void EnsureCanCancel(ARInvoice doc, bool isCorrection)
        {
            if (doc.DocType != ARDocType.Invoice)
            {
                throw new PXException(Messages.CantCancelDocType, doc.DocType);
            }

            if (doc.InstallmentCntr > 0)
            {
                throw new PXException(Messages.CantCancelMultipleInstallmentsInvoice);
            }

            var arAdjustGroups = PXSelectGroupBy <ARAdjust,
                                                  Where <ARAdjust.adjdDocType, Equal <Current <ARInvoice.docType> >, And <ARAdjust.adjdRefNbr, Equal <Current <ARInvoice.refNbr> > > >,
                                                  Aggregate <
                                                      GroupBy <ARAdjust.adjgDocType, GroupBy <ARAdjust.adjgRefNbr, GroupBy <ARAdjust.released,
                                                                                                                            Sum <ARAdjust.curyAdjdAmt> > > > > >
                                 .SelectMultiBound(Base, new[] { doc })
                                 .RowCast <ARAdjust>().ToList();

            if (arAdjustGroups.Any(a => a.Released == false))
            {
                throw new PXException(Messages.CantCancelInvoiceWithUnreleasedApplications);
            }

            var nonReversedCreditMemo = arAdjustGroups.FirstOrDefault(a => a.CuryAdjdAmt != 0m && a.AdjgDocType == ARDocType.CreditMemo);

            if (nonReversedCreditMemo != null)
            {
                throw new PXException(Messages.CantCancelInvoiceWithCM, nonReversedCreditMemo.AdjdRefNbr, nonReversedCreditMemo.AdjgRefNbr);
            }

            var nonReversedApplication = arAdjustGroups.FirstOrDefault(a => a.CuryAdjdAmt != 0m);

            if (nonReversedApplication != null)
            {
                throw new PXException(Messages.CantCancelInvoiceWithPayment, nonReversedApplication.AdjdRefNbr, nonReversedApplication.AdjgRefNbr);
            }

            ARTran directSale = PXSelectReadonly <ARTran,
                                                  Where <ARTran.tranType, Equal <Current <ARInvoice.docType> >, And <ARTran.refNbr, Equal <Current <ARInvoice.refNbr> >,
                                                                                                                     And <ARTran.invtMult, NotEqual <short0>, And <ARTran.lineType, Equal <SOLineType.inventory> > > > > >
                                .SelectSingleBound(Base, new[] { doc });

            if (directSale != null)
            {
                throw new PXException(Messages.CantCancelInvoiceWithDirectStockSales, doc.RefNbr);
            }

            SOOrderShipment notRequireShipment = PXSelectReadonly <SOOrderShipment,
                                                                   Where <SOOrderShipment.invoiceType, Equal <Current <ARInvoice.docType> >, And <SOOrderShipment.invoiceNbr, Equal <Current <ARInvoice.refNbr> >,
                                                                                                                                                  And <SOOrderShipment.shipmentNbr, Equal <Constants.noShipmentNbr> > > > >
                                                 .SelectSingleBound(Base, new[] { doc });

            if (notRequireShipment != null)
            {
                throw new PXException(Messages.CantCancelInvoiceWithOrdersNotRequiringShipments, doc.RefNbr);
            }
        }
Example #31
0
 protected bool IsForProperty(ARInvoice invoice)
 {
     return invoice.ROTOrganizationNbr == null;
 }
Example #32
0
		public virtual void InvoiceOrder(DateTime invoiceDate, PXResult<SOOrderShipment, SOOrder, CurrencyInfo, SOAddress, SOContact, SOOrderType> order, PXResultset<SOShipLine, SOLine> details, Customer customer, DocumentList<ARInvoice, SOInvoice> list)
		{
			ARInvoice newdoc;
			SOOrder soOrder = order;
			SOOrderType ordertype = order;

            decimal ApprovedBalance = 0;
            decimal PrevDocBal = 0;

            PXRowUpdated ApprovedBalanceCollector = delegate(PXCache sender, PXRowUpdatedEventArgs e)
            {
                ARInvoice ARDoc = (ARInvoice)e.Row;
                if ((decimal)ARDoc.DocBal > (decimal)ARDoc.ApprovedCreditAmt)
                {
                    if ((bool)((SOOrder)order).ApprovedCredit && (decimal)ARDoc.DocBal > PrevDocBal)
                    {
                        ApprovedBalance += (decimal)ARDoc.DocBal - PrevDocBal;
                        ARDoc.ApprovedCreditAmt = ApprovedBalance;
                    }
                    ARDoc.ApprovedCredit = (ApprovedBalance == (decimal)ARDoc.DocBal ? true : false);
                    PrevDocBal = (decimal)ARDoc.DocBal;
                }
            };

            this.RowUpdated.AddHandler(typeof(ARInvoice), ApprovedBalanceCollector);

			if (list != null)
			{
				bool iscc = false;
				DateTime? orderInvoiceDate = (sosetup.Current.UseShipDateForInvoiceDate == true ? ((SOOrderShipment)order).ShipDate : soOrder.InvoiceDate);

				if (soOrder.BillSeparately == false)
				{
					iscc = PXSelectReadonly<CCProcTran, Where<CCProcTran.origDocType, Equal<Required<CCProcTran.origDocType>>, And<CCProcTran.origRefNbr, Equal<Required<CCProcTran.origRefNbr>>, And<CCProcTran.refNbr, IsNull>>>>.Select(this, soOrder.OrderType, soOrder.OrderNbr).Count > 0;
				}

				if (soOrder.PaymentCntr == 0 && soOrder.BillSeparately == false && iscc == false)
				{
					if(soOrder.PaymentMethodID == null && soOrder.CashAccountID == null)
						newdoc = list.Find<ARInvoice.docType, ARInvoice.docDate, ARInvoice.branchID, ARInvoice.customerID, ARInvoice.customerLocationID, SOInvoice.billAddressID, SOInvoice.billContactID, SOInvoice.extRefNbr, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrderType)order).ARDocType, orderInvoiceDate ?? invoiceDate, soOrder.BranchID, soOrder.CustomerID, soOrder.CustomerLocationID, soOrder.BillAddressID, soOrder.BillContactID, soOrder.ExtRefNbr, soOrder.CuryID, soOrder.TermsID, false) ?? (ARInvoice)new ARInvoice();
					else if (soOrder.CashAccountID == null)
						newdoc = list.Find<ARInvoice.docType, ARInvoice.docDate, ARInvoice.branchID, ARInvoice.customerID, ARInvoice.customerLocationID, SOInvoice.billAddressID, SOInvoice.billContactID, SOInvoice.pMInstanceID, SOInvoice.extRefNbr, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrderType)order).ARDocType, orderInvoiceDate ?? invoiceDate, soOrder.BranchID, soOrder.CustomerID, soOrder.CustomerLocationID, soOrder.BillAddressID, soOrder.BillContactID, soOrder.PMInstanceID, soOrder.ExtRefNbr, soOrder.CuryID, soOrder.TermsID, false) ?? (ARInvoice)new ARInvoice();					
					else
						newdoc = list.Find<ARInvoice.docType, ARInvoice.docDate, ARInvoice.branchID, ARInvoice.customerID, ARInvoice.customerLocationID, SOInvoice.billAddressID, SOInvoice.billContactID, SOInvoice.pMInstanceID, SOInvoice.cashAccountID, SOInvoice.extRefNbr, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrderType)order).ARDocType, orderInvoiceDate ?? invoiceDate, soOrder.BranchID, soOrder.CustomerID, soOrder.CustomerLocationID, soOrder.BillAddressID, soOrder.BillContactID, soOrder.PMInstanceID, soOrder.CashAccountID, soOrder.ExtRefNbr, soOrder.CuryID, soOrder.TermsID, false) ?? (ARInvoice)new ARInvoice();
				}
				else
				{
					newdoc = list.Find<ARInvoice.hidden, ARInvoice.hiddenOrderType, ARInvoice.hiddenOrderNbr>(true, soOrder.OrderType, soOrder.OrderNbr);
					if (newdoc == null)
					{
						newdoc = new ARInvoice();
						newdoc.HiddenOrderType = soOrder.OrderType;
						newdoc.HiddenOrderNbr = soOrder.OrderNbr;
						newdoc.Hidden = true;
					}
				}

				if (newdoc.RefNbr != null)
				{
					Document.Current = this.Document.Search<ARInvoice.refNbr>(newdoc.RefNbr, newdoc.DocType);
				}
				else
				{
					this.Clear();

					string docType = ((SOOrderType)order).ARDocType;
					if (((SOOrderShipment)order).Operation == ((SOOrderType)order).DefaultOperation)
					{
						newdoc.DocType = docType;
					}
					else
					{
						//for RMA switch document type if previous shipment was not invoiced previously in the current run, i.e. list.Find() returned null
 						newdoc.DocType = 
							docType == ARDocType.Invoice ? ARDocType.CreditMemo :
							docType == ARDocType.DebitMemo ? ARDocType.CreditMemo :
							docType == ARDocType.CreditMemo ? ARDocType.Invoice :
							docType == ARDocType.CashSale ? ARDocType.CashReturn :
							docType == ARDocType.CashReturn ? ARDocType.CashSale :
							null;
					}

					newdoc.DocDate = orderInvoiceDate ?? invoiceDate;

					if (string.IsNullOrEmpty(soOrder.FinPeriodID) == false)
					{
						newdoc.FinPeriodID = soOrder.FinPeriodID;
					}

					if (soOrder.InvoiceNbr != null)
					{
						newdoc.RefNbr = soOrder.InvoiceNbr;
						newdoc.RefNoteID = soOrder.NoteID;
					}

					if (((SOOrderType)order).UserInvoiceNumbering == true && string.IsNullOrEmpty(newdoc.RefNbr))
					{
						throw new PXException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName<SOOrder.invoiceNbr>(soorder.Cache));
					}

					AutoNumberAttribute.SetNumberingId<ARInvoice.refNbr>(Document.Cache, ((SOOrderType)order).ARDocType, ((SOOrderType)order).InvoiceNumberingID);

					newdoc = (ARInvoice)Document.Cache.CreateCopy(this.Document.Insert(newdoc));

					newdoc.BranchID = soOrder.BranchID;
					newdoc.CustomerID = ((SOOrder)order).CustomerID;
					newdoc.CustomerLocationID = ((SOOrder)order).CustomerLocationID;
					newdoc.TermsID = ((SOOrder)order).TermsID;
					newdoc.DiscDate = ((SOOrder)order).DiscDate;
					newdoc.DueDate = ((SOOrder)order).DueDate;
					newdoc.TaxZoneID = ((SOOrder)order).TaxZoneID;
					newdoc.AvalaraCustomerUsageType = ((SOOrder)order).AvalaraCustomerUsageType;
					newdoc.SalesPersonID = ((SOOrder)order).SalesPersonID;
					newdoc.DocDesc = ((SOOrder)order).OrderDesc;
					newdoc.InvoiceNbr = ((SOOrder)order).CustomerOrderNbr;
					newdoc.CuryID = ((SOOrder)order).CuryID;
					newdoc.ProjectID = ((SOOrder)order).ProjectID ?? PM.ProjectDefaultAttribute.NonProject(this);
				    newdoc.Hold = ordertype.InvoiceHoldEntry;

					if (((SOOrderType)order).MarkInvoicePrinted == true)
					{
						newdoc.Printed = true;
					}

					if (((SOOrderType)order).MarkInvoiceEmailed == true)
					{
						newdoc.Emailed = true;
					}

					if (soOrder.PMInstanceID != null || string.IsNullOrEmpty(soOrder.PaymentMethodID) == false)
					{
						newdoc.PMInstanceID = soOrder.PMInstanceID;
						newdoc.PaymentMethodID = soOrder.PaymentMethodID;
						newdoc.CashAccountID = soOrder.CashAccountID;
					}

					newdoc = this.Document.Update(newdoc);


					if (soOrder.PMInstanceID != null || string.IsNullOrEmpty(soOrder.PaymentMethodID) == false)
					{
						SODocument.Current.PMInstanceID = soOrder.PMInstanceID;
						SODocument.Current.PaymentMethodID = soOrder.PaymentMethodID;
						SODocument.Current.CashAccountID = soOrder.CashAccountID;						
						if(SODocument.Current.CashAccountID == null)
							SODocument.Cache.SetDefaultExt<SOInvoice.cashAccountID>(SODocument.Current);
						SODocument.Current.ExtRefNbr = soOrder.ExtRefNbr;
						//clear error in case invoice currency different from default cash account for customer
						SODocument.Cache.RaiseExceptionHandling<SOInvoice.cashAccountID>(SODocument.Current, null, null);
					}

					foreach (CurrencyInfo info in this.currencyinfo.Select())
					{
						if (((SOOrder)order).InvoiceDate != null)
						{
							PXCache<CurrencyInfo>.RestoreCopy(info, (CurrencyInfo)order);
							info.CuryInfoID = newdoc.CuryInfoID;
						}
					}
					AddressAttribute.CopyRecord<ARInvoice.billAddressID>(this.Document.Cache, newdoc, (SOAddress)order, true);
					ContactAttribute.CopyRecord<ARInvoice.billContactID>(this.Document.Cache, newdoc, (SOContact)order, true);					
				}
			}
			else
			{
				newdoc = (ARInvoice)Document.Cache.CreateCopy(Document.Current);

                if (Transactions.SelectSingle() == null)
                {
                    newdoc.CustomerID = ((SOOrder)order).CustomerID;
                    newdoc.ProjectID = ((SOOrder)order).ProjectID;
                    newdoc.CustomerLocationID = ((SOOrder)order).CustomerLocationID;
                    newdoc.SalesPersonID = ((SOOrder)order).SalesPersonID;
                    newdoc.TaxZoneID = ((SOOrder)order).TaxZoneID;
                    newdoc.AvalaraCustomerUsageType = ((SOOrder)order).AvalaraCustomerUsageType;
                    newdoc.DocDesc = ((SOOrder)order).OrderDesc;
                    newdoc.InvoiceNbr = ((SOOrder)order).CustomerOrderNbr;
                    newdoc.TermsID = ((SOOrder)order).TermsID;

					foreach (CurrencyInfo info in this.currencyinfo.Select())
					{
						PXCache<CurrencyInfo>.RestoreCopy(info, (CurrencyInfo)order);
						info.CuryInfoID = newdoc.CuryInfoID;
						newdoc.CuryID = info.CuryID;
					}
                }

                newdoc = this.Document.Update(newdoc);

				

				AddressAttribute.CopyRecord<ARInvoice.billAddressID>(this.Document.Cache, newdoc, (SOAddress)order, true);
				ContactAttribute.CopyRecord<ARInvoice.billContactID>(this.Document.Cache, newdoc, (SOContact)order, true);								
			}

			PXSelectBase<SOInvoiceDiscountDetail> selectInvoiceDiscounts = new PXSelect<SOInvoiceDiscountDetail,
			Where<SOInvoiceDiscountDetail.tranType, Equal<Current<SOInvoice.docType>>,
			And<SOInvoiceDiscountDetail.refNbr, Equal<Current<SOInvoice.refNbr>>,
			And<SOInvoiceDiscountDetail.orderType, Equal<Required<SOInvoiceDiscountDetail.orderType>>,
			And<SOInvoiceDiscountDetail.orderNbr, Equal<Required<SOInvoiceDiscountDetail.orderNbr>>>>>>>(this);

			foreach (SOInvoiceDiscountDetail detail in selectInvoiceDiscounts.Select(((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
			    DiscountDetails.Delete(detail);
			}

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

			if (details != null)
			{
				foreach (SOShipLine shipline in details)
				{
					this.Caches[typeof(SOShipLine)].Insert(shipline);
				}
			}

			DateTime? origInvoiceDate = null;
			foreach (PXResult<SOShipLine, SOLine, SOOrderTypeOperation, ARTran> res in PXSelectJoin<SOShipLine, InnerJoin<SOLine, On<SOLine.orderType, Equal<SOShipLine.origOrderType>, And<SOLine.orderNbr, Equal<SOShipLine.origOrderNbr>, And<SOLine.lineNbr, Equal<SOShipLine.origLineNbr>>>>, InnerJoin<SOOrderTypeOperation, On<SOOrderTypeOperation.orderType, Equal<SOLine.orderType>, And<SOOrderTypeOperation.operation, Equal<SOLine.operation>>>, LeftJoin<ARTran, On<ARTran.sOShipmentNbr, Equal<SOShipLine.shipmentNbr>, And<ARTran.sOShipmentType, Equal<SOShipLine.shipmentType>, And<ARTran.sOShipmentLineNbr, Equal<SOShipLine.lineNbr>, And<ARTran.sOOrderType, Equal<SOShipLine.origOrderType>, And<ARTran.sOOrderNbr, Equal<SOShipLine.origOrderNbr>, And<ARTran.sOOrderLineNbr, Equal<SOShipLine.origLineNbr>>>>>>>>>>, Where<SOShipLine.shipmentNbr, Equal<Required<SOShipLine.shipmentNbr>>, And<SOShipLine.origOrderType, Equal<Required<SOShipLine.origOrderType>>, And<SOShipLine.origOrderNbr, Equal<Required<SOShipLine.origOrderNbr>>, And<ARTran.refNbr, IsNull>>>>>.Select(this, ((SOOrderShipment)order).ShipmentNbr, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				SOLine orderline = (SOLine)res;
				SOShipLine shipline = (SOShipLine)res;

                if (Math.Abs((decimal)shipline.BaseShippedQty) < 0.0000005m)
                {
                    continue;
                }

				if (origInvoiceDate == null && orderline.InvoiceDate != null)
					origInvoiceDate = orderline.InvoiceDate;

				ARTran newtran = new ARTran();
				newtran.BranchID = orderline.BranchID;
				newtran.AccountID = orderline.SalesAcctID;
				newtran.SubID = orderline.SalesSubID;
				newtran.SOOrderType = shipline.OrigOrderType;
				newtran.SOOrderNbr = shipline.OrigOrderNbr;
				newtran.SOOrderLineNbr = shipline.OrigLineNbr;
				newtran.SOShipmentNbr = shipline.ShipmentNbr;
				newtran.SOShipmentType = shipline.ShipmentType;
				newtran.SOShipmentLineNbr = shipline.LineNbr;

				newtran.LineType = orderline.LineType;
				newtran.InventoryID = shipline.InventoryID;
                newtran.SiteID = orderline.SiteID;
				newtran.UOM = shipline.UOM;

				newtran.Qty = shipline.ShippedQty;
				newtran.BaseQty = shipline.BaseShippedQty;

                newtran.Commissionable = orderline.Commissionable;
                newtran.GroupDiscountRate = orderline.GroupDiscountRate;

				decimal shippedQtyInBaseUnits = INUnitAttribute.ConvertToBase(Transactions.Cache, newtran.InventoryID, shipline.UOM, shipline.ShippedQty.Value, INPrecision.QUANTITY);
				decimal shippedQtyInOrderUnits = INUnitAttribute.ConvertFromBase(Transactions.Cache, newtran.InventoryID, orderline.UOM, shippedQtyInBaseUnits, INPrecision.QUANTITY);

				if (shippedQtyInOrderUnits != orderline.OrderQty || shipline.UOM != orderline.UOM)
				{
					decimal curyUnitPriceInBaseUnits = INUnitAttribute.ConvertFromBase(Transactions.Cache, newtran.InventoryID, orderline.UOM, orderline.CuryUnitPrice.Value, INPrecision.UNITCOST);
					decimal curyUnitPriceInShippedUnits = INUnitAttribute.ConvertToBase(Transactions.Cache, newtran.InventoryID, shipline.UOM, curyUnitPriceInBaseUnits, INPrecision.UNITCOST);

                    if (arsetup.Current.LineDiscountTarget == LineDiscountTargetType.SalesPrice)
					{
						decimal? salesPriceAfterDiscount = curyUnitPriceInShippedUnits * (1m - orderline.DiscPct / 100m);
						newtran.CuryTranAmt = shipline.ShippedQty * PXCurrencyAttribute.Round(Transactions.Cache, newtran, salesPriceAfterDiscount ?? 0, CMPrecision.TRANCURY);
					}
					else
					{
						decimal? curyTranAmt = shipline.ShippedQty * curyUnitPriceInShippedUnits * (1m - orderline.DiscPct / 100m);
						newtran.CuryTranAmt = PXCurrencyAttribute.Round(Transactions.Cache, newtran, curyTranAmt ?? 0, CMPrecision.TRANCURY);
					}

					newtran.CuryUnitPrice = curyUnitPriceInShippedUnits;
					newtran.CuryDiscAmt = (shipline.ShippedQty * curyUnitPriceInShippedUnits) - newtran.CuryTranAmt;
				}
				else
				{
					newtran.CuryUnitPrice = orderline.CuryUnitPrice;
                    newtran.CuryTranAmt = orderline.CuryLineAmt;
					newtran.CuryDiscAmt = orderline.CuryDiscAmt;
				}

				if (newdoc.DocType == ((SOOrderType)order).ARDocType && ((SOOrderType)order).DefaultOperation != ((SOOrderTypeOperation)res).Operation)
				{
					//keep BaseQty positive for PXFormula
					newtran.Qty = -newtran.Qty;
					newtran.CuryDiscAmt = -newtran.CuryDiscAmt;
					newtran.CuryTranAmt = -newtran.CuryTranAmt;
				}

				newtran.ProjectID = orderline.ProjectID;
				newtran.TaskID = orderline.TaskID;
				newtran.TranDesc = orderline.TranDesc;
				newtran.SalesPersonID = orderline.SalesPersonID;
				newtran.TaxCategoryID = orderline.TaxCategoryID;
				newtran.DiscPct = orderline.DiscPct;
				
				newtran.ManualDisc = orderline.ManualDisc == true || orderline.IsFree == true;
				newtran.FreezeManualDisc = true;

                newtran.DiscountID = orderline.DiscountID;
                newtran.DiscountSequenceID = orderline.DiscountSequenceID;

				newtran.DetDiscIDC1 = orderline.DetDiscIDC1;
				newtran.DetDiscIDC2 = orderline.DetDiscIDC2;
				newtran.DetDiscSeqIDC1 = orderline.DetDiscSeqIDC1;
				newtran.DetDiscSeqIDC2 = orderline.DetDiscSeqIDC2;
				newtran.DetDiscApp = orderline.DetDiscApp;
				newtran.DocDiscIDC1 = orderline.DocDiscIDC1;
				newtran.DocDiscIDC2 = orderline.DocDiscIDC2;
				newtran.DocDiscSeqIDC1 = orderline.DocDiscSeqIDC1;
				newtran.DocDiscSeqIDC2 = orderline.DocDiscSeqIDC2;

				foreach (ARTran existing in Transactions.Cache.Inserted)
				{
					if (Transactions.Cache.ObjectsEqual<ARTran.sOShipmentNbr, ARTran.sOShipmentType, ARTran.sOShipmentLineNbr, ARTran.sOOrderType, ARTran.sOOrderNbr, ARTran.sOOrderLineNbr>(newtran, existing))
					{
						Transactions.Cache.RestoreCopy(newtran, existing);
						break;
					}
				}

				if (newtran.LineNbr == null)
				{
					newtran = this.Transactions.Insert(newtran);

					if (((SOOrderType)order).CopyLineNotesToInvoice == true)
					{
						if (((SOOrderType)order).CopyLineNotesToInvoiceOnlyNS == false || orderline.LineType == SOLineType.NonInventory)
						{
							PXNoteAttribute.SetNote(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetNote(Caches[typeof(SOLine)], orderline));
						}
					}

					if (((SOOrderType)order).CopyLineFilesToInvoice == true)
					{
						if (((SOOrderType)order).CopyLineFilesToInvoiceOnlyNS == false || orderline.LineType == SOLineType.NonInventory)
						{
							PXNoteAttribute.SetFileNotes(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetFileNotes(Caches[typeof(SOLine)], orderline));
						}
					}
				}
				else
				{
					newtran = this.Transactions.Update(newtran);
					TaxAttribute.Calculate<ARTran.taxCategoryID>(Transactions.Cache, new PXRowUpdatedEventArgs(newtran, null, true));
				}

			}
			
			PXSelectBase<ARTran> cmd = new PXSelect<ARTran, Where<ARTran.tranType, Equal<Current<ARInvoice.docType>>, And<ARTran.refNbr, Equal<Current<ARInvoice.refNbr>>, And<ARTran.sOOrderType, Equal<Current<SOMiscLine2.orderType>>, And<ARTran.sOOrderNbr, Equal<Current<SOMiscLine2.orderNbr>>, And<ARTran.sOOrderLineNbr, Equal<Current<SOMiscLine2.lineNbr>>>>>>>>(this);

			foreach (SOMiscLine2 orderline in PXSelect<SOMiscLine2, Where<SOMiscLine2.orderType, Equal<Required<SOMiscLine2.orderType>>, And<SOMiscLine2.orderNbr, Equal<Required<SOMiscLine2.orderNbr>>, And<Where<SOMiscLine2.curyUnbilledAmt, Greater<decimal0>, Or<SOMiscLine2.curyLineAmt, LessEqual<decimal0>>>>>>>.Select(this, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				if (cmd.View.SelectSingleBound(new object[] { Document.Current, orderline }) == null)
				{
					ARTran newtran = new ARTran();
					newtran.BranchID = orderline.BranchID;
					newtran.AccountID = orderline.SalesAcctID;
					newtran.SubID = orderline.SalesSubID;
					newtran.SOOrderType = orderline.OrderType;
					newtran.SOOrderNbr = orderline.OrderNbr;
					newtran.SOOrderLineNbr = orderline.LineNbr;
					newtran.SOShipmentNbr = ((SOOrderShipment)order).ShipmentNbr;
					newtran.SOShipmentType = ((SOOrderShipment)order).ShipmentType; 
					newtran.SOShipmentLineNbr = null;

					newtran.LineType = SOLineType.MiscCharge;
					newtran.InventoryID = orderline.InventoryID;
					newtran.TaskID = orderline.TaskID;
					newtran.SalesPersonID = orderline.SalesPersonID;
                    newtran.Commissionable = orderline.Commissionable;
					newtran.UOM = orderline.UOM;
					newtran.Qty = orderline.UnbilledQty;
					newtran.BaseQty = orderline.BaseUnbilledQty;
					newtran.CuryUnitPrice = orderline.CuryUnitPrice;
                    newtran.CuryDiscAmt = orderline.CuryDiscAmt;
					newtran.CuryTranAmt = orderline.CuryUnbilledAmt;
					newtran.TranDesc = orderline.TranDesc;
					newtran.TaxCategoryID = orderline.TaxCategoryID;
                    newtran.DiscPct = orderline.DiscPct;
					newtran.ManualDisc = orderline.ManualDisc == true || orderline.IsFree == true;
					newtran.FreezeManualDisc = true;

                    newtran.DiscountID = orderline.DiscountID;
                    newtran.DiscountSequenceID = orderline.DiscountSequenceID;

					newtran.DetDiscIDC1 = orderline.DetDiscIDC1;
					newtran.DetDiscIDC2 = orderline.DetDiscIDC2;
					newtran.DetDiscSeqIDC1 = orderline.DetDiscSeqIDC1;
					newtran.DetDiscSeqIDC2 = orderline.DetDiscSeqIDC2;
					newtran.DetDiscApp = orderline.DetDiscApp;
					newtran.DocDiscIDC1 = orderline.DocDiscIDC1;
					newtran.DocDiscIDC2 = orderline.DocDiscIDC2;
					newtran.DocDiscSeqIDC1 = orderline.DocDiscSeqIDC1;
					newtran.DocDiscSeqIDC2 = orderline.DocDiscSeqIDC2;

					newtran = this.Transactions.Insert(newtran);

					if (((SOOrderType)order).CopyLineNotesToInvoice == true)
					{
						PXNoteAttribute.SetNote(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetNote(Caches[typeof(SOMiscLine2)], orderline));
					}

					if (((SOOrderType)order).CopyLineFilesToInvoice == true)
					{
						PXNoteAttribute.SetFileNotes(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetFileNotes(Caches[typeof(SOMiscLine2)], orderline));
					}
				}
			}

			SODocument.Current = (SOInvoice)SODocument.Select() ?? (SOInvoice)SODocument.Cache.Insert();
			SODocument.Current.BillAddressID = soOrder.BillAddressID;
			SODocument.Current.BillContactID = soOrder.BillContactID;
			SODocument.Current.ShipAddressID = soOrder.ShipAddressID;
			SODocument.Current.ShipContactID = soOrder.ShipContactID;
			SODocument.Current.IsCCCaptured = soOrder.IsCCCaptured;
			SODocument.Current.IsCCCaptureFailed = soOrder.IsCCCaptureFailed;
			SODocument.Current.PaymentProjectID = PM.ProjectDefaultAttribute.NonProject(this);
			
			if (soOrder.IsCCCaptured == true)
			{
				SODocument.Current.CuryCCCapturedAmt = soOrder.CuryCCCapturedAmt;
				SODocument.Current.CCCapturedAmt = soOrder.CCCapturedAmt;
			}

			SODocument.Current.RefTranExtNbr = soOrder.RefTranExtNbr;

			SOOrderShipment shipment = PXCache<SOOrderShipment>.CreateCopy((SOOrderShipment)order);
			shipment.InvoiceType = SODocument.Current.DocType;
			shipment.InvoiceNbr = SODocument.Current.RefNbr;
			shipmentlist.Cache.Update(shipment);

			FillFreightDetails((SOOrder)order, shipment);

            /*In case Discounts were not recalculated add prorated Doc discounts */
            if (ordertype.RecalculateDiscOnPartialShipment != true)
            {
                //add prorated document discount details from invoice:
                PXSelectBase<SOOrderDiscountDetail> selectOrderDocGroupDiscounts = new PXSelect<SOOrderDiscountDetail,
                Where<SOOrderDiscountDetail.orderType, Equal<Required<SOOrderDiscountDetail.orderType>>,
                And<SOOrderDiscountDetail.orderNbr, Equal<Required<SOOrderDiscountDetail.orderNbr>>>>>(this);

                decimal? rate = 1m;
                if (soOrder.LineTotal > 0m)
                    rate = shipment.LineTotal / soOrder.LineTotal;

                foreach (SOOrderDiscountDetail docGroupDisc in selectOrderDocGroupDiscounts.Select(((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
                {
                        SOInvoiceDiscountDetail dd = new SOInvoiceDiscountDetail();
                        dd.Type = docGroupDisc.Type;
                        dd.DiscountID = docGroupDisc.DiscountID;
                        dd.DiscountSequenceID = docGroupDisc.DiscountSequenceID;
                        dd.OrderType = docGroupDisc.OrderType;
                        dd.OrderNbr = docGroupDisc.OrderNbr;
                        dd.TranType = newdoc.DocType;
                        dd.RefNbr = newdoc.RefNbr;
                        dd.DiscountPct = docGroupDisc.DiscountPct;
                        dd.FreeItemID = docGroupDisc.FreeItemID;
                        dd.FreeItemQty = docGroupDisc.FreeItemQty;

                        if (docGroupDisc.Type == DiscountType.Group)
                        {
                            SOOrderEntry soOrderQ = (SOOrderEntry)PXGraph.CreateInstance(typeof(SOOrderEntry));
                            soOrderQ.Document.Current = order;

                            Dictionary<DiscountSequenceKey, DiscountEngine<SOLine>.DiscountDetailToLineCorrelation<SOOrderDiscountDetail>> grLinesOrderCorrelation = DiscountEngine<SOLine>.CollectGroupDiscountToLineCorrelation(soOrderQ.Transactions.Cache, soOrderQ.Transactions, soOrderQ.DiscountDetails, soOrder.CustomerLocationID, (DateTime)soOrder.OrderDate, false);

                            foreach (KeyValuePair<DiscountSequenceKey, DiscountEngine<SOLine>.DiscountDetailToLineCorrelation<SOOrderDiscountDetail>> dsGroup in grLinesOrderCorrelation)
                            {
                                if (dsGroup.Key.DiscountID == docGroupDisc.DiscountID && dsGroup.Key.DiscountSequenceID == docGroupDisc.DiscountSequenceID)
                                {
                                    decimal invoicedGroupAmt = 0m;
                                    foreach (SOLine soLine in dsGroup.Value.listOfApplicableLines)
                                    {
                                        foreach (ARTran tran in Transactions.Select())
                                        {
                                            if (soLine.LineNbr == tran.SOOrderLineNbr)
                                                invoicedGroupAmt += (tran.CuryLineAmt ?? 0m);
                                        }
                                    }
                                    rate = (invoicedGroupAmt / (decimal)dsGroup.Value.discountDetailLine.CuryDiscountableAmt);
                                }
                            }
                        }

                        SOInvoiceDiscountDetail located = DiscountDetails.Locate(dd);
                        if (located != null)
                        {
                            located.DiscountAmt += docGroupDisc.DiscountAmt * rate;
                            located.CuryDiscountAmt += docGroupDisc.CuryDiscountAmt * rate;
                            located.DiscountableAmt += docGroupDisc.DiscountableAmt * rate;
                            located.CuryDiscountableAmt += docGroupDisc.CuryDiscountableAmt * rate;
                            located.DiscountableQty += docGroupDisc.DiscountableQty * rate;

                            DiscountDetails.Update(located);
                        }
                        else
                        {
                            dd.DiscountAmt = docGroupDisc.DiscountAmt * rate;
                            dd.CuryDiscountAmt = docGroupDisc.CuryDiscountAmt * rate;
                            dd.DiscountableAmt = docGroupDisc.DiscountableAmt * rate;
                            dd.CuryDiscountableAmt = docGroupDisc.CuryDiscountableAmt * rate;
                            dd.DiscountableQty = docGroupDisc.DiscountableQty * rate;

                            DiscountDetails.Insert(dd);
                        }

                    }
                }
            else
            {
                //Recalculate all discounts
                foreach (ARTran tran in Transactions.Select())
                {
                    RecalculateDiscounts(this.Transactions.Cache, tran);
                }
            }
			RecalculateTotalDiscount();

			foreach (PXResult<SOTaxTran, Tax> res in PXSelectJoin<SOTaxTran,
				InnerJoin<Tax, On<SOTaxTran.taxID, Equal<Tax.taxID>>>,
				Where<SOTaxTran.orderType, Equal<Required<SOTaxTran.orderType>>, And<SOTaxTran.orderNbr, Equal<Required<SOTaxTran.orderNbr>>>>>.Select(this, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				SOTaxTran tax = (SOTaxTran)res;
				ARTaxTran newtax = new ARTaxTran();
				newtax.Module = BatchModule.AR;
                Taxes.Cache.SetDefaultExt<ARTaxTran.origTranType>(newtax);
                Taxes.Cache.SetDefaultExt<ARTaxTran.origRefNbr>(newtax);
				Taxes.Cache.SetDefaultExt<ARTaxTran.lineRefNbr>(newtax);
				newtax.TranType = Document.Current.DocType;
				newtax.RefNbr = Document.Current.RefNbr;
				newtax.TaxID = tax.TaxID;
				newtax.TaxRate = 0m;

				this.Taxes.Delete(newtax);

				newtax = this.Taxes.Insert(newtax);
			}

			decimal? CuryApplAmt = 0m;
			bool Calculated = false;

			

			foreach (SOAdjust soadj in PXSelectJoin<SOAdjust, InnerJoin<AR.ARPayment, On<AR.ARPayment.docType, Equal<SOAdjust.adjgDocType>, And<AR.ARPayment.refNbr, Equal<SOAdjust.adjgRefNbr>>>>, Where<SOAdjust.adjdOrderType, Equal<Required<SOAdjust.adjdOrderType>>, And<SOAdjust.adjdOrderNbr, Equal<Required<SOAdjust.adjdOrderNbr>>, And<AR.ARPayment.openDoc, Equal<True>>>>>.Select(this, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				ARAdjust prev_adj = null;
				bool found = false;

				foreach (ARAdjust adj in Adjustments.Select())
				{
					if (Calculated)
					{
						CuryApplAmt -= adj.CuryAdjdAmt;
					}

					if (string.Equals(adj.AdjgDocType, soadj.AdjgDocType) && string.Equals(adj.AdjgRefNbr, soadj.AdjgRefNbr))
					{
						if (soadj.CuryAdjdAmt > 0m)
						{
							ARAdjust copy = PXCache<ARAdjust>.CreateCopy(adj);
							copy.CuryAdjdAmt += (soadj.CuryAdjdAmt > adj.CuryDocBal) ? adj.CuryDocBal : soadj.CuryAdjdAmt;
							copy.AdjdOrderType = soadj.AdjdOrderType;
							copy.AdjdOrderNbr = soadj.AdjdOrderNbr;
							prev_adj = Adjustments.Update(copy);
						}

						found = true;

						if (Calculated)
						{
							CuryApplAmt += adj.CuryAdjdAmt;
							break;
						}
					}

					CuryApplAmt += adj.CuryAdjdAmt;
				}

				//if soadjust is not available in adjustments mark as billed
				if (!found)
				{
				/*
					soadj.Billed = true;
					soadjustments.Cache.SetStatus(soadj, PXEntryStatus.Updated);
				*/
				}

				Calculated = true;

				if (!IsExternalTax)
				{
					if (CuryApplAmt > Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt && prev_adj != null)
					{
						prev_adj = PXCache<ARAdjust>.CreateCopy(prev_adj);

						if (prev_adj.CuryAdjdAmt > (CuryApplAmt - (Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt)))
						{
							prev_adj.CuryAdjdAmt -= (CuryApplAmt - (Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt));
							CuryApplAmt = Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt;
						}
						else
						{
							CuryApplAmt -= prev_adj.CuryAdjdAmt;
							prev_adj.CuryAdjdAmt = 0m;
						}

						prev_adj = Adjustments.Update(prev_adj);
					}
				}
			}

			newdoc = (ARInvoice)Document.Cache.CreateCopy(Document.Current);
			newdoc.OrigDocDate = origInvoiceDate;
			SOInvoice socopy = (SOInvoice)SODocument.Cache.CreateCopy(SODocument.Current);

			PXFormulaAttribute.CalcAggregate<ARAdjust.curyAdjdAmt>(Adjustments.Cache, SODocument.Current, false);
			Document.Cache.RaiseFieldUpdated<SOInvoice.curyPaymentTotal>(SODocument.Current, null);
			PXDBCurrencyAttribute.CalcBaseValues<SOInvoice.curyPaymentTotal>(SODocument.Cache, SODocument.Current);

			SODocument.Cache.RaiseRowUpdated(SODocument.Current, socopy);

			List<string> ordersdistinct = new List<string>();
			foreach (SOOrderShipment shipments in PXSelect<SOOrderShipment, Where<SOOrderShipment.invoiceType, Equal<Current<ARInvoice.docType>>, And<SOOrderShipment.invoiceNbr, Equal<Current<ARInvoice.refNbr>>>>>.Select(this))
			{
				string key = string.Format("{0}|{1}", shipments.OrderType, shipments.OrderNbr);
				if (!ordersdistinct.Contains(key))
				{
					ordersdistinct.Add(key);
				}

				if (ordersdistinct.Count > 1)
				{
					newdoc.InvoiceNbr = null;
					newdoc.SalesPersonID = null;
					newdoc.DocDesc = null;
					break;
				}

				#region Update FreeItemQty for DiscountDetails based on shipments
				
				PXSelectBase<SOShipmentDiscountDetail> selectShipmentDiscounts = new PXSelect<SOShipmentDiscountDetail,
						Where<SOShipmentDiscountDetail.orderType, Equal<Required<SOShipmentDiscountDetail.orderType>>,
						And<SOShipmentDiscountDetail.orderNbr, Equal<Required<SOShipmentDiscountDetail.orderNbr>>,
						And<SOShipmentDiscountDetail.shipmentNbr, Equal<Required<SOShipmentDiscountDetail.shipmentNbr>>>>>>(this);

				foreach (SOShipmentDiscountDetail sdd in selectShipmentDiscounts.Select(shipments.OrderType, shipments.OrderNbr, shipments.ShipmentNbr))
				{
					SOInvoiceDiscountDetail idd = PXSelect<SOInvoiceDiscountDetail,
						Where<SOInvoiceDiscountDetail.tranType, Equal<Current<ARInvoice.docType>>,
						And<SOInvoiceDiscountDetail.refNbr, Equal<Current<ARInvoice.refNbr>>,
						And<SOInvoiceDiscountDetail.orderType, Equal<Required<SOInvoiceDiscountDetail.orderType>>,
						And<SOInvoiceDiscountDetail.orderNbr, Equal<Required<SOInvoiceDiscountDetail.orderNbr>>,
						And<SOInvoiceDiscountDetail.discountID, Equal<Required<SOInvoiceDiscountDetail.discountID>>,
						And<SOInvoiceDiscountDetail.discountSequenceID, Equal<Required<SOInvoiceDiscountDetail.discountSequenceID>>>>>>>>>.Select(this, shipments.OrderType, shipments.OrderNbr, sdd.DiscountID, sdd.DiscountSequenceID);

					if (idd != null)
					{
						if (idd.FreeItemID == null)
						{
							idd.FreeItemID = sdd.FreeItemID;
							idd.FreeItemQty = sdd.FreeItemQty;
						}
						else
							idd.FreeItemQty = sdd.FreeItemQty;

						DiscountDetails.Update(idd);
					}
					else
					{
						idd = new SOInvoiceDiscountDetail();
						idd.Type = DiscountType.Line;
						idd.TranType = newdoc.DocType;
						idd.RefNbr = newdoc.RefNbr;
						idd.OrderType = sdd.OrderType;
						idd.OrderNbr = sdd.OrderNbr;
						idd.DiscountID = sdd.DiscountID;
						idd.DiscountSequenceID = sdd.DiscountSequenceID;
						idd.FreeItemID = sdd.FreeItemID;
						idd.FreeItemQty = sdd.FreeItemQty;

						DiscountDetails.Insert(idd);
					}
				} 

				#endregion
			}

            this.Document.Update(newdoc);

			if (list != null)
			{
				if (Transactions.Search<ARTran.sOOrderType, ARTran.sOOrderNbr, ARTran.sOShipmentType, ARTran.sOShipmentNbr>(shipment.OrderType, shipment.OrderNbr, shipment.ShipmentType, shipment.ShipmentNbr).Count > 0)
				{
					try
					{
						this.Document.Current.ApplyPaymentWhenTaxAvailable = true;
						this.Save.Press();
					}
					finally
					{
						this.Document.Current.ApplyPaymentWhenTaxAvailable = false;
					}
					

					if (list.Find(this.Document.Current) == null)
					{
						list.Add(this.Document.Current, this.SODocument.Current);
					}
				}
				else
				{
					this.Clear();
				}
			}
            this.RowUpdated.RemoveHandler(typeof(ARInvoice), ApprovedBalanceCollector);
		}
Example #33
0
		protected override void ApplyAvalaraTax(ARInvoice invoice, GetTaxResult result)
		{
			TaxZone taxZone = (TaxZone)taxzone.View.SelectSingleBound(new object[] { invoice });
			AP.Vendor vendor = PXSelect<AP.Vendor, Where<AP.Vendor.bAccountID, Equal<Required<AP.Vendor.bAccountID>>>>.Select(this, taxZone.TaxVendorID);

			if (vendor == null)
				throw new PXException("Tax Vendor is required but not found for the External TaxZone.");

			Dictionary<string, ARTaxTran> existingRows = new Dictionary<string, ARTaxTran>();
			foreach (PXResult<ARTaxTran, Tax> res in Taxes.View.SelectMultiBound(new object[] { invoice }))
			{
				ARTaxTran taxTran = (ARTaxTran)res;
				existingRows.Add(taxTran.TaxID.Trim().ToUpperInvariant(), taxTran);
			}

			this.Views.Caches.Add(typeof(Tax));

			bool requireControlTotal = ARSetup.Current.RequireControlTotal == true;

			if (invoice.Hold != true)
				ARSetup.Current.RequireControlTotal = false;

			try
			{

				for (int i = 0; i < result.TaxSummary.Count; i++)
				{
					string taxID = result.TaxSummary[i].TaxName.ToUpperInvariant();

					//Insert Tax if not exists - just for the selectors sake
					Tax tx = PXSelect<Tax, Where<Tax.taxID, Equal<Required<Tax.taxID>>>>.Select(this, taxID);
					if (tx == null)
					{
						tx = new Tax();
						tx.TaxID = taxID;
						//tx.Descr = string.Format("Avalara {0} {1}%", taxID, Convert.ToDecimal(result.TaxSummary[i].Rate)*100);
						tx.Descr = string.Format("Avalara {0}", taxID);
						tx.TaxType = CSTaxType.Sales;
						tx.TaxCalcType = CSTaxCalcType.Doc;
						tx.TaxCalcLevel = CSTaxCalcLevel.CalcOnItemAmt;
						tx.TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount;
						tx.SalesTaxAcctID = vendor.SalesTaxAcctID;
						tx.SalesTaxSubID = vendor.SalesTaxSubID;
						tx.ExpenseAccountID = vendor.TaxExpenseAcctID;
						tx.ExpenseSubID = vendor.TaxExpenseSubID;
						tx.TaxVendorID = taxZone.TaxVendorID;

						this.Caches[typeof(Tax)].Insert(tx);
					}

					ARTaxTran existing = null;
					existingRows.TryGetValue(taxID, out existing);

					if (existing != null)
					{
						existing.TaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						existing.CuryTaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						existing.TaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						existing.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						existing.TaxRate = Convert.ToDecimal(result.TaxSummary[i].Rate);

						Taxes.Update(existing);
						existingRows.Remove(existing.TaxID.Trim().ToUpperInvariant());
					}
					else
					{
						ARTaxTran tax = new ARTaxTran();
						tax.Module = BatchModule.AR;
						tax.TranType = invoice.DocType;
						tax.RefNbr = invoice.RefNbr;
						tax.TaxID = taxID;
						tax.TaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						tax.CuryTaxAmt = Math.Abs(result.TaxSummary[i].Tax);
						tax.TaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						tax.CuryTaxableAmt = Math.Abs(result.TaxSummary[i].Taxable);
						tax.TaxRate = Convert.ToDecimal(result.TaxSummary[i].Rate);
						tax.TaxType = "S";
						tax.TaxBucketID = 0;
						tax.AccountID = vendor.SalesTaxAcctID;
						tax.SubID = vendor.SalesTaxSubID;

						Taxes.Insert(tax);
					}
				}

				foreach (ARTaxTran taxTran in existingRows.Values)
				{
					Taxes.Delete(taxTran);
				}

				SOInvoice soInvoice = PXSelect<SOInvoice, Where<SOInvoice.docType, Equal<Required<SOInvoice.docType>>, And<SOInvoice.refNbr, Equal<Required<SOInvoice.refNbr>>>>>.Select(this, invoice.DocType, invoice.RefNbr);

				invoice.CuryTaxTotal = Math.Abs(result.TotalTax);
				Document.Cache.SetValueExt<ARInvoice.isTaxSaved>(invoice, true);
			}
			finally
			{
				ARSetup.Current.RequireControlTotal = requireControlTotal;
			}


			if (invoice.ApplyPaymentWhenTaxAvailable == true)
			{
				PXSelectBase<ARAdjust> select = new PXSelectJoin<ARAdjust,
					InnerJoin<ARPayment, On<ARAdjust.adjgDocType, Equal<ARPayment.docType>, And<ARAdjust.adjgRefNbr, Equal<ARPayment.refNbr>>>>,
					Where<ARAdjust.adjdDocType, Equal<Required<ARInvoice.docType>>,
					And<ARAdjust.adjdRefNbr, Equal<Required<ARInvoice.refNbr>>>>>(this);


				foreach (PXResult<ARAdjust, ARPayment> res in select.Select(invoice.DocType, invoice.RefNbr))
				{
					ARAdjust row = (ARAdjust)res;
					ARPayment payment = (ARPayment)res;

					ARAdjust copy = PXCache<ARAdjust>.CreateCopy(row);
					copy.CuryAdjdAmt = Math.Min(copy.CuryAdjdAmt.GetValueOrDefault(), invoice.CuryDocBal.GetValueOrDefault());
					Adjustments.Update(copy);
				}
			}

		}
Example #34
0
		public virtual void PostInvoice(INIssueEntry docgraph, ARInvoice invoice, DocumentList<INRegister> list)
		{
			SOOrderEntry oe = null;
			SOShipmentEntry se = null;

			foreach (PXResult<SOOrderShipment, SOOrder> res in PXSelectJoin<SOOrderShipment, InnerJoin<SOOrder, On<SOOrder.orderType, Equal<SOOrderShipment.orderType>, And<SOOrder.orderNbr, Equal<SOOrderShipment.orderNbr>>>>, Where<SOOrderShipment.invoiceType, Equal<Current<ARInvoice.docType>>, And<SOOrderShipment.invoiceNbr, Equal<Current<ARInvoice.refNbr>>>>>.SelectMultiBound(this, new object[] { invoice }))
			{
				if (((SOOrderShipment)res).ShipmentType == SOShipmentType.DropShip)
				{
					if (se == null)
					{
						se = PXGraph.CreateInstance<SOShipmentEntry>();
					}
					else
					{
						se.Clear();
					}
					se.PostReceipt(docgraph, res, list);
				}
				else if (string.Equals(((SOOrderShipment)res).ShipmentNbr, Constants.NoShipmentNbr))
				{
					if (oe == null)
					{
						oe = PXGraph.CreateInstance<SOOrderEntry>();
					}
					else
					{
						oe.Clear();
					}
					oe.PostOrder(docgraph, (SOOrder)res, list);
				}
				else
				{
					if (se == null)
					{
						se = PXGraph.CreateInstance<SOShipmentEntry>();

						se.Caches[typeof(SiteStatus)] = docgraph.Caches[typeof(SiteStatus)];
						se.Caches[typeof(LocationStatus)] = docgraph.Caches[typeof(LocationStatus)];
						se.Caches[typeof(LotSerialStatus)] = docgraph.Caches[typeof(LotSerialStatus)];
						se.Caches[typeof(ItemLotSerial)] = docgraph.Caches[typeof(ItemLotSerial)];

						se.Views.Caches.Remove(typeof(SiteStatus));
						se.Views.Caches.Remove(typeof(LocationStatus));
						se.Views.Caches.Remove(typeof(LotSerialStatus));
						se.Views.Caches.Remove(typeof(ItemLotSerial));
					}
					else
					{
						se.Clear();
					}
					se.PostShipment(docgraph, res, list);
				}
			}		
		}
Example #35
0
		public override IEnumerable Release(PXAdapter adapter)
		{
			List<ARRegister> list = new List<ARRegister>();
			foreach (ARInvoice order in adapter.Get<ARInvoice>())
			{
				list.Add(order);
			}

			if (!IsExternalTax)
			{
				Save.Press();
			}
			else
			{
				try
				{
					skipAvalaraCallOnSave = true;
					Save.Press();
				}
				finally
				{
					skipAvalaraCallOnSave = false;
				}
			}

			PXLongOperation.StartOperation(this, delegate()
			{
				List<ARRegister> listWithTax = new List<ARRegister>();
				if (!IsExternalTax)
				{
					foreach (ARInvoice ardoc in list)
					{
						if (ardoc.IsTaxValid != true && AvalaraMaint.IsExternalTax(this, ardoc.TaxZoneID))
						{
							ARInvoice doc = new ARInvoice();
							doc.DocType = ardoc.DocType;
							doc.RefNbr = ardoc.RefNbr;
							doc.OrigModule = ardoc.OrigModule;
							doc.ApplyPaymentWhenTaxAvailable = ardoc.ApplyPaymentWhenTaxAvailable;
							listWithTax.Add(ARExternalTaxCalc.Process(doc));
						}
						else
						{
							listWithTax.Add(ardoc);
						}
					}
				}
				else
				{
					listWithTax.AddRange(list);
				}

				SOInvoiceEntry ie = PXGraph.CreateInstance<SOInvoiceEntry>();				
				INIssueEntry ingraph = PXGraph.CreateInstance<INIssueEntry>();
				SOOrderShipmentProcess docgraph = PXGraph.CreateInstance<SOOrderShipmentProcess>();
				HashSet<object> processed = new HashSet<object>();
						
				//Field Verification can fail if IN module is not "Visible";therfore suppress it:
				ingraph.FieldVerifying.AddHandler<INTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
				ingraph.FieldVerifying.AddHandler<INTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
				

				ARDocumentRelease.ReleaseDoc(listWithTax, adapter.MassProcess, null, delegate(ARRegister ardoc, bool isAborted)
				{
					List<object> items = new List<object>();
					items.Add(ardoc);
					PXAutomation.RemovePersisted(ie, typeof(ARInvoice), items);

					docgraph.Clear();
					foreach (PXResult<SOOrderShipment, SOOrder> ordershipment in docgraph.Items.View.SelectMultiBound(new object[] { ardoc }))
					{
						SOOrderShipment copy = PXCache<SOOrderShipment>.CreateCopy(ordershipment);
						SOOrder order = ordershipment;
						copy.InvoiceReleased = true;
						docgraph.Items.Update(copy);

						if (order.Completed == true && order.BilledCntr <= 1 && order.ShipmentCntr <= order.BilledCntr + order.ReleasedCntr)
						{
							foreach (SOAdjust adj in docgraph.Adjustments.Select(order.OrderType, order.OrderNbr))
							{
								SOAdjust adjcopy = PXCache<SOAdjust>.CreateCopy(adj);
								adjcopy.CuryAdjdAmt = 0m;
								adjcopy.CuryAdjgAmt = 0m;
								adjcopy.AdjAmt = 0m;
								docgraph.Adjustments.Update(adjcopy);
							}
						}
						processed.Add(ardoc);
					}
					docgraph.Actions.PressSave();
				});
				PXAutomation.StorePersisted(ie, typeof(ARInvoice), new List<object>(processed));
				PXAutomation.CompleteAction(docgraph);				
			});
			return list;
		}