Beispiel #1
0
        protected virtual void INSite_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
        {
            if ((e.Operation & PXDBOperation.Command) == PXDBOperation.Delete)
            {
                return;
            }
            INSite site = e.Row as INSite;

            PX.SM.RelationGroup group = Group.Current;
            if (site != null && site.GroupMask != null && group != null && group.GroupMask != null)
            {
                if (site.GroupMask.Length < group.GroupMask.Length)
                {
                    byte[] mask = site.GroupMask;
                    Array.Resize <byte>(ref mask, group.GroupMask.Length);
                    site.GroupMask = mask;
                }
                for (int i = 0; i < group.GroupMask.Length; i++)
                {
                    if (group.GroupMask[i] == 0x00)
                    {
                        continue;
                    }
                    if (site.Included == true)
                    {
                        site.GroupMask[i] = (byte)(site.GroupMask[i] | group.GroupMask[i]);
                    }
                    else
                    {
                        site.GroupMask[i] = (byte)(site.GroupMask[i] & ~group.GroupMask[i]);
                    }
                }
            }
        }
Beispiel #2
0
        protected virtual void INTran_ToLocationID_FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
        {
            /// Needed for the posting of Transfer Orders via
            /// <see cref="SO.SOShipmentEntry.PostShipment(INIssueEntry, PXResult{SO.SOOrderShipment, SO.SOOrder}, DocumentList{INRegister}, AR.ARInvoice)"/>

            INTran row = (INTran)e.Row;

            if (row == null || row.DocType != INDocType.Transfer)
            {
                return;
            }

            INItemSite itemSite = PXSelect <INItemSite,
                                            Where <INItemSite.siteID, Equal <Required <INItemSite.siteID> >,
                                                   And <INItemSite.inventoryID, Equal <Required <INItemSite.inventoryID> > > > >
                                  .SelectWindowed(this, 0, 1, row.ToSiteID, row.InventoryID);

            if (itemSite != null)
            {
                e.NewValue = row.SiteID == row.ToSiteID ? itemSite.DfltShipLocationID : itemSite.DfltReceiptLocationID;
                e.Cancel   = true;
            }
            else
            {
                INSite site = (INSite)PXSelectorAttribute.Select <INTran.toSiteID>(sender, row);
                if (site != null)
                {
                    e.NewValue = row.SiteID == row.ToSiteID ? site.ShipLocationID : site.ReceiptLocationID;
                    e.Cancel   = true;
                }
            }
        }
        protected virtual void ProcessWarehouse(string barcode)
        {
            INSite site =
                SelectFrom <INSite>
                .Where <INSite.siteCD.IsEqual <@P.AsString> >
                .View.ReadOnly.Select(Base, barcode);

            if (site == null)
            {
                ReportError(Msg.WarehouseMissing, barcode);
            }
            else if (IsValid <Header.siteID>(site.SiteID, out string error) == false)
            {
                ReportError(error);
                return;
            }
            else
            {
                HeaderSetter.Set(h => h.SiteID, site.SiteID);

                Base.Filter.Cache.SetValueExt <InventorySummaryEnqFilter.siteID>(Base.Filter.Current, site.SiteID);
                Base.Filter.UpdateCurrent();

                SetScanState(ScanStates.Item, Msg.WarehouseReady, site.SiteCD);
            }
        }
        protected virtual void INTran_LocationID_FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
        {
            INTran row = (INTran)e.Row;

            if (row == null)
            {
                return;
            }

            INItemSite itemSite = itemsite.SelectWindowed(0, 1, row.SiteID, row.InventoryID);

            if (itemSite != null)
            {
                e.NewValue = itemSite.DfltReceiptLocationID;
                e.Cancel   = true;
            }
            else
            {
                INSite site = (INSite)PXSelectorAttribute.Select <INTran.siteID>(sender, row);
                if (site != null)
                {
                    e.NewValue = site.ReceiptLocationID;
                    e.Cancel   = true;
                }
            }
        }
Beispiel #5
0
        protected virtual void INItemClass_RowDeleting(PXCache sender, PXRowDeletingEventArgs e)
        {
            INSetup iNSetupRec = (INSetup)PXSelect <INSetup, Where <INSetup.dfltItemClassID, Equal <Current <INItemClass.itemClassID> > > > .SelectWindowed(this, 0, 1);

            if (iNSetupRec != null)
            {
                throw new PXException(Messages.ThisItemClassCanNotBeDeletedBecauseItIsUsedIn, "Inventory Setup");
            }

            InventoryItem inventoryItemRec = (InventoryItem)PXSelect <InventoryItem, Where <InventoryItem.itemClassID, Equal <Current <INItemClass.itemClassID> > > > .SelectWindowed(this, 0, 1);

            if (inventoryItemRec != null)
            {
                throw new PXException(Messages.ThisItemClassCanNotBeDeletedBecauseItIsUsedIn, "Inventory Item: " + inventoryItemRec.InventoryCD);
            }

            INLocation iNLocationRec = (INLocation)PXSelect <INLocation, Where <INLocation.primaryItemClassID, Equal <Current <INItemClass.itemClassID> > > > .SelectWindowed(this, 0, 1);

            if (iNLocationRec != null)
            {
                INSite iNSiteRec = (INSite)PXSelect <INSite, Where <INSite.siteID, Equal <Required <INSite.siteID> > > > .Select(this, iNLocationRec.SiteID);

                throw new PXException(Messages.ThisItemClassCanNotBeDeletedBecauseItIsUsedIn, "Warehouse/Location: " + (iNSiteRec.SiteCD ?? "") + "/" + iNLocationRec.LocationCD);
            }
        }
        public virtual void RevalueInventory(INUpdateStdCostRecord itemsite)
        {
            using (new PXConnectionScope())
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    if (je.adjustment.Current == null)
                    {
                        je.adjustment.Cache.Insert();
                    }

                    foreach (
                        PXResult <INCostStatus, InventoryItem, INSite, INPostClass, INItemSite> res in
                        incoststatus.View.SelectMultiBound(new object[] { itemsite }))
                    {
                        INCostStatus layer = res;
                        INSite       site  = res;
                        INTran       tran  = new INTran();

                        if (((INCostStatus)res).LayerType == INLayerType.Oversold)
                        {
                            tran.TranType = INTranType.NegativeCostAdjustment;
                        }
                        else
                        {
                            tran.TranType = INTranType.StandardCostAdjustment;
                        }
                        tran.BranchID   = site.BranchID;
                        tran.InvtAcctID = layer.AccountID;
                        tran.InvtSubID  = layer.SubID;
                        tran.AcctID     = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevAcctID>
                                              (je, (InventoryItem)res, (INSite)res, (INPostClass)res);
                        tran.SubID = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevSubID>
                                         (je, (InventoryItem)res, (INSite)res, (INPostClass)res);

                        tran.InventoryID = layer.InventoryID;
                        tran.SubItemID   = layer.CostSubItemID;
                        tran.SiteID      = layer.CostSiteID;
                        tran.Qty         = 0m;
                        tran.TranCost    = PXDBCurrencyAttribute.BaseRound(this, (decimal)(layer.QtyOnHand * itemsite.StdCost)) -
                                           layer.TotalCost;

                        je.transactions.Insert(tran);
                    }

                    if (je.transactions.Select().Count == 0)
                    {
                        je.Clear();
                    }
                    else
                    {
                        je.Save.Press();
                        PXProcessing <INUpdateStdCostRecord> .SetInfo(string.Format(Messages.AdjstmentCreated, je.adjustment.Current.RefNbr));
                    }

                    ts.Complete();
                }
            }
        }
Beispiel #7
0
        protected virtual void INSite_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            INSite site = e.Row as INSite;

            PX.SM.RelationGroup group = Group.Current;
            if (site != null && site.GroupMask != null && group != null && group.GroupMask != null &&
                sender.GetStatus(site) == PXEntryStatus.Notchanged)
            {
                for (int i = 0; i < site.GroupMask.Length && i < group.GroupMask.Length; i++)
                {
                    if (group.GroupMask[i] != 0x00 && (site.GroupMask[i] & group.GroupMask[i]) == group.GroupMask[i])
                    {
                        site.Included = true;
                    }
                }
            }
        }
        /// <summary>
        /// Validates that there are no Quantities on hand on any Project Locations for the given Warehouse.
        /// </summary>
        /// <param name="site">Warehouse</param>
        public virtual void ValidateProjectLocation(INSite site, InventoryItem item)
        {
            var select = new PXSelectJoin <INLocationStatus,
                                           InnerJoin <INLocation, On <INLocation.locationID, Equal <INLocationStatus.locationID> > >,
                                           Where <INLocation.siteID, Equal <Required <INLocation.siteID> >,
                                                  And <INLocation.isCosted, Equal <True>,
                                                       And <INLocation.taskID, IsNotNull,
                                                            And <INLocationStatus.inventoryID, Equal <Required <INLocationStatus.inventoryID> >,
                                                                 And <INLocationStatus.qtyOnHand, NotEqual <decimal0> > > > > > >(this);

            var res = select.SelectWindowed(0, 1, site.SiteID, item.InventoryID);

            if (res.Count == 1)
            {
                INLocation loc = (PXResult <INLocationStatus, INLocation>)res.First();

                throw new PXException(Messages.StandardCostItemOnProjectLocation, loc.LocationCD);
            }
        }
