Ejemplo n.º 1
0
    protected void grid_OnRowDataBound(object sender, PX.Web.UI.PXGridRowEventArgs e)
    {
        var graph = (StoragePlaceEnq)((PXGrid)sender).DataGraph;
        StoragePlaceStatus tran;

        PXResult record = e.Row.DataItem as PXResult;

        if (record != null)
        {
            tran = (StoragePlaceStatus)record[typeof(StoragePlaceStatus)];
        }
        else
        {
            tran = e.Row.DataItem as StoragePlaceStatus;
        }

        if (tran == null)
        {
            return;
        }

        //if (graph.Filter.Current.With(_ => _.ExpandByLotSerialNbr) == true && tran.IsOverall == true)
        //{
        //	e.Row.Style.CssClass = PickCss.Splitting;
        //}
        //else
        //{
        //	e.Row.Style.Reset();
        //}
    }
        protected virtual FinPeriod BuildFinPeriod(int?organizationID, object record)
        {
            if (organizationID == FinPeriod.organizationID.MasterValue &&
                MasterPeriodBasedOnOrganizationPeriods)
            {
                MasterFinPeriod baseFinPeriod = (record as PXResult).GetItem <MasterFinPeriod>();

                return(new FinPeriod()
                {
                    FinPeriodID = baseFinPeriod.FinPeriodID,
                    StartDateUI = baseFinPeriod.StartDateUI,
                    EndDateUI = baseFinPeriod.EndDateUI,
                    Descr = baseFinPeriod.Descr,
                    NoteID = baseFinPeriod.NoteID
                });
            }
            else
            {
                PXResult resultRecord = record as PXResult;

                FinPeriod orgFinPeriod = resultRecord != null
                                                                                                        ? resultRecord.GetItem <FinPeriod>()
                                                                                                        : (FinPeriod)record;

                return(new FinPeriod
                {
                    FinPeriodID = orgFinPeriod.FinPeriodID,
                    StartDateUI = orgFinPeriod.StartDateUI,
                    EndDateUI = orgFinPeriod.EndDateUI,
                    Descr = orgFinPeriod.Descr,
                    NoteID = orgFinPeriod.NoteID
                });
            }
        }
        public static int?PeriodMinusPeriod(PXGraph graph, string FiscalPeriodID1, string FiscalPeriodID2, int?BookID)
        {
            // TODO: AC-106141
            // Use BranchID (OrganizationID) passed as parameter
            int count = PXSelect <
                FABookPeriod,
                Where <FABookPeriod.bookID, Equal <Required <FABookPeriod.bookID> >,
                       And <Where <FABookPeriod.finPeriodID, Equal <Required <FABookPeriod.finPeriodID> >,
                                   Or <FABookPeriod.finPeriodID, Equal <Required <FABookPeriod.finPeriodID> > > > > > >
                        .Select(graph, BookID, FiscalPeriodID1, FiscalPeriodID2)
                        .Count;

            if (count < 2 && string.Equals(FiscalPeriodID1, FiscalPeriodID2) == false)
            {
                throw new PXException(Messages.NoCalendarDefined);
            }

            // TODO: AC-106141
            // Use BranchID (OrganizationID) passed as parameter
            PXResult res = PXSelectGroupBy <
                FABookPeriod,
                Where <FABookPeriod.bookID, Equal <Required <FABookPeriod.bookID> >,
                       And <FABookPeriod.finPeriodID, LessEqual <Required <FABookPeriod.finPeriodID> >,
                            And <FABookPeriod.finPeriodID, Greater <Required <FABookPeriod.finPeriodID> >,
                                 And <FABookPeriod.endDate, Greater <FABookPeriod.startDate> > > > >,
                Aggregate <
                    GroupBy <FABookPeriod.bookID, Count> > >
                           .Select(graph, BookID, FiscalPeriodID1, FiscalPeriodID2);

            return(res != null ? res.RowCount : null);
        }
Ejemplo n.º 4
0
        /// <summary> SOPackageDetailEx_qty Updated Event </summary>
        protected void _(Events.FieldUpdated <SOPackageDetail.qty> e)
        {
            var _splitLineNbr = e.Cache.GetExtension <SOPackageDetailExt>(e.Row).UsrShipmentSplitLineNbr;

            if (e.NewValue == null || _splitLineNbr == null)
            {
                return;
            }

            if ((decimal?)e.NewValue == 0)
            {
                e.Cache.SetValueExt <SOPackageDetail.weight>(e.Row, 0);
                return;
            }

            var row = (SOPackageDetailEx)e.Row;

            var _shipLine = Base.Transactions.Cache.Cached.RowCast <SOShipLine>().Where(x => x.LineNbr == _splitLineNbr).SingleOrDefault();
            PXResult <InventoryItem, CSAnswers> _sotockItemData = GetStockInfo(_shipLine.InventoryID.Value, _QTYINBOX);
            decimal _qtyInBox = 1;

            try
            {
                _qtyInBox = decimal.Parse(_sotockItemData.GetItem <CSAnswers>()?.Value);
            }
            catch (Exception)
            {
                _qtyInBox = 1;
            }

            e.Cache.SetValueExt <SOPackageDetail.weight>(e.Row, row.Qty * _sotockItemData.GetItem <InventoryItem>().BaseItemWeight / _qtyInBox);
        }
Ejemplo n.º 5
0
        protected virtual IEnumerable viewHandler()
        {
            if (intView == null)
            {
                intView = CreateIntView(View.Graph);
            }
            int startRow = PXView.StartRow;
            int num      = 0;
            PXDelegateResult pXDelegateResult = new PXDelegateResult();

            foreach (object obj in intView.Select(null, null, PXView.Searches, PXView.SortColumns, PXView.Descendings, PXView.Filters, ref startRow, PXView.MaximumRows, ref num))
            {
                var statu  = PXResult.Unwrap <RowToSelect>(obj);
                var statu1 = statu;
                var statu2 = (Cache.Locate(statu) as RowToSelect);
                if (statu2 != null)
                {
                    bool?value = (Cache.GetValue(statu2, Selected) as bool?);
                    if (value.GetValueOrDefault() & value.HasValue)
                    {
                        Cache.RestoreCopy(statu2, statu);
                        Cache.SetValue(statu2, Selected, true);
                        statu1 = statu2;
                    }
                }
                pXDelegateResult.Add(statu1);
            }
            PXView.StartRow = 0;
            if (PXView.ReverseOrder)
            {
                pXDelegateResult.Reverse();
            }
            pXDelegateResult.IsResultSorted = true;
            return(pXDelegateResult);
        }
Ejemplo n.º 6
0
        public virtual IEnumerable export(PXAdapter adapter)
        {
            CheckPrevOperation();
            CABatch document = this.Document.Current;

            if (document != null && document.Released == true && document.Hold == false)
            {
                PXResult <PaymentMethod, SYMapping> res = (PXResult <PaymentMethod, SYMapping>) PXSelectJoin <PaymentMethod,
                                                                                                              LeftJoin <SYMapping, On <SYMapping.mappingID, Equal <PaymentMethod.aPBatchExportSYMappingID> > >,
                                                                                                              Where <PaymentMethod.paymentMethodID, Equal <Optional <CABatch.paymentMethodID> > > > .Select(this, document.PaymentMethodID);

                PaymentMethod pt  = res;
                SYMapping     map = res;
                if (pt != null && pt.APCreateBatchPayment == true && pt.APBatchExportSYMappingID != null && map != null)
                {
                    string defaultFileName = this.GenerateFileName(document);
                    PXLongOperation.StartOperation(this, delegate()
                    {
                        PX.Api.SYExportProcess.RunScenario(map.Name,
                                                           SYMapping.RepeatingOption.All,
                                                           true,
                                                           true,
                                                           new PX.Api.PXSYParameter(ExportProviderParams.FileName, defaultFileName),
                                                           new PX.Api.PXSYParameter(ExportProviderParams.BatchNbr, document.BatchNbr));
                    });
                }
                else
                {
                    throw new PXException(Messages.CABatchExportProviderIsNotConfigured);
                }
            }
            return(adapter.Get());
        }
Ejemplo n.º 7
0
        protected virtual IEnumerable documentList()
        {
            foreach (PXResult <APInvoiceExt> result in PXSelect <APInvoiceExt,
                                                                 Where2 <
                                                                     Where <Current2 <APRetainageFilter.vendorID>, IsNull, Or <APInvoiceExt.vendorID, Equal <Current2 <APRetainageFilter.vendorID> > > >,
                                                                     And2 <Where <Current2 <APRetainageFilter.projectID>, IsNull, Or <APInvoiceExt.projectID, Equal <Current2 <APRetainageFilter.projectID> > > >,
                                                                           And2 <Where <Current2 <APRetainageFilter.branchID>, IsNull, Or <APInvoiceExt.branchID, Equal <Current2 <APRetainageFilter.branchID> > > >,
                                                                                 And2 <Where <Current <APRetainageFilter.showBillsWithOpenBalance>, Equal <True>,
                                                                                              Or <Where <APInvoiceExt.curyDocBal, Equal <decimal0>,
                                                                                                         And <Current <APRetainageFilter.showBillsWithOpenBalance>, NotEqual <True> > > > >,
                                                                                       And <APInvoiceExt.curyRetainageUnreleasedAmt, Greater <decimal0>,
                                                                                            And <APInvoiceExt.curyRetainageTotal, Greater <decimal0>,
                                                                                                 And <APInvoiceExt.docType, Equal <APDocType.invoice>,
                                                                                                      And <APInvoiceExt.retainageApply, Equal <True>,
                                                                                                           And <APInvoiceExt.released, Equal <True>,
                                                                                                                And <APInvoiceExt.docDate, LessEqual <Current <APRetainageFilter.docDate> > > > > > > > > > > >,
                                                                 OrderBy <Asc <APInvoiceExt.refNbr> > > .Select(this))
            {
                APInvoiceExt doc = result;

                PXResult <APRetainageInvoice> NotReleasedRetainageInvoice = PXSelect <APRetainageInvoice,
                                                                                      Where <APRetainageInvoice.isRetainageDocument, Equal <True>,
                                                                                             And <APRetainageInvoice.origDocType, Equal <Required <APInvoice.docType> >,
                                                                                                  And <APRetainageInvoice.origRefNbr, Equal <Required <APInvoice.refNbr> >,
                                                                                                       And <APRetainageInvoice.released, NotEqual <True> > > > > > .SelectSingleBound(this, null, doc.DocType, doc.RefNbr);

                if (NotReleasedRetainageInvoice == null)
                {
                    yield return(doc);
                }
            }
        }