Beispiel #9
0
        protected virtual void INSetup_RowInserted(PXCache sender, PXRowInsertedEventArgs e)
        {
            var row = (INSetup)e.Row;

            if (row.TransitSiteID == null)
            {
                var    sitecache   = sites.Cache;
                INSite transitSite = (INSite)sitecache.CreateInstance();
                transitSite.BranchID           = row.TransitSiteID;
                transitSite.SiteCD             = "INTR";
                transitSite.Descr              = "Transit default warehouse";
                transitSite.OverrideInvtAccSub = true;
                sitecache.Current              = transitSite;
                transitSite = (INSite)sitecache.Insert(transitSite);

                row.TransitSiteID = transitSite.SiteID;
                sender.Update(row);
                PX.Common.PXContext.ClearSlot(typeof(SiteAttribute.Definition));
            }
        }
Beispiel #10
0
        protected virtual INTran PrepareTransaction(INCostStatus layer, INSite site, InventoryItem inventoryItem, decimal?tranCost)
        {
            try
            {
                ValidateProjectLocation(site, inventoryItem);
            }
            catch (PXException ex)
            {
                PXProcessing <INUpdateStdCostRecord> .SetError(ex.Message);

                return(null);
            }

            INTran tran = new INTran();

            if (layer.LayerType == INLayerType.Oversold)
            {
                tran.TranType = INTranType.NegativeCostAdjustment;
            }
            else
            {
                tran.TranType = INTranType.StandardCostAdjustment;
            }
            tran.BranchID   = site.BranchID;
            tran.InvtAcctID = layer.AccountID;
            tran.InvtSubID  = layer.SubID;
            var postClass = INPostClass.PK.Find(this, inventoryItem.PostClassID);

            tran.AcctID = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevAcctID>
                              (je, inventoryItem, site, postClass);
            tran.SubID = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevSubID>
                             (je, inventoryItem, site, postClass);

            tran.InventoryID = layer.InventoryID;
            tran.SubItemID   = layer.CostSubItemID;
            tran.SiteID      = layer.CostSiteID;
            tran.Qty         = 0m;
            tran.TranCost    = tranCost;
            return(tran);
        }
Beispiel #11
0
        protected virtual void ProcessWarehouse(string barcode)
        {
            INSite site =
                SelectFrom <INSite>
                .Where <INSite.siteCD.IsEqual <@P.AsString> >
                .View.ReadOnly.Select(Base, barcode);

            if (site == null)
            {
                ReportError(Msg.WarehouseMissing, barcode);
            }
            else if (IsValid <Header.siteID>(site.SiteID, out string error) == false)
            {
                ReportError(error);
                return;
            }
            else
            {
                HeaderSetter.Set(h => h.SiteID, site.SiteID);
                SetScanState(ScanStates.Location, Msg.WarehouseReady, site.SiteCD);
            }
        }