Ejemplo n.º 8
0
        private bool DoesJointPayeeInternalIdMatchGenerationKey(PXResult jointPayeePayment)
        {
            var jointPayee = jointPayeePayment.GetItem <JointPayee>();

            return(jointPayee.JointPayeeInternalId != null &&
                   jointPayee.JointPayeeInternalId == generationKey.JointPayeeVendorId);
        }
        protected virtual void FixedAsset_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
        {
            FixedAsset header = (FixedAsset)e.Row;

            if (header == null)
            {
                return;
            }

            if (header.Depreciable == true && (header.UsefulLife ?? 0m) == 0m)
            {
                sender.RaiseExceptionHandling <FixedAsset.usefulLife>(header, header.UsefulLife, new PXSetPropertyException(CS.Messages.Entry_GT, PXErrorLevel.Error, 0m));
            }
            if (header.Active != true)
            {
                PXSelectBase <FixedAsset> selectStatement = new PXSelectJoin <FixedAsset,
                                                                              InnerJoin <FADetails, On <FixedAsset.assetID, Equal <FADetails.assetID> > >,
                                                                              Where <FixedAsset.classID, Equal <Required <FixedAsset.classID> >,
                                                                                     And <Where <FADetails.status, Equal <FixedAssetStatus.active> > > > >(this);

                PXResult <FixedAsset, FADetails> res = (PXResult <FixedAsset, FADetails>)selectStatement.View.SelectSingle(header.AssetID);
                if ((FixedAsset)res != null)
                {
                    sender.RaiseExceptionHandling <FixedAsset.active>(header, header.Active, new PXSetPropertyException(Messages.FixedAssetClassCannotBeDeactivated));
                }
            }
        }
Ejemplo n.º 10
0
        private (List <object> PerUnitInclusiveTaxes, List <object> PerUnitLevel1Taxes) GetNonExcludedPerUnitTaxesByCalculationLevel(List <object> allPerUnitTaxes)
        {
            List <object> perUnitLevel1Taxes    = new List <object>(capacity: allPerUnitTaxes.Count);
            List <object> perUnitInclusiveTaxes = new List <object>(capacity: allPerUnitTaxes.Count);

            foreach (object taxRow in allPerUnitTaxes)
            {
                Tax perUnitTax = PXResult.Unwrap <Tax>(taxRow);

                if (perUnitTax.TaxCalcLevel2Exclude != false)
                {
                    continue;
                }

                switch (perUnitTax.TaxCalcLevel)
                {
                case CSTaxCalcLevel.CalcOnItemQtyInclusively:
                    perUnitInclusiveTaxes.Add(taxRow);
                    continue;

                case CSTaxCalcLevel.CalcOnItemQtyExclusively:
                    perUnitLevel1Taxes.Add(taxRow);
                    continue;
                }
            }

            return(perUnitInclusiveTaxes, perUnitLevel1Taxes);
        }
Ejemplo n.º 11
0
        public virtual void ARTranSplit_LotSerialNbr_FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
        {
            PXResult <InventoryItem, INLotSerClass> item = ReadInventoryItem(sender, ((ARTranAsSplit)e.Row).InventoryID);

            if (item != null)
            {
                object InvtMult = ((ARTranAsSplit)e.Row).InvtMult;
                if (InvtMult == null)
                {
                    sender.RaiseFieldDefaulting <ARTranAsSplit.invtMult>(e.Row, out InvtMult);
                }

                INLotSerTrack.Mode mode = GetTranTrackMode((ILSMaster)e.Row, item);
                if (mode == INLotSerTrack.Mode.None || (mode & INLotSerTrack.Mode.Create) > 0)
                {
                    ILotSerNumVal lotSerNum = ReadLotSerNumVal(sender, item);
                    foreach (ARTranAsSplit lssplit in INLotSerialNbrAttribute.CreateNumbers <ARTranAsSplit>(sender, item, lotSerNum, mode, 1m))
                    {
                        e.NewValue = lssplit.LotSerialNbr;
                        e.Cancel   = true;
                    }
                }
                //otherwise default via attribute
            }
        }
        public virtual void RenumberAll(IComparer <PXResult> comparer)
        {
            PXResultset <Table> res  = Select();
            List <PXResult>     list = new List <PXResult>(res.Count);

            foreach (PXResult item in res)
            {
                list.Add(item);
            }

            list.Sort(comparer);

            int sortorder = 0;

            foreach (PXResult item in list)
            {
                sortorder++;
                Table line = PXResult.Unwrap <Table>(item);
                if (line.SortOrder != sortorder)
                {
                    Cache.SetValue(line, nameof(ISortOrder.SortOrder), sortorder);
                    Cache.SmartSetStatus(line, PXEntryStatus.Updated);
                    Cache.IsDirty = true;
                }
            }

            View.Clear();            //clears stored cache so that grid lines are reordered.
        }
        void ICustomerDataReader.ReadData(Dictionary <string, string> aData)
        {
            PXResult <Customer, CR.Address, CR.Contact> result = null;

            if (_customerID != 0)
            {
                result = (PXResult <Customer, CR.Address, CR.Contact>) PXSelectJoin <Customer,
                                                                                     LeftJoin <CR.Address, On <CR.Address.addressID, Equal <Customer.defBillAddressID> >,
                                                                                               LeftJoin <CR.Contact, On <CR.Contact.contactID, Equal <Customer.defBillContactID> > > >,
                                                                                     Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(_graph, _customerID);
            }
            else if (!string.IsNullOrEmpty(_customerCD))
            {
                result = (PXResult <Customer, CR.Address, CR.Contact>) PXSelectJoin <Customer,
                                                                                     LeftJoin <CR.Address, On <CR.Address.addressID, Equal <Customer.defBillAddressID> >,
                                                                                               LeftJoin <CR.Contact, On <CR.Contact.contactID, Equal <Customer.defBillContactID> > > >,
                                                                                     Where <Customer.acctCD, Equal <Required <Customer.acctCD> > > > .Select(_graph, _customerCD);
            }
            PXResult <CustomerPaymentMethod> pmResult = PXSelect <CustomerPaymentMethod,
                                                                  Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > >
                                                        .Select(_graph, _pminstanceID);

            if (result != null)
            {
                CustomerPaymentMethod customerPaymentMethod = pmResult;
                Customer customer = result;

                Address billAddress = null;
                Address address     = PXSelect <Address, Where <Address.addressID, Equal <Required <Address.addressID> > > > .Select(_graph,
                                                                                                                                     customerPaymentMethod.BillAddressID);

                billAddress = address ?? result;

                Contact billContact = null;
                Contact contact     = PXSelect <Contact, Where <CR.Contact.contactID, Equal <Required <Contact.contactID> > > > .Select(_graph,
                                                                                                                                        customerPaymentMethod.BillContactID);

                billContact = contact ?? result;

                aData[key_CustomerCD]   = (_prefixForCustomerCD ?? String.Empty) + (customer.AcctCD ?? String.Empty);
                aData[key_CustomerName] = customer.AcctName;

                if (pmResult != null && !string.IsNullOrEmpty(((CustomerPaymentMethod)pmResult).CustomerCCPID))
                {
                    aData[Key_Customer_CCProcessingID] = ((CustomerPaymentMethod)pmResult).CustomerCCPID;
                }

                aData[key_Country]    = billAddress?.CountryID;
                aData[key_State]      = billAddress?.State;
                aData[key_City]       = billAddress?.City;
                aData[key_Address]    = CCProcessingHelper.ExtractStreetAddress(billAddress);
                aData[key_PostalCode] = billAddress?.PostalCode;

                aData[key_Customer_FirstName] = billContact?.FirstName;
                aData[key_Customer_LastName]  = billContact?.LastName;
                aData[key_Phone] = billContact?.Phone1;
                aData[key_Fax]   = billContact?.Fax;
                aData[key_Email] = billContact?.EMail;
            }
        }
    protected void grid_OnRowDataBound(object sender, PX.Web.UI.PXGridRowEventArgs e)
    {
        GLTranReclHist tran;

        PXResult record = e.Row.DataItem as PXResult;

        if (record != null)
        {
            tran = (GLTranReclHist)record[typeof(GLTranReclHist)];
        }
        else
        {
            tran = e.Row.DataItem as GLTranReclHist;
        }

        if (tran == null)
        {
            return;
        }

        if (tran.IsCurrent == true)
        {
            e.Row.Style.CssClass = "CssCurrentLine";
        }
    }
Ejemplo n.º 15
0
        public override object Map(KCMapObjectRequest request)
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(request.Target))
            {
                PXResult <KCMapping> exportMappingRow = _mappingMaint.ExportMappingRow.Select(request.EntityType, property.Name, request.ViewName).FirstOrDefault();
                if (exportMappingRow == null)
                {
                    continue;
                }
                KCMapping mapping = exportMappingRow.GetItem <KCMapping>();
                KCAcumaticaMappingField acumaticaField = exportMappingRow.GetItem <KCAcumaticaMappingField>();
                string formula = mapping.RuleType == KCRuleTypesConstants.Expression
                              ? mapping.SourceExpression
                              : acumaticaField?.FieldName;

                IDictionary <string, object> mappingValue = GetMappingValue(request, property);
                if (mappingValue == null || (property.PropertyType != typeof(bool?) && property.PropertyType != typeof(bool) && mappingValue.GetValue(formula) == null))
                {
                    continue;
                }
                MapField(request.EntityType, request.Target, property, mappingValue, formula);
            }

            return(request.Target);
        }
Ejemplo n.º 16
0
        protected virtual void SPWikiCategoryTags_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
        {
            SPWikiCategoryTags row = e.Row as SPWikiCategoryTags;

            if (row == null || row.PageName == null)
            {
                return;
            }

            PXResult <WikiPage, WikiPageLanguage> currentrow = (PXResult <WikiPage, WikiPageLanguage>) PXSelectJoin <WikiPage,
                                                                                                                     LeftJoin <WikiPageLanguage, On <WikiPage.pageID, Equal <WikiPageLanguage.pageID> > >,
                                                                                                                     Where <WikiPage.name, Equal <Required <WikiPage.name> > > > .SelectWindowed(this, 0, 1, row.PageName);

            if (currentrow != null)
            {
                WikiPage         wp  = currentrow[typeof(WikiPage)] as WikiPage;
                WikiPageLanguage wpl = currentrow[typeof(WikiPageLanguage)] as WikiPageLanguage;

                if (wp != null)
                {
                    row.PageName = wp.Name;
                    row.PageID   = wp.PageID;
                }

                if (wpl != null)
                {
                    row.PageTitle = wpl.Title;
                }
                else
                {
                    row.PageTitle = row.PageName;
                }
            }
        }