Beispiel #12
0
        protected virtual IEnumerable internalResultRecords()
        {
            InventoryTranHistEnqFilter filter = Filter.Current;

            bool summaryByDay      = filter.SummaryByDay ?? false;
            bool includeUnreleased = filter.IncludeUnreleased ?? false;

            var resultList = new List <PXResult <InventoryTranHistEnqResult, INTran, INTranSplit> >();

            if (filter.InventoryID == null)
            {
                PXDelegateResult emptyResult = new PXDelegateResult();
                emptyResult.IsResultFiltered  = true;
                emptyResult.IsResultSorted    = true;
                emptyResult.IsResultTruncated = true;

                return(emptyResult);                 //empty
            }

            PXSelectBase <INTranSplit> cmd = new PXSelectReadonly2 <INTranSplit,
                                                                    InnerJoin <INTran, On <INTranSplit.FK.Tran>,
                                                                               InnerJoin <INSubItem, On <INTranSplit.FK.SubItem>,
                                                                                          InnerJoin <INSite, On <INTran.FK.Site> > > >,
                                                                    Where <INTranSplit.inventoryID, Equal <Current <InventoryTranHistEnqFilter.inventoryID> >, And <Match <INSite, Current <AccessInfo.userName> > > >,
                                                                    OrderBy <Asc <INTranSplit.docType, Asc <INTranSplit.refNbr, Asc <INTranSplit.lineNbr, Asc <INTranSplit.splitLineNbr> > > > > >(this);

            PXSelectBase <INItemSiteHistByDay> cmdBegBalanceNew = new PXSelectReadonly2 <INItemSiteHistByDay,
                                                                                         InnerJoin <INItemSiteHistDay,
                                                                                                    On <INItemSiteHistDay.inventoryID, Equal <INItemSiteHistByDay.inventoryID>,
                                                                                                        And <INItemSiteHistDay.siteID, Equal <INItemSiteHistByDay.siteID>,
                                                                                                             And <INItemSiteHistDay.subItemID, Equal <INItemSiteHistByDay.subItemID>,
                                                                                                                  And <INItemSiteHistDay.locationID, Equal <INItemSiteHistByDay.locationID>,
                                                                                                                       And <INItemSiteHistDay.sDate, Equal <INItemSiteHistByDay.lastActivityDate> > > > > >,
                                                                                                    InnerJoin <INSubItem,
                                                                                                               On <INSubItem.subItemID, Equal <INItemSiteHistByDay.subItemID> >,
                                                                                                               InnerJoin <INSite, On <INSite.siteID, Equal <INItemSiteHistByDay.siteID> > > > >,
                                                                                         Where <INItemSiteHistByDay.inventoryID, Equal <Current <InventoryTranHistEnqFilter.inventoryID> >,
                                                                                                And <INItemSiteHistByDay.date, Equal <Required <INItemSiteHistByDay.date> >,
                                                                                                     And <Match <INSite, Current <AccessInfo.userName> > > > > >(this);

            if (!SubCDUtils.IsSubCDEmpty(filter.SubItemCD) && PXAccess.FeatureInstalled <FeaturesSet.subItem>())
            {
                cmd.WhereAnd <Where <INSubItem.subItemCD, Like <Current <InventoryTranHistEnqFilter.subItemCDWildcard> > > >();
                cmdBegBalanceNew.WhereAnd <Where <INSubItem.subItemCD, Like <Current <InventoryTranHistEnqFilter.subItemCDWildcard> > > >();
            }

            if (filter.SiteID != null && PXAccess.FeatureInstalled <FeaturesSet.warehouse>())
            {
                cmd.WhereAnd <Where <INTranSplit.siteID, Equal <Current <InventoryTranHistEnqFilter.siteID> > > >();
                cmdBegBalanceNew.WhereAnd <Where <INItemSiteHistByDay.siteID, Equal <Current <InventoryTranHistEnqFilter.siteID> > > >();
            }

            if ((filter.LocationID ?? -1) != -1 && PXAccess.FeatureInstalled <FeaturesSet.warehouseLocation>())        // there are cases when filter.LocationID = -1
            {
                cmd.WhereAnd <Where <INTranSplit.locationID, Equal <Current <InventoryTranHistEnqFilter.locationID> > > >();
                cmdBegBalanceNew.WhereAnd <Where <INItemSiteHistByDay.locationID, Equal <Current <InventoryTranHistEnqFilter.locationID> > > >();
            }

            if ((filter.LotSerialNbr ?? "") != "" && PXAccess.FeatureInstalled <FeaturesSet.lotSerialTracking>())
            {
                cmd.WhereAnd <Where <INTranSplit.lotSerialNbr, Like <Current <InventoryTranHistEnqFilter.lotSerialNbrWildcard> > > >();
            }

            if (!includeUnreleased)
            {
                cmd.WhereAnd <Where <INTranSplit.released, Equal <True> > >();
            }

            decimal cumulativeQty = 0m;

            if (filter.StartDate != null)
            {
                foreach (PXResult <INItemSiteHistByDay, INItemSiteHistDay> res in cmdBegBalanceNew.Select(filter.StartDate))
                {
                    INItemSiteHistByDay byday = res;
                    INItemSiteHistDay   hist  = res;

                    cumulativeQty +=
                        ((byday.LastActivityDate != null && byday.Date != null &&
                          byday.Date.Value.Date == byday.LastActivityDate.Value.Date)
                                            ? hist.BegQty
                                            : hist.EndQty) ?? 0m;
                }

                if (includeUnreleased)
                {
                    INSite site = INSite.PK.Find(this, filter.SiteID);

                    int calendarOrganizationID = PXAccess.GetParentOrganizationID(site?.BranchID) ?? FinPeriod.organizationID.MasterValue;

                    string   TranPeriodID;
                    DateTime?PeriodStartDate;

                    try
                    {
                        TranPeriodID    = FinPeriodRepository.GetPeriodIDFromDate(filter.StartDate, calendarOrganizationID);
                        PeriodStartDate = FinPeriodRepository.PeriodStartDate(TranPeriodID, calendarOrganizationID);
                    }
                    catch (PXFinPeriodException)
                    {
                        TranPeriodID    = null;
                        PeriodStartDate = filter.StartDate;
                    }

                    PXSelectBase <OrganizationFinPeriod> periodCmd =
                        new PXSelectGroupBy <OrganizationFinPeriod,
                                             Where <OrganizationFinPeriod.finPeriodID, LessEqual <Required <OrganizationFinPeriod.finPeriodID> >,
                                                    And <OrganizationFinPeriod.iNClosed, Equal <False>,
                                                         Or <OrganizationFinPeriod.finPeriodID, Equal <Required <OrganizationFinPeriod.finPeriodID> > > > >,
                                             Aggregate <GroupBy <OrganizationFinPeriod.finPeriodID> >,
                                             OrderBy <Asc <OrganizationFinPeriod.finPeriodID> > >(this);

                    List <object> periodCmdParams = new List <object>()
                    {
                        TranPeriodID, TranPeriodID
                    };


                    if (calendarOrganizationID != FinPeriod.organizationID.MasterValue)
                    {
                        periodCmd.WhereAnd <Where <OrganizationFinPeriod.organizationID, Equal <Required <OrganizationFinPeriod.organizationID> > > >();

                        periodCmdParams.Add(calendarOrganizationID);
                    }

                    OrganizationFinPeriod firstOpenOrCurrentClosedPeriod = periodCmd.SelectWindowed(0, 1, periodCmdParams.ToArray());

                    if (firstOpenOrCurrentClosedPeriod != null)
                    {
                        TranPeriodID    = firstOpenOrCurrentClosedPeriod.FinPeriodID;
                        PeriodStartDate = FinPeriodRepository.PeriodStartDate(firstOpenOrCurrentClosedPeriod.FinPeriodID, calendarOrganizationID);

                        PXView v2 = new PXView(this, true, cmd.View.BqlSelect
                                               .WhereAnd <Where <INTranSplit.tranDate, GreaterEqual <Required <INTranSplit.tranDate> > > >()
                                               .WhereAnd <Where <INTranSplit.tranDate, Less <Required <INTranSplit.tranDate> > > >()
                                               .WhereAnd <Where <INTranSplit.released, Equal <False> > >()
                                               .AggregateNew <Aggregate <
                                                                  GroupBy <INTranSplit.inventoryID, GroupBy <INTranSplit.invtMult, Sum <INTranSplit.baseQty> > > > >());

                        int splitStartRow  = 0;
                        int splitTotalRows = 0;

                        foreach (PXResult <INTranSplit> res in v2.Select(new object[0], new object[] { PeriodStartDate, filter.StartDate.Value }, new object[0],
                                                                         new string[0], new bool[0], new PXFilterRow[0], ref splitStartRow, 0, ref splitTotalRows))
                        {
                            INTranSplit tsRec = res;
                            cumulativeQty += (tsRec.InvtMult * tsRec.BaseQty) ?? 0m;
                        }
                    }
                }
            }

            if (filter.StartDate != null)
            {
                cmd.WhereAnd <Where <INTranSplit.tranDate, GreaterEqual <Current <InventoryTranHistEnqFilter.startDate> > > >();
            }

            if (filter.EndDate != null)
            {
                cmd.WhereAnd <Where <INTranSplit.tranDate, LessEqual <Current <InventoryTranHistEnqFilter.endDate> > > >();
            }

            AlterSortsAndFilters(out string[] newSortColumns, out bool[] newDescendings, out bool sortsChanged, out PXFilterRow[] newFilters, out bool filtersChanged);

            //if user clicks last, sorts will be inverted
            //as it is not possible to calculate beginning balance from the end
            //we will select without top from the start and then apply reverse order and select top n records
            //for next page we will ommit startrow to set beginning balance correctly
            //top (n, m) will be set in the outer search results since we do not reset PXView.StartRow to 0
            //Also, user can set a filter or sort by a column from result DAC (sortsChanged = true, filtersChanged = true) and need to get full result set.
            int  startRow           = 0;
            bool allowSelectWithTop = !sortsChanged && !filtersChanged && !PXView.ReverseOrder;
            int  maximumRows        = allowSelectWithTop ? PXView.StartRow + PXView.MaximumRows : 0;
            int  totalRows          = 0;

            PXView selectView = !summaryByDay
                            ? cmd.View
                            : new PXView(this, true,
                                         cmd.View.BqlSelect
                                         .AggregateNew <Aggregate <GroupBy <INTranSplit.tranDate, Sum <INTranSplit.qtyIn, Sum <INTranSplit.qtyOut> > > > >());

            List <object> intermediateResult = selectView.Select(PXView.Currents, new object[] { filter.StartDate },
                                                                 new string[newSortColumns.Length], newSortColumns, newDescendings, newFilters, ref startRow, maximumRows,
                                                                 ref totalRows);

            int gridLineNbr = 0;

            foreach (PXResult <INTranSplit, INTran, INSubItem> it in intermediateResult)
            {
                INTranSplit ts_rec = (INTranSplit)it;
                INTran      t_rec  = (INTran)it;

                if (summaryByDay)
                {
                    InventoryTranHistEnqResult item = new InventoryTranHistEnqResult();
                    item.BegQty      = cumulativeQty;
                    item.TranDate    = ts_rec.TranDate;
                    item.QtyIn       = ts_rec.QtyIn;
                    item.QtyOut      = ts_rec.QtyOut;
                    item.EndQty      = item.BegQty + ts_rec.QtyIn - ts_rec.QtyOut;
                    item.GridLineNbr = ++gridLineNbr;
                    resultList.Add(new PXResult <InventoryTranHistEnqResult, INTran, INTranSplit>(item, null, null));
                    cumulativeQty += (ts_rec.QtyIn - ts_rec.QtyOut) ?? 0m;
                }
                else
                {
                    InventoryTranHistEnqResult item = new InventoryTranHistEnqResult();
                    item.BegQty   = cumulativeQty;
                    item.TranDate = ts_rec.TranDate;
                    item.QtyIn    = ts_rec.QtyIn;
                    item.QtyOut   = ts_rec.QtyOut;
                    item.EndQty   = item.BegQty + ts_rec.QtyIn - ts_rec.QtyOut;

                    item.DocType      = ts_rec.DocType;
                    item.RefNbr       = ts_rec.RefNbr;
                    item.LineNbr      = ts_rec.LineNbr;
                    item.SplitLineNbr = ts_rec.SplitLineNbr;
                    item.GridLineNbr  = ++gridLineNbr;

                    decimal?unitcost;
                    if (filter.ShowAdjUnitCost ?? false)
                    {
                        unitcost = ts_rec.TotalQty != null && ts_rec.TotalQty != 0m ? (ts_rec.TotalCost + ts_rec.AdditionalCost) / ts_rec.TotalQty : 0m;
                    }
                    else
                    {
                        unitcost = ts_rec.TotalQty != null && ts_rec.TotalQty != 0m ? ts_rec.TotalCost / ts_rec.TotalQty : 0m;
                    }

                    item.UnitCost = unitcost;
                    resultList.Add(new PXResult <InventoryTranHistEnqResult, INTran, INTranSplit>(item, t_rec, ts_rec));
                    cumulativeQty += (ts_rec.InvtMult * ts_rec.BaseQty) ?? 0m;
                }
            }


            PXDelegateResult delegateResult = new PXDelegateResult();

            delegateResult.IsResultFiltered  = !filtersChanged;
            delegateResult.IsResultSorted    = !sortsChanged;
            delegateResult.IsResultTruncated = totalRows > resultList.Count;

            if (!PXView.ReverseOrder)
            {
                delegateResult.AddRange(resultList);
            }
            else
            {
                var sortedList = PXView.Sort(resultList);
                delegateResult.AddRange(sortedList.Cast <PXResult <InventoryTranHistEnqResult, INTran, INTranSplit> >());
                delegateResult.IsResultSorted = true;
            }

            return(delegateResult);
        }
        protected virtual IEnumerable internalResultRecords()
        {
            InventoryTranHistEnqFilter filter = Filter.Current;

            bool summaryByDay      = filter.SummaryByDay ?? false;
            bool includeUnreleased = filter.IncludeUnreleased ?? false;

            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.inventoryID>(ResultRecords.Cache, null, false);
            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.finPerNbr>(ResultRecords.Cache, null, false);  //???
            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.tranPerNbr>(ResultRecords.Cache, null, false); //???


            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.tranType>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.docRefNbr>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.subItemID>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.siteID>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.locationID>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranHistEnqResult.lotSerialNbr>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible(Tran.Cache, null, !summaryByDay);

            var resultList = new List <PXResult <InventoryTranHistEnqResult, INTran> >();

            if (filter.InventoryID == null)
            {
                return(resultList);  //empty
            }

            PXSelectBase <INTranSplit> cmd = new PXSelectReadonly2 <INTranSplit,
                                                                    InnerJoin <INTran,
                                                                               On <INTran.docType, Equal <INTranSplit.docType>,
                                                                                   And <INTran.refNbr, Equal <INTranSplit.refNbr>,
                                                                                        And <INTran.lineNbr, Equal <INTranSplit.lineNbr> > > >,
                                                                               InnerJoin <INSubItem,
                                                                                          On <INSubItem.subItemID, Equal <INTranSplit.subItemID> >,
                                                                                          InnerJoin <INSite, On <INSite.siteID, Equal <INTran.siteID> > > > >,
                                                                    Where <INTranSplit.inventoryID, Equal <Current <InventoryTranHistEnqFilter.inventoryID> >, And <Match <INSite, Current <AccessInfo.userName> > > >,
                                                                    OrderBy <Asc <INTranSplit.docType, Asc <INTranSplit.refNbr, Asc <INTranSplit.lineNbr, Asc <INTranSplit.splitLineNbr> > > > > >(this);

            PXSelectBase <INItemSiteHistByPeriod> cmdBegBalance = new PXSelectReadonly2 <INItemSiteHistByPeriod,
                                                                                         InnerJoin <INItemSiteHist,
                                                                                                    On <INItemSiteHist.inventoryID, Equal <INItemSiteHistByPeriod.inventoryID>,
                                                                                                        And <INItemSiteHist.siteID, Equal <INItemSiteHistByPeriod.siteID>,
                                                                                                             And <INItemSiteHist.subItemID, Equal <INItemSiteHistByPeriod.subItemID>,
                                                                                                                  And <INItemSiteHist.locationID, Equal <INItemSiteHistByPeriod.locationID>,
                                                                                                                       And <INItemSiteHist.finPeriodID, Equal <INItemSiteHistByPeriod.lastActivityPeriod> > > > > >,
                                                                                                    InnerJoin <INSubItem,
                                                                                                               On <INSubItem.subItemID, Equal <INItemSiteHistByPeriod.subItemID> >,
                                                                                                               InnerJoin <INSite, On <INSite.siteID, Equal <INItemSiteHistByPeriod.siteID> > > > >,
                                                                                         Where <INItemSiteHistByPeriod.inventoryID, Equal <Current <InventoryTranHistEnqFilter.inventoryID> >,
                                                                                                And <INItemSiteHistByPeriod.finPeriodID, Equal <Required <INItemSiteHistByPeriod.finPeriodID> >,
                                                                                                     And <Match <INSite, Current <AccessInfo.userName> > > > > >(this);

            if (!SubCDUtils.IsSubCDEmpty(filter.SubItemCD) && PXAccess.FeatureInstalled <FeaturesSet.subItem>())
            {
                cmdBegBalance.WhereAnd <Where <INSubItem.subItemCD, Like <Current <InventoryTranHistEnqFilter.subItemCDWildcard> > > >();
                cmd.WhereAnd <Where <INSubItem.subItemCD, Like <Current <InventoryTranHistEnqFilter.subItemCDWildcard> > > >();
            }

            if (filter.SiteID != null && PXAccess.FeatureInstalled <FeaturesSet.warehouse>())
            {
                cmdBegBalance.WhereAnd <Where <INItemSiteHistByPeriod.siteID, Equal <Current <InventoryTranHistEnqFilter.siteID> > > >();
                cmd.WhereAnd <Where <INTranSplit.siteID, Equal <Current <InventoryTranHistEnqFilter.siteID> > > >();
            }

            if ((filter.LocationID ?? -1) != -1 && PXAccess.FeatureInstalled <FeaturesSet.warehouseLocation>()) // there are cases when filter.LocationID = -1
            {
                cmdBegBalance.WhereAnd <Where <INItemSiteHistByPeriod.locationID, Equal <Current <InventoryTranHistEnqFilter.locationID> > > >();
                cmd.WhereAnd <Where <INTranSplit.locationID, Equal <Current <InventoryTranHistEnqFilter.locationID> > > >();
            }

            if ((filter.LotSerialNbr ?? "") != "" && PXAccess.FeatureInstalled <FeaturesSet.lotSerialTracking>())
            {
                cmd.WhereAnd <Where <INTranSplit.lotSerialNbr, Like <Current <InventoryTranHistEnqFilter.lotSerialNbrWildcard> > > >();
            }

            if (!includeUnreleased)
            {
                cmd.WhereAnd <Where <INTranSplit.released, Equal <True> > >();
            }

            decimal  cumulativeQty = 0m;
            string   TranPeriodID;
            DateTime?PeriodStartDate;
            bool     AnyPeriod = false;

            INSite site = PXSelect <INSite, Where <INSite.siteID, Equal <Required <INSite.siteID> > > > .Select(this, filter.SiteID);

            int calendarOrganizationID = PXAccess.GetParentOrganizationID(site?.BranchID) ?? FinPeriod.organizationID.MasterValue;

            try
            {
                TranPeriodID    = FinPeriodRepository.GetPeriodIDFromDate(filter.StartDate, calendarOrganizationID);
                PeriodStartDate = FinPeriodRepository.PeriodStartDate(TranPeriodID, calendarOrganizationID);
            }
            catch (PXFinPeriodException)
            {
                TranPeriodID    = null;
                PeriodStartDate = filter.StartDate;
            }

            int startRow    = 0;
            int totalRows   = 0;
            int maximumRows = 0;

            if (includeUnreleased)
            {
                PXSelectBase <OrganizationFinPeriod> periodCmd =
                    new PXSelectGroupBy <OrganizationFinPeriod,
                                         Where <OrganizationFinPeriod.finPeriodID, LessEqual <Required <OrganizationFinPeriod.finPeriodID> >,
                                                And <OrganizationFinPeriod.iNClosed, Equal <False>,
                                                     Or <OrganizationFinPeriod.finPeriodID, Equal <Required <OrganizationFinPeriod.finPeriodID> > > > >,
                                         Aggregate <GroupBy <OrganizationFinPeriod.finPeriodID> >,
                                         OrderBy <Asc <OrganizationFinPeriod.finPeriodID> > >(this);

                List <object> periodCmdParams = new List <object>()
                {
                    TranPeriodID, TranPeriodID
                };


                if (calendarOrganizationID != FinPeriod.organizationID.MasterValue)
                {
                    periodCmd.WhereAnd <Where <OrganizationFinPeriod.organizationID, Equal <Required <OrganizationFinPeriod.organizationID> > > >();

                    periodCmdParams.Add(calendarOrganizationID);
                }

                OrganizationFinPeriod firstOpenOrCurrentClosedPeriod = periodCmd.SelectWindowed(0, 1, periodCmdParams.ToArray());

                if (firstOpenOrCurrentClosedPeriod != null)
                {
                    TranPeriodID    = firstOpenOrCurrentClosedPeriod.FinPeriodID;
                    PeriodStartDate = FinPeriodRepository.PeriodStartDate(firstOpenOrCurrentClosedPeriod.FinPeriodID, calendarOrganizationID);
                }

                foreach (PXResult <INItemSiteHistByPeriod, INItemSiteHist> res in cmdBegBalance.Select(TranPeriodID))
                {
                    INItemSiteHistByPeriod byperiod = res;
                    INItemSiteHist         hist     = res;

                    cumulativeQty += string.Equals(byperiod.FinPeriodID, byperiod.LastActivityPeriod) ? (decimal)hist.TranBegQty : (decimal)hist.TranYtdQty;
                    AnyPeriod      = true;
                }

                if (AnyPeriod)
                {
                    //if StartDate is not on the Period border, make additional select with grouping
                    if (PeriodStartDate != filter.StartDate)
                    {
                        PXView v2 = new PXView(this, true, cmd.View.BqlSelect
                                               .WhereAnd <Where <INTranSplit.tranDate, GreaterEqual <Required <INTranSplit.tranDate> > > >()
                                               .WhereAnd <Where <INTranSplit.tranDate, Less <Required <INTranSplit.tranDate> > > >()
                                               .AggregateNew <Aggregate <GroupBy <INTranSplit.inventoryID, GroupBy <INTranSplit.invtMult, Sum <INTranSplit.baseQty> > > > >());

                        foreach (PXResult <INTranSplit> res in v2.Select(new object[0], new object[] { PeriodStartDate, filter.StartDate }, new object[0], new string[0], new bool[0], new PXFilterRow[0], ref startRow, 0, ref totalRows))
                        {
                            INTranSplit ts_rec = res;
                            cumulativeQty += (ts_rec.InvtMult * ts_rec.BaseQty) ?? 0m;
                        }
                    }
                }
                else
                {
                    PXView v2 = new PXView(this, true, cmd.View.BqlSelect
                                           .WhereAnd <Where <INTranSplit.tranDate, Less <Required <INTranSplit.tranDate> > > >()
                                           .AggregateNew <Aggregate <GroupBy <INTranSplit.inventoryID, GroupBy <INTranSplit.invtMult, Sum <INTranSplit.baseQty> > > > >());

                    foreach (PXResult <INTranSplit> res in v2.Select(new object[0], new object[] { filter.StartDate }, new object[0], new string[0], new bool[0], new PXFilterRow[0], ref startRow, 0, ref totalRows))
                    {
                        INTranSplit ts_rec = res;
                        cumulativeQty += (ts_rec.InvtMult * ts_rec.BaseQty) ?? 0m;
                    }
                }
            }
            else
            {
                foreach (PXResult <INItemSiteHistByPeriod, INItemSiteHist> res in cmdBegBalance.Select(TranPeriodID))
                {
                    INItemSiteHistByPeriod byperiod = res;
                    INItemSiteHist         hist     = res;

                    cumulativeQty += string.Equals(byperiod.FinPeriodID, byperiod.LastActivityPeriod) ? (decimal)hist.TranBegQty : (decimal)hist.TranYtdQty;
                    AnyPeriod      = true;
                }

                if (AnyPeriod)
                {
                    //if StartDate is not on the Period border, make additional select with grouping
                    if (PeriodStartDate != filter.StartDate)
                    {
                        PXView v2 = new PXView(this, true, cmd.View.BqlSelect
                                               .WhereAnd <Where <INTranSplit.tranDate, GreaterEqual <Required <INTranSplit.tranDate> > > >()
                                               .WhereAnd <Where <INTranSplit.tranDate, Less <Required <INTranSplit.tranDate> > > >()
                                               .AggregateNew <Aggregate <GroupBy <INTranSplit.inventoryID, GroupBy <INTranSplit.invtMult, Sum <INTranSplit.baseQty> > > > >());

                        foreach (PXResult <INTranSplit> res in v2.Select(new object[0], new object[] { PeriodStartDate, filter.StartDate }, new object[0], new string[0], new bool[0], new PXFilterRow[0], ref startRow, 0, ref totalRows))
                        {
                            INTranSplit ts_rec = res;
                            cumulativeQty += (ts_rec.InvtMult * ts_rec.BaseQty) ?? 0m;
                        }
                    }
                }
            }

            if (filter.StartDate != null)
            {
                cmd.WhereAnd <Where <INTranSplit.tranDate, GreaterEqual <Current <InventoryTranHistEnqFilter.startDate> > > >();
            }

            if (filter.EndDate != null)
            {
                cmd.WhereAnd <Where <INTranSplit.tranDate, LessEqual <Current <InventoryTranHistEnqFilter.endDate> > > >();
            }

            string[] newSortColumns;
            bool[]   newDescendings;
            AlterSorts(out newSortColumns, out newDescendings);
            PXFilterRow[] newFilters = AlterFilters();

            //if user clicks last, sorts will be inverted
            //as it is not possible to calculate beginning balance from the end
            //we will select without top from the start and then apply reverse order and select top n records
            //for next page we will ommit startrow to set beginning balance correctly
            //top (n, m) will be set in the outer search results since we do not reset PXView.StartRow to 0
            startRow    = 0;
            maximumRows = !PXView.ReverseOrder ? PXView.StartRow + PXView.MaximumRows : 0;
            totalRows   = 0;

            PXView selectView = !summaryByDay ? cmd.View
                                : new PXView(this, true, cmd.View.BqlSelect.AggregateNew <Aggregate <GroupBy <INTranSplit.tranDate, Sum <INTranSplit.qtyIn, Sum <INTranSplit.qtyOut> > > > >());

            List <object> intermediateResult = selectView.Select(PXView.Currents, new object[] { filter.StartDate }, new string[newSortColumns.Length], newSortColumns, PXView.Descendings, newFilters, ref startRow, maximumRows, ref totalRows);

            int gridLineNbr = 0;

            foreach (PXResult <INTranSplit, INTran, INSubItem> it in intermediateResult)
            {
                INTranSplit ts_rec = (INTranSplit)it;
                INTran      t_rec  = (INTran)it;

                if (ts_rec.TranDate < filter.StartDate)
                {
                    cumulativeQty += (ts_rec.InvtMult * ts_rec.BaseQty) ?? 0m;
                }
                else
                {
                    if (summaryByDay)
                    {
                        InventoryTranHistEnqResult item = new InventoryTranHistEnqResult();
                        item.BegQty      = cumulativeQty;
                        item.TranDate    = ts_rec.TranDate;
                        item.QtyIn       = ts_rec.QtyIn;
                        item.QtyOut      = ts_rec.QtyOut;
                        item.EndQty      = item.BegQty + ts_rec.QtyIn - ts_rec.QtyOut;
                        item.GridLineNbr = ++gridLineNbr;
                        resultList.Add(new PXResult <InventoryTranHistEnqResult, INTran>(item, null));
                        cumulativeQty += (ts_rec.QtyIn - ts_rec.QtyOut) ?? 0m;
                    }
                    else
                    {
                        InventoryTranHistEnqResult item = new InventoryTranHistEnqResult();
                        item.BegQty   = cumulativeQty;
                        item.TranDate = ts_rec.TranDate;
                        item.QtyIn    = ts_rec.QtyIn;
                        item.QtyOut   = ts_rec.QtyOut;
                        item.EndQty   = item.BegQty + ts_rec.QtyIn - ts_rec.QtyOut;

                        item.InventoryID  = ts_rec.InventoryID;
                        item.TranType     = ts_rec.TranType;
                        item.DocType      = ts_rec.DocType;
                        item.DocRefNbr    = ts_rec.RefNbr;
                        item.SubItemID    = ts_rec.SubItemID;
                        item.SiteID       = ts_rec.SiteID;
                        item.LocationID   = ts_rec.LocationID;
                        item.LotSerialNbr = ts_rec.LotSerialNbr;
                        item.FinPerNbr    = t_rec.FinPeriodID;
                        item.TranPerNbr   = t_rec.TranPeriodID;
                        item.Released     = t_rec.Released;
                        item.GridLineNbr  = ++gridLineNbr;

                        decimal?unitcost;
                        if (filter.ShowAdjUnitCost ?? false)
                        {
                            unitcost = ts_rec.TotalQty != null && ts_rec.TotalQty != 0m ? (ts_rec.TotalCost + ts_rec.AdditionalCost) / ts_rec.TotalQty : 0m;
                        }
                        else
                        {
                            unitcost = ts_rec.TotalQty != null && ts_rec.TotalQty != 0m ? ts_rec.TotalCost / ts_rec.TotalQty : 0m;
                        }

                        item.UnitCost = unitcost;
                        resultList.Add(new PXResult <InventoryTranHistEnqResult, INTran>(item, t_rec));
                        cumulativeQty += (ts_rec.InvtMult * ts_rec.BaseQty) ?? 0m;
                    }
                }
            }
            if (!PXView.ReverseOrder)
            {
                return(resultList);
            }
            return(PXView.Sort(resultList));
        }
        protected virtual IEnumerable internalResultRecords()
        {
            const bool useItemCostHistoryToOptimizeBalanceCalculation = true;             // false to debug and ensure that INItemCostHistory corresponds to INCostTran

            InventoryTranByAcctEnqFilter filter = Filter.Current;

            bool summaryByDay = filter.SummaryByDay ?? false;

            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.tranType>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.docRefNbr>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.subItemCD>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.siteID>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.locationID>(ResultRecords.Cache, null, !summaryByDay);

            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.accountID>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.subID>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.inventoryID>(ResultRecords.Cache, null, !summaryByDay);

            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.costAdj>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.finPerNbr>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.tranPerNbr>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.qty>(ResultRecords.Cache, null, !summaryByDay);
            PXUIFieldAttribute.SetVisible <InventoryTranByAcctEnqResult.unitCost>(ResultRecords.Cache, null, !summaryByDay);

            PXUIFieldAttribute.SetVisible(Tran.Cache, null, !summaryByDay);

            var resultList = new List <PXResult <InventoryTranByAcctEnqResult, INTran> >();

            decimal cumulativeBalance = 0m;

            if (filter.AccountID == null)
            {
                return(resultList);                 //empty
            }

            if (filter.FinPeriodID == null)
            {
                return(resultList);                 //empty
            }

            if (useItemCostHistoryToOptimizeBalanceCalculation)
            {
                PXSelectBase <INItemCostHist> cmd_CostHist = new PXSelectJoinGroupBy <INItemCostHist,

                                                                                      InnerJoin <Sub,
                                                                                                 On <Sub.subID, Equal <INItemCostHist.subID> > >,

                                                                                      Where <INItemCostHist.finPeriodID, Less <Current <InventoryTranByAcctEnqFilter.finPeriodID> > >,

                                                                                      Aggregate <
                                                                                          Sum <INItemCostHist.tranYtdCost,
                                                                                               Sum <INItemCostHist.tranBegCost,
                                                                                                    Sum <INItemCostHist.finYtdCost,
                                                                                                         Sum <INItemCostHist.finBegCost> > > > > >(this);

                //if (filter.AccountID != null) // checked above
                {
                    cmd_CostHist.WhereAnd <Where <INItemCostHist.accountID, Equal <Current <InventoryTranByAcctEnqFilter.accountID> > > >();
                }

                if (!SubCDUtils.IsSubCDEmpty(filter.SubCD))
                {
                    cmd_CostHist.WhereAnd <Where <Sub.subCD, Like <Current <InventoryTranByAcctEnqFilter.subCDWildcard> > > >();
                }

                PXResultset <INItemCostHist> costHistResult = (PXResultset <INItemCostHist>)cmd_CostHist.Select();
                if (costHistResult.Count == 1)                 // 0 is possible too
                {
                    if (filter.ByFinancialPeriod == true)
                    {
                        cumulativeBalance += (((INItemCostHist)costHistResult[0]).FinYtdCost ?? 0m) - (((INItemCostHist)costHistResult[0]).FinBegCost ?? 0m);
                    }
                    else
                    {
                        cumulativeBalance += (((INItemCostHist)costHistResult[0]).TranYtdCost ?? 0m) - (((INItemCostHist)costHistResult[0]).TranBegCost ?? 0m);
                    }
                }
            }

            PXSelectBase <INTranCost> cmd = new PXSelectReadonly2 <INTranCost,
                                                                   InnerJoin <INTran,
                                                                              On <INTran.tranType, Equal <INTranCost.tranType>,
                                                                                  And <INTran.refNbr, Equal <INTranCost.refNbr>,
                                                                                       And <INTran.lineNbr, Equal <INTranCost.lineNbr> > > >,
                                                                              InnerJoin <InventoryItem, On <InventoryItem.inventoryID, Equal <INTranCost.inventoryID>,
                                                                                                            And <Match <InventoryItem, Current <AccessInfo.userName> > > >,
                                                                                         InnerJoin <Sub, On <Sub.subID, Equal <INTranCost.invtSubID> >,
                                                                                                    InnerJoin <INSubItem, On <INSubItem.subItemID, Equal <INTranCost.costSubItemID> >,
                                                                                                               LeftJoin <INSite, On <INSite.siteID, Equal <INTranCost.costSiteID> >,
                                                                                                                         LeftJoin <INLocation, On <INLocation.locationID, Equal <INTranCost.costSiteID> >,
                                                                                                                                   LeftJoin <INCostStatus, On <INTranCost.costID, Equal <INCostStatus.costID> > > > > > > > >,
                                                                   Where <INSite.siteID, IsNull,
                                                                          Or <Match <INSite, Current <AccessInfo.userName> > > >,
                                                                   OrderBy <Asc <INTranCost.tranDate,
                                                                                 Asc <INTranCost.createdDateTime> > > >(this);

            //if (filter.FinPeriodID != null) // checked above
            if (filter.ByFinancialPeriod == true)
            {
                cmd.WhereAnd <Where <INTranCost.finPeriodID, Equal <Current <InventoryTranByAcctEnqFilter.finPeriodID> > > >();
            }
            else
            {
                cmd.WhereAnd <Where <INTranCost.tranPeriodID, Equal <Current <InventoryTranByAcctEnqFilter.finPeriodID> > > >();
            }

            //if (filter.AccountID != null) // checked above
            {
                cmd.WhereAnd <Where <INTranCost.invtAcctID, Equal <Current <InventoryTranByAcctEnqFilter.accountID> > > >();
            }

            if (!SubCDUtils.IsSubCDEmpty(filter.SubCD))
            {
                cmd.WhereAnd <Where <Sub.subCD, Like <Current <InventoryTranByAcctEnqFilter.subCDWildcard> > > >();
            }

            if (filter.EndDate != null)
            {
                cmd.WhereAnd <Where <INTranCost.tranDate, LessEqual <Current <InventoryTranByAcctEnqFilter.endDate> > > >();
            }
            if (filter.InventoryID != null)
            {
                cmd.WhereAnd <Where <INTranCost.inventoryID, Equal <Current <InventoryTranByAcctEnqFilter.inventoryID> > > >();
            }

            if (filter.SiteID != null)
            {
                cmd.WhereAnd <Where <INTranCost.costSiteID, Equal <Current <InventoryTranByAcctEnqFilter.siteID> > > >();
            }

            int gridLineNbr = 0;

            foreach (PXResult <INTranCost, INTran, InventoryItem, Sub, INSubItem, INSite, INLocation, INCostStatus> it in cmd.Select())
            {
                INTranCost   tc_rec = (INTranCost)it;
                INTran       t_rec  = (INTran)it;
                INSite       s_rec  = (INSite)it;
                INLocation   l_rec  = (INLocation)it;
                INSubItem    si_rec = (INSubItem)it;
                INCostStatus cs_rec = (INCostStatus)it;

                decimal rowCost = (tc_rec.InvtMult * tc_rec.TranCost) ?? 0m;

                if (tc_rec.TranDate < filter.StartDate)
                {
                    cumulativeBalance += rowCost;
                }
                else
                {
                    if (summaryByDay)
                    {
                        if ((resultList.Count > 0) && (((InventoryTranByAcctEnqResult)resultList[resultList.Count - 1]).TranDate == tc_rec.TranDate))
                        {
                            InventoryTranByAcctEnqResult lastItem = resultList[resultList.Count - 1];
                            if (rowCost >= 0)
                            {
                                lastItem.Debit += rowCost;
                            }
                            else
                            {
                                lastItem.Credit -= rowCost;
                            }
                            lastItem.EndBalance += rowCost;
                            resultList[resultList.Count - 1] = new PXResult <InventoryTranByAcctEnqResult, INTran>(lastItem, null);
                        }
                        else
                        {
                            InventoryTranByAcctEnqResult item = new InventoryTranByAcctEnqResult();
                            item.BegBalance = cumulativeBalance;
                            item.TranDate   = tc_rec.TranDate;
                            if (rowCost >= 0)
                            {
                                item.Debit  = rowCost;
                                item.Credit = 0m;
                            }
                            else
                            {
                                item.Debit  = 0m;
                                item.Credit = -rowCost;
                            }
                            item.EndBalance      = item.BegBalance + rowCost;
                            item.GridLineNbr     = ++gridLineNbr;
                            item.CreatedDateTime = tc_rec.CreatedDateTime;
                            resultList.Add(new PXResult <InventoryTranByAcctEnqResult, INTran>(item, null));
                        }
                        cumulativeBalance += rowCost;
                    }
                    else
                    {
                        InventoryTranByAcctEnqResult item = new InventoryTranByAcctEnqResult();
                        item.BegBalance = cumulativeBalance;
                        item.TranDate   = tc_rec.TranDate;
                        if (rowCost >= 0)
                        {
                            item.Debit  = rowCost;
                            item.Credit = 0m;
                        }
                        else
                        {
                            item.Debit  = 0m;
                            item.Credit = -rowCost;
                        }
                        item.EndBalance = item.BegBalance + rowCost;

                        item.AccountID   = tc_rec.InvtAcctID;
                        item.SubID       = tc_rec.InvtSubID;
                        item.TranType    = tc_rec.TranType;
                        item.DocType     = t_rec.DocType;
                        item.DocRefNbr   = tc_rec.RefNbr;
                        item.ReceiptNbr  = cs_rec.ReceiptNbr;
                        item.InventoryID = tc_rec.InventoryID;
                        item.SubItemCD   = si_rec.SubItemCD;
                        if (s_rec.SiteID != null)
                        {
                            item.SiteID     = s_rec.SiteID;
                            item.LocationID = null;
                        }
                        else
                        if (l_rec.LocationID != null)                                 //though it's more or less guaranteed
                        {
                            item.SiteID     = l_rec.SiteID;
                            item.LocationID = l_rec.LocationID;
                        }
                        item.TranDate        = tc_rec.TranDate;
                        item.FinPerNbr       = tc_rec.FinPeriodID;
                        item.TranPerNbr      = tc_rec.TranPeriodID;
                        item.Qty             = tc_rec.Qty * tc_rec.InvtMult;
                        item.UnitCost        = (tc_rec.Qty ?? 0m) == 0m ? null : ((tc_rec.TranCost ?? 0m) + (tc_rec.VarCost ?? 0m)) / tc_rec.Qty;
                        item.CostAdj         = tc_rec.CostRefNbr != tc_rec.RefNbr;
                        item.GridLineNbr     = ++gridLineNbr;
                        item.CreatedDateTime = tc_rec.CreatedDateTime;
                        resultList.Add(new PXResult <InventoryTranByAcctEnqResult, INTran>(item, t_rec));
                        cumulativeBalance += rowCost;
                    }
                }
            }
            return(resultList);
        }
        public virtual void UpdateStdCost(INUpdateStdCostRecord itemsite)
        {
            using (new PXConnectionScope())
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    //will be true for non-stock items as well
                    if (itemsite.StdCostOverride == false)
                    {
                        PXDatabase.Update <INItemSite>(
                            new PXDataFieldAssign("StdCost", PXDbType.DirectExpression, "PendingStdCost"),
                            new PXDataFieldAssign("StdCostDate", PXDbType.DateTime, itemsite.PendingStdCostDate),
                            new PXDataFieldAssign("PendingStdCost", PXDbType.Decimal, 0m),
                            new PXDataFieldAssign("PendingStdCostDate", PXDbType.DateTime, null),
                            new PXDataFieldAssign("LastStdCost", PXDbType.DirectExpression, "StdCost"),
                            new PXDataFieldRestrict("InventoryID", PXDbType.Int, itemsite.InventoryID),
                            new PXDataFieldRestrict("StdCostOverride", PXDbType.Bit, false),
                            new PXDataFieldRestrict("PendingStdCostDate", PXDbType.DateTime, 4, itemsite.PendingStdCostDate, PXComp.LE));

                        PXDatabase.Update <InventoryItem>(
                            new PXDataFieldAssign("StdCost", PXDbType.DirectExpression, "PendingStdCost"),
                            new PXDataFieldAssign("StdCostDate", PXDbType.DateTime, itemsite.PendingStdCostDate),
                            new PXDataFieldAssign("PendingStdCost", PXDbType.Decimal, 0m),
                            new PXDataFieldAssign("PendingStdCostDate", PXDbType.DateTime, null),
                            new PXDataFieldAssign("LastStdCost", PXDbType.DirectExpression, "StdCost"),
                            new PXDataFieldRestrict("InventoryID", PXDbType.Int, itemsite.InventoryID),
                            new PXDataFieldRestrict("PendingStdCostDate", PXDbType.DateTime, 4, itemsite.PendingStdCostDate, PXComp.LE));
                    }
                    else
                    {
                        PXDatabase.Update <INItemSite>(
                            new PXDataFieldAssign("StdCost", PXDbType.DirectExpression, "PendingStdCost"),
                            new PXDataFieldAssign("StdCostDate", PXDbType.DateTime, itemsite.PendingStdCostDate),
                            new PXDataFieldAssign("PendingStdCost", PXDbType.Decimal, 0m),
                            new PXDataFieldAssign("PendingStdCostDate", PXDbType.DateTime, null),
                            new PXDataFieldAssign("LastStdCost", PXDbType.DirectExpression, "StdCost"),
                            new PXDataFieldRestrict("InventoryID", PXDbType.Int, itemsite.InventoryID),
                            new PXDataFieldRestrict("SiteID", PXDbType.Int, itemsite.SiteID),
                            new PXDataFieldRestrict("PendingStdCostDate", PXDbType.DateTime, 4, itemsite.PendingStdCostDate, PXComp.LE));
                    }

                    if (je.adjustment.Current == null)
                    {
                        je.adjustment.Cache.Insert();
                    }

                    foreach (
                        PXResult <INCostStatus, InventoryItem, INSite, INPostClass, INItemSite> res in
                        incoststatus.View.SelectMultiBound(new object[] { je.adjustment.Current, itemsite }))
                    {
                        INCostStatus layer = res;
                        INSite       site  = res;
                        INTran       tran  = new INTran();

                        try
                        {
                            ValidateProjectLocation(site, res);
                        }
                        catch (PXException ex)
                        {
                            PXProcessing <INUpdateStdCostRecord> .SetError(ex.Message);

                            continue;
                        }

                        if (((INCostStatus)res).LayerType == INLayerType.Oversold)
                        {
                            tran.TranType = INTranType.NegativeCostAdjustment;
                        }
                        else
                        {
                            tran.TranType = INTranType.StandardCostAdjustment;
                        }
                        tran.BranchID   = site.BranchID;
                        tran.InvtAcctID = layer.AccountID;
                        tran.InvtSubID  = layer.SubID;
                        tran.AcctID     = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevAcctID>
                                              (je, (InventoryItem)res, (INSite)res, (INPostClass)res);
                        tran.SubID = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevSubID>
                                         (je, (InventoryItem)res, (INSite)res, (INPostClass)res);

                        tran.InventoryID = layer.InventoryID;
                        tran.SubItemID   = layer.CostSubItemID;
                        tran.SiteID      = layer.CostSiteID;
                        tran.Qty         = 0m;
                        tran.TranCost    = PXDBCurrencyAttribute.BaseRound(this, (decimal)(layer.QtyOnHand * itemsite.PendingStdCost)) -
                                           layer.TotalCost;

                        je.transactions.Insert(tran);
                    }

                    if (je.transactions.Select().Count == 0)
                    {
                        je.Clear();
                    }
                    else
                    {
                        je.Save.Press();
                        PXProcessing <INUpdateStdCostRecord> .SetInfo(PXMessages.LocalizeFormatNoPrefixNLA(Messages.AdjstmentCreated, je.adjustment.Current.RefNbr));
                    }
                    ts.Complete();
                }
            }
        }