Ejemplo n.º 17
0
        protected virtual void TaxTotal_CuryTaxableAmt_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            TaxTotal taxdetOrig = sender.GetExtension <TaxTotal>(e.Row);

            if (taxdetOrig == null)
            {
                return;
            }

            decimal newValue = (decimal)(sender.GetValue(e.Row, typeof(TaxTotal.curyTaxableAmt).Name) ?? 0m);
            decimal oldValue = (decimal)(e.OldValue ?? 0m);

            if (CurrentDocument.TaxCalc != TaxCalc.NoCalc && e.ExternalCall &&
                newValue != oldValue)
            {
                foreach (object taxrow in SelectTaxes <
                             Where <Tax.taxID, Equal <Required <Tax.taxID> > > >(sender.Graph, null, PXTaxCheck.RecalcTotals, taxdetOrig.RefTaxID))
                {
                    TaxTotal taxdet = sender.GetExtension <TaxTotal>(((PXResult)taxrow)[0]);
                    Tax      tax    = PXResult.Unwrap <Tax>(taxrow);
                    TaxRev   taxrev = PXResult.Unwrap <TaxRev>(taxrow);

                    CalculateTaxSumTaxAmt(taxdet, tax, taxrev);
                }
            }
        }
Ejemplo n.º 18
0
        public override void ProccessItem(PXGraph graph, TPrimary item)
        {
            PXCache  cache   = graph.Caches[typeof(TPrimary)];
            TPrimary newItem = (TPrimary)cache.CreateInstance();

            PXCache <TPrimary> .RestoreCopy(newItem, item);

            string entityType = CSAnswerType.GetAnswerType(cache.GetItemType());
            string entityID   = CSAnswerType.GetEntityID(cache.GetItemType());

            PXView primaryView = graph.Views[graph.PrimaryView];

            object[] searches    = new object[primaryView.Cache.BqlKeys.Count];
            string[] sortcolumns = new string[primaryView.Cache.BqlKeys.Count];
            for (int i = 0; i < cache.BqlKeys.Count(); i++)
            {
                sortcolumns[i] = cache.BqlKeys[i].Name;
                searches[i]    = cache.GetValue(newItem, sortcolumns[i]);
            }
            int startRow = 0, totalRows = 0;

            List <object> result = primaryView.Select(null, null, searches, sortcolumns, null, null, ref startRow, 1, ref totalRows);

            newItem = (TPrimary)cache.CreateCopy(PXResult.Unwrap <TPrimary>(result[0]));

            foreach (FieldValue fieldValue in Fields.Cache.Cached.Cast <FieldValue>().Where(o => o.AttributeID == null && o.Selected == true))
            {
                PXFieldState  state    = cache.GetStateExt(newItem, fieldValue.Name) as PXFieldState;
                PXIntState    intState = state as PXIntState;
                PXStringState strState = state as PXStringState;
                if ((intState != null && intState.AllowedValues != null && intState.AllowedValues.Length > 0 &&
                     intState.AllowedValues.All(v => v != int.Parse(fieldValue.Value)))
                    ||
                    (strState != null && strState.AllowedValues != null && strState.AllowedValues.Length > 0 &&
                     strState.AllowedValues.All(v => v != fieldValue.Value)))
                {
                    throw new PXSetPropertyException(ErrorMessages.UnallowedListValue, fieldValue.Value, fieldValue.Name);
                }
                if (state != null && !Equals(state.Value, fieldValue.Value))
                {
                    cache.SetValueExt(newItem, fieldValue.Name, fieldValue.Value);
                    cache.Update(newItem);
                }

                result  = primaryView.Select(null, null, searches, sortcolumns, null, null, ref startRow, 1, ref totalRows);
                newItem = (TPrimary)cache.CreateCopy(PXResult.Unwrap <TPrimary>(result[0]));
            }

            PXCache attrCache = cache.Graph.Caches[typeof(CSAnswers)];

            foreach (FieldValue attrValue in Attributes.Cache.Cached.Cast <FieldValue>().Where(o => o.AttributeID != null && o.Selected == true))
            {
                CSAnswers attr = (CSAnswers)attrCache.CreateInstance();
                attr.AttributeID = attrValue.AttributeID;
                attr.EntityID    = cache.GetValue(newItem, entityID) as int?;
                attr.EntityType  = entityType;
                attr.Value       = attrValue.Value;
                attrCache.Update(attr);
            }
        }
            public override void CacheAttached(PXCache sender)
            {
                base.CacheAttached(sender);
                PXView outerview = new PXView(sender.Graph, true, _Select);
                PXView view      = sender.Graph.Views[_ViewName] = new PXView(sender.Graph, true, _Select, (PXSelectDelegate) delegate()
                {
                    int startRow  = PXView.StartRow;
                    int totalRows = 0;
                    List <object> res;

                    using (new PXReadBranchRestrictedScope())
                    {
                        res             = outerview.Select(PXView.Currents, PXView.Parameters, PXView.Searches, PXView.SortColumns, PXView.Descendings, PXView.Filters, ref startRow, PXView.MaximumRows, ref totalRows);
                        PXView.StartRow = 0;
                    }

                    PXCache cache = outerview.Graph.Caches[typeof(INSite)];

                    return(res.FindAll((item) =>
                    {
                        return _RestrictedSelect.Meet(cache, item is PXResult ? PXResult.Unwrap <INSite>(item) : item);
                    }));
                });

                if (_DirtyRead)
                {
                    view.IsReadOnly = false;
                }
            }
Ejemplo n.º 20
0
        /// <summary> Get Current Value to Report Parameter </summary>
        public Dictionary <string, string> GetCurrentRowToParameter(bool isOutter = false)
        {
            var _CurrentRow = this.GetCacheCurrent <LumShipmentPlan>().Current;
            PXResultset <InventoryItem> data =
                SelectFrom <InventoryItem>
                .LeftJoin <INItemXRef> .On <INItemXRef.inventoryID.IsEqual <InventoryItem.inventoryID> >
                .LeftJoin <CSAnswers> .On <InventoryItem.noteID.IsEqual <CSAnswers.refNoteID> >
                .Where <InventoryItem.inventoryID.IsEqual <P.AsInt> > .View.Select(this, _CurrentRow.InventoryID);

            PXResult <AMProdItem, SOLine> soData =
                (PXResult <AMProdItem, SOLine>)SelectFrom <AMProdItem>
                .LeftJoin <SOLine> .On <AMProdItemExt.usrSOLineNbr.IsEqual <SOLine.lineNbr>
                                        .And <AMProdItemExt.usrSOOrderNbr.IsEqual <SOLine.orderNbr> >
                                        .And <AMProdItemExt.usrSOOrderType.IsEqual <SOLine.orderType> > >
                .Where <AMProdItem.prodOrdID.IsEqual <P.AsString> > .View.Select(this, _CurrentRow.ProdOrdID);

            var ENDCDescr = new PXGraph().Select <CSAttributeDetail>().Where(x => x.ValueID == _CurrentRow.Customer).FirstOrDefault()?.Description;

            ENDCDescr = ENDCDescr ?? _CurrentRow.Customer;

            Dictionary <string, string> parameters = new Dictionary <string, string>
            {
                ["ShipmentPlanID"] = _CurrentRow.ShipmentPlanID,
                ["ProdOrdID"]      = _CurrentRow.ProdOrdID,
                ["Customer"]       = ENDCDescr,
                ["CustomerPartNo"] = soData.GetItem <SOLine>()?.AlternateID,
                ["Description"]    = data.FirstOrDefault().GetItem <InventoryItem>().Descr,
                ["Resistor"]       = data.RowCast <CSAnswers>().Where(x => x.AttributeID == "RESISTOR").FirstOrDefault()?.Value,
                ["DATE"]           = _CurrentRow.PlannedShipDate?.ToString("yyyy/MM/dd")
            };

            return(parameters);
        }
Ejemplo n.º 21
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, InvoiceOrderDelegate baseMethod)
        {
            baseMethod(invoiceDate, order, details, customer, list);
            SOOrder       soorder = (SOOrder)order;
            SOOrderRUTROT orderRR = PXCache <SOOrder> .GetExtension <SOOrderRUTROT>(soorder);

            if (orderRR?.IsRUTROTDeductible == true && Base.Document.Current != null)
            {
                Base.Document.SetValueExt <ARInvoiceRUTROT.isRUTROTDeductible>(Base.Document.Current, true);
                Base.Document.Update(Base.Document.Current);

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

                rutrot                      = (RUTROT)Base.Rutrots.Cache.CreateCopy(rutrot);
                rutrot.DocType              = Base.Document.Current.DocType;
                rutrot.RefNbr               = Base.Document.Current.RefNbr;
                rutrot.CuryDistributedAmt   = 0m;
                rutrot.CuryUndistributedAmt = 0m;
                rutrot                      = Base.Rutrots.Update(rutrot);
                RecalcFormulas(rutrot, PXCache <ARInvoice> .GetExtension <ARInvoiceRUTROT>(Base.Document.Current));
                foreach (RUTROTDistribution rutrotDetail in PXSelect <RUTROTDistribution, Where <RUTROTDistribution.docType, Equal <Required <SOOrder.orderType> >,
                                                                                                 And <RUTROTDistribution.refNbr, Equal <Required <SOOrder.orderNbr> > > > > .Select(Base, soorder.OrderType, soorder.OrderNbr))
                {
                    RUTROTDistribution new_detail = (RUTROTDistribution)Base.RRDistribution.Cache.CreateCopy(rutrotDetail);
                    new_detail.RefNbr  = null;
                    new_detail.DocType = null;
                    Base.RRDistribution.Insert(new_detail);
                }

                Base.Save.Press();
            }
        }
        protected IEnumerable <TRefItem> RefItemsForAction(TInstance leaveInstance, ICollection <TInstance> deletingInstances, bool forDeleting)
        {
            // Constraint
            if (deletingInstances.Count < 1)
            {
                yield break;
            }

            // Compose command
            BqlCommand command = GetCommand(leaveInstance, deletingInstances, forDeleting);

            if (command == null)
            {
                yield break;
            }

            // Compose parameters
            object[] deletingIDs = GetInstancesKeys(leaveInstance, deletingInstances, forDeleting);

            // Select
            PXView view = new PXView(Graph, false, command);

            foreach (object item in view.SelectMulti(deletingIDs))
            {
                PXResult record = item as PXResult;
                if (record != null)
                {
                    yield return(record[typeof(TRefItem)] as TRefItem);
                }
                else
                {
                    yield return(item as TRefItem);
                }
            }
        }