Beispiel #16
0
        public static void DefaultItemSiteByItem(PXGraph graph, INItemSite itemsite, InventoryItem item, INSite site, INPostClass postclass)
        {
            if (item != null)
            {
                itemsite.PendingStdCost     = item.PendingStdCost;
                itemsite.PendingStdCostDate = item.PendingStdCostDate;
                itemsite.StdCost            = item.StdCost;
                itemsite.StdCostDate        = item.StdCostDate;
                itemsite.LastStdCost        = item.LastStdCost;

                itemsite.PendingBasePrice     = item.PendingBasePrice;
                itemsite.PendingBasePriceDate = item.PendingBasePriceDate;
                itemsite.BasePrice            = item.BasePrice;
                itemsite.BasePriceDate        = item.BasePriceDate;
                itemsite.LastBasePrice        = item.LastBasePrice;

                itemsite.MarkupPct = item.MarkupPct;
                itemsite.RecPrice  = item.RecPrice;

                itemsite.ABCCodeID            = item.ABCCodeID;
                itemsite.ABCCodeIsFixed       = item.ABCCodeIsFixed;
                itemsite.MovementClassID      = item.MovementClassID;
                itemsite.MovementClassIsFixed = item.MovementClassIsFixed;

                itemsite.PreferredVendorID         = item.PreferredVendorID;
                itemsite.PreferredVendorLocationID = item.PreferredVendorLocationID;
                itemsite.ReplenishmentClassID      = site != null ? site.ReplenishmentClassID : null;
                itemsite.DfltReceiptLocationID     = site.ReceiptLocationID;
                itemsite.DfltShipLocationID        = site.ShipLocationID;

                DefaultItemReplenishment(graph, itemsite);
                DefaultSubItemReplenishment(graph, itemsite);
            }
            if (itemsite.InvtAcctID == null)
            {
                if (site.OverrideInvtAccSub == true)
                {
                    itemsite.InvtAcctID = site.InvtAcctID;
                    itemsite.InvtSubID  = site.InvtSubID;
                }
                else if (postclass != null)
                {
                    itemsite.InvtAcctID = INReleaseProcess.GetAccountDefaults <INPostClass.invtAcctID>(graph, item, site, postclass);
                    itemsite.InvtSubID  = INReleaseProcess.GetAccountDefaults <INPostClass.invtSubID>(graph, item, site, postclass);
                }
                itemsite.StdCost = item.StdCost;
            }
        }
 public static void DefaultInvtAcctSub(PXGraph graph, INItemSite itemsite, InventoryItem item, INSite site, INPostClass postclass)
 {
     if (site != null && site.OverrideInvtAccSub == true)
     {
         itemsite.InvtAcctID = site.InvtAcctID;
         itemsite.InvtSubID  = site.InvtSubID;
     }
     else if (postclass != null)
     {
         itemsite.InvtAcctID = INReleaseProcess.GetAccountDefaults <INPostClass.invtAcctID>(graph, item, site, postclass);
         itemsite.InvtSubID  = INReleaseProcess.GetAccountDefaults <INPostClass.invtSubID>(graph, item, site, postclass);
     }
 }
        protected virtual void INRegister_TransferNbr_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            INTran newtran      = null;
            INTran prev_tran    = null;
            int?   prev_linenbr = null;

            using (new PXReadBranchRestrictedScope())
            {
                foreach (PXResult <INTran, INTranSplit, INItemPlan, INSite> res in
                         PXSelectJoin <INTran,
                                       InnerJoin <INTranSplit,
                                                  On <INTranSplit.tranType, Equal <INTran.tranType>,
                                                      And <INTranSplit.refNbr, Equal <INTran.refNbr>,
                                                           And <INTranSplit.lineNbr, Equal <INTran.lineNbr> > > >,
                                                  InnerJoin <INItemPlan,
                                                             On <INItemPlan.planID, Equal <INTranSplit.planID>,
                                                                 And <INItemPlan.planType, Equal <INPlanConstants.plan42> > >,
                                                             InnerJoin <INSite, On <INSite.siteID, Equal <INTran.toSiteID> > > > >,
                                       Where <INTran.docType, Equal <Required <INTran.docType> >,
                                              And <INTran.refNbr, Equal <Required <INTran.refNbr> >,
                                                   And <INTran.docType, Equal <INDocType.transfer>,
                                                        And <INTran.invtMult, Equal <shortMinus1> > > > >,
                                       OrderBy <Asc <INTran.tranType, Asc <INTran.refNbr, Asc <INTran.lineNbr> > > > >
                         .Select(this, INDocType.Transfer, ((INRegister)e.Row).TransferNbr))
                {
                    INTran      tran  = res;
                    INTranSplit split = res;
                    INSite      site  = res;

                    if (object.Equals(prev_tran, tran) == false)
                    {
                        if (!object.Equals(receipt.Current.BranchID, site.BranchID))
                        {
                            INRegister copy = PXCache <INRegister> .CreateCopy(receipt.Current);

                            copy.BranchID = site.BranchID;
                            receipt.Update(copy);
                        }
                        newtran = PXCache <INTran> .CreateCopy(tran);

                        newtran.OrigBranchID = newtran.BranchID;
                        newtran.OrigTranType = newtran.TranType;
                        newtran.OrigRefNbr   = newtran.RefNbr;
                        newtran.OrigLineNbr  = newtran.LineNbr;
                        newtran.BranchID     = site.BranchID;
                        newtran.DocType      = ((INRegister)e.Row).DocType;
                        newtran.RefNbr       = ((INRegister)e.Row).RefNbr;
                        newtran.LineNbr      = (int)PXLineNbrAttribute.NewLineNbr <INTran.lineNbr>(transactions.Cache, e.Row);
                        newtran.InvtMult     = (short)1;
                        newtran.SiteID       = newtran.ToSiteID;
                        newtran.LocationID   = newtran.ToLocationID;
                        newtran.ToSiteID     = null;
                        newtran.ToLocationID = null;
                        newtran.Qty          = 0m;
                        newtran.BaseQty      = 0m;
                        newtran.Released     = false;
                        newtran.InvtAcctID   = null;
                        newtran.InvtSubID    = null;
                        newtran.ReasonCode   = null;
                        newtran.ARDocType    = null;
                        newtran.ARRefNbr     = null;
                        newtran.ARLineNbr    = null;
                        newtran.ProjectID    = null;
                        newtran.TaskID       = null;

                        splits.Current = null;

                        newtran = transactions.Insert(newtran);

                        if (splits.Current != null)
                        {
                            splits.Delete(splits.Current);
                        }

                        prev_tran    = tran;
                        prev_linenbr = newtran.LineNbr;
                    }

                    INTranSplit newsplit = PXCache <INTranSplit> .CreateCopy(split);

                    newsplit.DocType      = ((INRegister)e.Row).DocType;
                    newsplit.RefNbr       = ((INRegister)e.Row).RefNbr;
                    newsplit.LineNbr      = prev_linenbr;
                    newsplit.SplitLineNbr = (int)PXLineNbrAttribute.NewLineNbr <INTranSplit.splitLineNbr>(splits.Cache, e.Row);
                    newsplit.InvtMult     = (short)1;
                    newsplit.SiteID       = tran.ToSiteID;
                    newsplit.LocationID   = tran.ToLocationID;
                    newsplit.PlanID       = null;
                    newsplit.Released     = false;
                    newsplit.ProjectID    = null;
                    newsplit.TaskID       = null;

                    newsplit = splits.Insert(newsplit);

                    if (newtran.BaseQty == tran.BaseQty)
                    {
                        //fix conversion rounding
                        newtran = PXCache <INTran> .CreateCopy(newtran);

                        newtran.Qty      = tran.Qty;
                        newtran.UnitCost = PXPriceCostAttribute.Round(tran.Qty != 0m ? (decimal)(tran.TranCost / tran.Qty) : 0m);
                        newtran.TranCost = tran.TranCost;
                        newtran          = transactions.Update(newtran);
                    }
                }
            }
        }
        public static void DefaultItemSiteByItem(PXGraph graph, INItemSite itemsite, InventoryItem item, INSite site, INPostClass postclass)
        {
            if (item != null)
            {
                itemsite.PendingStdCost     = item.PendingStdCost;
                itemsite.PendingStdCostDate = item.PendingStdCostDate;
                itemsite.StdCost            = item.StdCost;
                itemsite.StdCostDate        = item.StdCostDate;
                itemsite.LastStdCost        = item.LastStdCost;

                itemsite.BasePrice = item.BasePrice;

                itemsite.MarkupPct = item.MarkupPct;
                itemsite.RecPrice  = item.RecPrice;

                itemsite.ABCCodeID            = item.ABCCodeID;
                itemsite.ABCCodeIsFixed       = item.ABCCodeIsFixed;
                itemsite.MovementClassID      = item.MovementClassID;
                itemsite.MovementClassIsFixed = item.MovementClassIsFixed;

                itemsite.PreferredVendorID         = item.PreferredVendorID;
                itemsite.PreferredVendorLocationID = item.PreferredVendorLocationID;
                itemsite.ReplenishmentClassID      = site != null ? site.ReplenishmentClassID : null;
                itemsite.DfltReceiptLocationID     = site.ReceiptLocationID;
                itemsite.DfltShipLocationID        = site.ShipLocationID;

                DefaultItemReplenishment(graph, itemsite);
                DefaultSubItemReplenishment(graph, itemsite);
            }
        }