Ejemplo n.º 23
0
    protected void PackGrid_RowDataBound(object sender, PX.Web.UI.PXGridRowEventArgs e)
    {
        var shipLine = (SOShipLineSplit)PXResult.UnwrapMain(e.Row.DataItem);

        if (shipLine == null)
        {
            return;
        }

        SOPickPackShipSetup setup = ((PX.Web.UI.PXGrid)sender).DataGraph.GetExtension <PickPackShip>().Setup.With(s => s.Current ?? s.Select());
        bool noPick = setup.ShowPickTab == false;

        if (shipLine.PickedQty > 0 && shipLine.PackedQty > (noPick ? shipLine.Qty : shipLine.PickedQty))
        {
            e.Row.Style.CssClass = PickCss.Overpick;
        }
        else if (shipLine.PickedQty > 0 && shipLine.PackedQty == (noPick ? shipLine.Qty : shipLine.PickedQty))
        {
            e.Row.Style.CssClass = PickCss.Complete;
        }
        else if (shipLine.PackedQty > 0)
        {
            e.Row.Style.CssClass = PickCss.Partial;
        }
    }
            protected override TaxDetail CalculateTaxSum(PXCache sender, object taxrow, object row)
            {
                TaxRev taxrev = PXResult.Unwrap <TaxRev>(taxrow);
                Tax    tax    = PXResult.Unwrap <Tax>(taxrow);
                bool   propagateCustomRate = false;
                var    origTaxRate         = taxrev.TaxRate;

                if (taxrev.TaxID != null && tax != null)
                {
                    SOTaxAmazonExt taxExt = tax.GetExtension <SOTaxAmazonExt>();
                    if (taxExt.UsrAMPropagateTaxAmt == true)
                    {
                        SOTaxTran soTax = PXResult <SOTaxTran> .Current;
                        if (soTax != null && taxrev.TaxID == soTax.TaxID && soTax.CuryTaxableAmt.GetValueOrDefault() > 0)
                        {
                            var taxRate = soTax.CuryTaxAmt / soTax.CuryTaxableAmt * 100;
                            if (taxRate != origTaxRate && taxRate > 0)
                            {
                                taxrev.TaxRate      = taxRate;
                                propagateCustomRate = true;
                            }
                        }
                    }
                }
                TaxDetail result = base.CalculateTaxSum(sender, taxrow, row);

                if (result != null && propagateCustomRate)
                {
                    result.TaxRate = origTaxRate;
                    taxrev.TaxRate = origTaxRate;
                }
                return(result);
            }
 public static Tuple <T0, T1, T2> ToTuple <T0, T1, T2>(this PXResult <T0, T1, T2> result)
     where T0 : class, IBqlTable, new()
     where T1 : class, IBqlTable, new()
     where T2 : class, IBqlTable, new()
 {
     return(Tuple.Create <T0, T1, T2>(result, result, result));
 }
Ejemplo n.º 26
0
        protected virtual IEnumerable Cancel(PXAdapter adapter)
        {
            BAccountLocation bAccountLocationRow = LocationRecords.Current;

            if (bAccountLocationRow != null && bAccountLocationRow.CustomerID != null &&
                adapter.Searches.Length == 2 && adapter.Searches[0] != null)
            {
                if (bAccountLocationRow.CustomerCD.Trim() != adapter.Searches[0].ToString().Trim())
                {
                    PXResult <BAccount, Location> BaccountLocationResultSet = (PXResult <BAccount, Location>)
                                                                              PXSelectJoin <BAccount,
                                                                                            InnerJoin <Location,
                                                                                                       On <
                                                                                                           Location.bAccountID, Equal <BAccount.bAccountID> > >,
                                                                                            Where <
                                                                                                BAccount.acctCD, Equal <Required <BAccount.acctCD> > > >
                                                                              .SelectWindowed(this, 0, 1, adapter.Searches[0]);

                    Location locationRow = BaccountLocationResultSet;

                    adapter.Searches[1] = locationRow.LocationCD;
                }
            }

            foreach (BAccountLocation loc in (new PXCancel <BAccountLocation>(this, "Cancel")).Press(adapter))
            {
                return(new object[] { loc });
            }

            return(new object[0]);
        }
Ejemplo n.º 27
0
        public static IEnumerable GetPMdetails(PXGraph graph, int?PMInstanceID, bool CCPIDCondition, bool OtherDetailsCondition)
        {
            var items = PXSelectJoin <CustomerPaymentMethodDetail, InnerJoin <PaymentMethodDetail, On <PaymentMethodDetail.paymentMethodID, Equal <CustomerPaymentMethodDetail.paymentMethodID>,
                                                                                                       And <PaymentMethodDetail.detailID, Equal <CustomerPaymentMethodDetail.detailID>,
                                                                                                            And <PaymentMethodDetail.useFor, Equal <PaymentMethodDetailUsage.useForARCards> > > > >,
                                      Where <CustomerPaymentMethodDetail.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .Select(graph, PMInstanceID);

            if (PMInstanceID > 0)
            {
                PXResult <CustomerPaymentMethodDetail, PaymentMethodDetail> stored = HasSavedPaymentProfile(items);
                if (stored != null)
                {
                    yield return(stored);

                    yield break;
                }
            }

            foreach (PXResult <CustomerPaymentMethodDetail, PaymentMethodDetail> item in items)
            {
                PaymentMethodDetail pmd = item;
                bool isCCPid            = pmd.IsCCProcessingID == true;
                if (CCPIDCondition && isCCPid ||
                    OtherDetailsCondition && !isCCPid)
                {
                    yield return(item);
                }
            }
        }
Ejemplo n.º 28
0
        public static CCProcessingCenter GetProcessingCenter(PXGraph graph, int?PMInstanceID, bool UsePMFromCacheDeleted)
        {
            if (PMInstanceID == null && !UsePMFromCacheDeleted)
            {
                return(null);
            }

            CCProcessingCenter processingCenter = null;

            if (PMInstanceID != null)
            {
                PXResult <CustomerPaymentMethod, CCProcessingCenter> res =
                    (PXResult <CustomerPaymentMethod, CCProcessingCenter>) PXSelectJoin <
                        CustomerPaymentMethod,
                        InnerJoin <CCProcessingCenter,
                                   On <CCProcessingCenter.processingCenterID, Equal <CustomerPaymentMethod.cCProcessingCenterID> > >,
                        Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > >
                    .Select(graph, PMInstanceID);

                processingCenter = (CCProcessingCenter)res;
            }

            if (processingCenter == null && UsePMFromCacheDeleted)
            {
                //assuming that payment method was just deleted
                IEnumerator cpmEnumerator = graph.Caches[typeof(CustomerPaymentMethod)].Deleted.GetEnumerator();
                if (cpmEnumerator.MoveNext())
                {
                    CustomerPaymentMethod customerPaymentMethod = (CustomerPaymentMethod)cpmEnumerator.Current;
                    processingCenter = GetProcessingCenter(graph, customerPaymentMethod.CCProcessingCenterID);
                }
            }

            return(processingCenter);
        }
Ejemplo n.º 29
0
        public virtual void CCTransactionsHistoryFilter_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
        {
            CCTransactionsHistoryFilter row    = (CCTransactionsHistoryFilter)e.Row;
            CCTransactionsHistoryFilter oldRow = (CCTransactionsHistoryFilter)e.OldRow;

            if (oldRow.PaymentMethodID != row.PaymentMethodID || oldRow.CardNumber != row.CardNumber || oldRow.PartialCardNumber != row.PartialCardNumber)
            {
                this.RecalcRow(row);
            }
            if (row.MaskedCardNumber != oldRow.MaskedCardNumber || row.DBSearchName != oldRow.DBSearchName)
            {
                PXResult <CustomerPaymentMethod> cnt = PXSelectJoinGroupBy <CustomerPaymentMethod, InnerJoin <Customer,
                                                                                                              On <Customer.bAccountID, Equal <CustomerPaymentMethod.bAccountID> > >,
                                                                            Where <CustomerPaymentMethod.paymentMethodID, Equal <Current <CCTransactionsHistoryFilter.paymentMethodID> >,
                                                                                   And <CustomerPaymentMethod.descr, Like <Optional <CCTransactionsHistoryFilter.maskedCardNumber> >,
                                                                                        And <Customer.acctName, Like <Optional <CCTransactionsHistoryFilter.dBSearchName> >,
                                                                                             And <CustomerPaymentMethod.isActive, Equal <True> > > > >,
                                                                            Aggregate <Count <CustomerPaymentMethod.pMInstanceID> > > .Select(this, row.MaskedCardNumber, row.DBSearchName);

                int count = 0;
                if (cnt != null && cnt.RowCount != null)
                {
                    count             = (int)cnt.RowCount;
                    row.NumberOfCards = cnt.RowCount;
                }
                row.PMInstanceID = count == 1 ? ((CustomerPaymentMethod)cnt).PMInstanceID : null;
            }
        }
Ejemplo n.º 30
0
        public override object Map(KCMapObjectRequest request)
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(request.Target))
            {
                PXResult <KCMapping> importMappingRow = _mappingMaint.ImportMappingRow.Select(request.EntityType, property.Name, request.ViewName).FirstOrDefault();
                if (importMappingRow == null)
                {
                    continue;
                }
                KCMapping mapping = importMappingRow.GetItem <KCMapping>();
                KCChannelAdvisorMappingField caField = importMappingRow.GetItem <KCChannelAdvisorMappingField>();
                string formula = mapping.RuleType == KCRuleTypesConstants.Expression
                              ? mapping.SourceExpression
                              : caField?.FieldName;

                IDictionary <string, object> mappingValue = GetMappingValue(request, property);
                if (string.IsNullOrWhiteSpace(formula) ||
                    mappingValue == null ||
                    (mapping.RuleType == KCRuleTypesConstants.Simple && mappingValue.GetValue(formula) == null))
                {
                    continue;
                }
                MapField(request.EntityType, request.Target, property, mappingValue, formula);
            }

            return(request.Target);
        }
Ejemplo n.º 31
0
		public virtual void InvoiceOrder(DateTime invoiceDate, PXResult<SOOrderShipment, SOOrder, CurrencyInfo, SOAddress, SOContact, SOOrderType> order, Customer customer, DocumentList<ARInvoice, SOInvoice> list)
		{
			InvoiceOrder(invoiceDate, order, null, customer, list);
		}
Ejemplo n.º 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);
		}