Exemple #1
0
        protected virtual IEnumerable AccountByPeriod(PXAdapter adapter)
        {
            if (this.EnqResult.Current != null)
            {
                AccountHistoryByYearEnq graph  = PXGraph.CreateInstance <AccountHistoryByYearEnq>();
                AccountByYearFilter     filter = PXCache <AccountByYearFilter> .CreateCopy(graph.Filter.Current);

                filter.OrgBAccountID  = Filter.Current.OrgBAccountID;
                filter.OrganizationID = Filter.Current.OrganizationID;
                filter.BranchID       = EnqResult.Current.BranchID;
                filter.LedgerID       = Filter.Current.LedgerID;
                filter.AccountID      = EnqResult.Current.AccountID;
                filter.SubCD          = Filter.Current.SubCD;
                filter.FinPeriodID    = EnqResult.Current.LastActivityPeriod;

                OrganizationFinPeriod fp = PXSelect <
                    OrganizationFinPeriod,
                    Where <OrganizationFinPeriod.finPeriodID, Equal <Required <OrganizationFinPeriod.finPeriodID> >,
                           And <OrganizationFinPeriod.organizationID, Equal <Required <OrganizationFinPeriod.organizationID> > > > >
                                           .Select(this, filter.FinPeriodID, PXAccess.GetParentOrganizationID(filter.BranchID));

                if (fp != null)
                {
                    filter.FinYear = fp.FinYear;
                }

                filter.ShowCuryDetail = this.Filter.Current.ShowCuryDetail;
                graph.Filter.Update(filter);
                throw new PXRedirectRequiredException(graph, "Account By Period");
            }
            return(adapter.Get());
        }
        protected IEnumerable bookYear()
        {
            if (BookYear.Cache.InternalCurrent == null)
            {
                FABookYear defaultYear =
                    SelectFrom <FABookYear>
                    .InnerJoin <FABook> .On <FABookYear.bookID.IsEqual <FABook.bookID> >
                    .Where <FABookYear.organizationID.IsEqual <@P.AsInt>
                            .And <FABookYear.endDate.IsGreater <@P.AsDateTime> > >
                    .OrderBy <
                        Desc <FABook.updateGL>,
                        Asc <FABookYear.year> >
                    .View.SelectSingleBound(this, null, PXAccess.GetParentOrganizationID(Accessinfo.BranchID), Accessinfo.BusinessDate);

                if (defaultYear == null)
                {
                    defaultYear = SelectFrom <FABookYear>
                                  .InnerJoin <FABook> .On <FABookYear.bookID.IsEqual <FABook.bookID> >
                                  .Where <FABookYear.organizationID.IsEqual <@P.AsInt>
                                          .And <FABookYear.endDate.IsLess <@P.AsDateTime> > >
                                  .OrderBy <
                        Desc <FABook.updateGL>,
                        Desc <FABookYear.year> >
                                  .View.SelectSingleBound(this, null, PXAccess.GetParentOrganizationID(Accessinfo.BranchID), Accessinfo.BusinessDate);
                }

                return(new object[] { defaultYear ?? throw new PXSetupNotEnteredException <FABookYear>(Messages.NoCalendarDefined) });
        public virtual OrganizationFinPeriod GetNearestOpenOrganizationFinPeriodInSubledger <TClosedInSubledgerField>(string orgFinPeriodID, int?branchID, Func <bool> additionalCondition = null)
            where TClosedInSubledgerField : IBqlField
        {
            int?organizationID = PXAccess.GetParentOrganizationID(branchID);

            return(GetNearestOpenOrganizationFinPeriodInSubledgerByOrganization <TClosedInSubledgerField>(orgFinPeriodID, organizationID, additionalCondition));
        }
Exemple #4
0
        public virtual void GetRange(DateTime date, string Range, int?cashAccountID, out DateTime?RangeStart, out DateTime?RangeEnd)
        {
            switch (Range)
            {
            case "W":
                RangeStart = date.AddDays(-1 * (PXDateTime.DayOfWeekOrdinal(date.DayOfWeek) - 1));
                RangeEnd   = date.AddDays(7 - PXDateTime.DayOfWeekOrdinal(date.DayOfWeek));
                return;

            case "M":
                RangeStart = new DateTime(date.Year, date.Month, 1);
                RangeEnd   = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);
                return;

            case "P":
                CashAccount cashAccount = PXSelect <CashAccount, Where <CashAccount.cashAccountID, Equal <Required <CashAccount.cashAccountID> > > > .Select(this, cashAccountID);

                int?organizationID = PXAccess.GetParentOrganizationID(cashAccount?.BranchID);
                var period         = FinPeriodRepository.FindFinPeriodByDate(date, organizationID);
                RangeStart = period?.StartDate;
                RangeEnd   = period?.EndDate;
                return;

            case "D":
            default:
                RangeStart = date;
                RangeEnd   = date;
                return;
            }
        }
        public FABookPeriod FindFABookPeriodOfDateByBranchID(DateTime?date, int?bookID, int?branchID, bool check = true)
        {
            CheckNotNullObjectContract(date, nameof(date));
            CheckNotNullIDContract(bookID, nameof(bookID));
            CheckNotNullIDContract(branchID, nameof(branchID));

            FABookPeriod period = PXSelect <
                FABookPeriod,
                Where <FABookPeriod.bookID, Equal <Required <FABookPeriod.bookID> >,
                       And <FABookPeriod.organizationID, Equal <Required <FABookPeriod.organizationID> >,
                            And <FABookPeriod.startDate, LessEqual <Required <FABookPeriod.startDate> >,
                                 And <FABookPeriod.endDate, Greater <Required <FABookPeriod.endDate> > > > > > >
                                  .Select(
                Graph,
                bookID,
                IsPostingFABook(bookID)
                ?PXAccess.GetParentOrganizationID(branchID)
                : FinPeriod.organizationID.MasterValue,
                date,
                date);

            if (check && period == null)
            {
                throw new PXFABookPeriodException();
            }

            return(period);
        }
 public virtual FABookPeriod GetMappedFABookPeriodByBranches(int?bookID, int?sourceBranchID, string sourcefinPeriodID, int?targetBranchID)
 {
     return(GetMappedFABookPeriod(
                bookID,
                PXAccess.GetParentOrganizationID(sourceBranchID),
                sourcefinPeriodID,
                PXAccess.GetParentOrganizationID(targetBranchID)));
 }
Exemple #7
0
 public int?GetCalendarOrganizationID(int?branchID, bool?useMasterCalendar)
 {
     if (useMasterCalendar == true || branchID == null)
     {
         return(FinPeriod.organizationID.MasterValue);
     }
     else
     {
         return(PXAccess.GetParentOrganizationID(branchID));
     }
 }
Exemple #8
0
        private static ProcessingResult ValidateFinPeriods(GLBudgetEntry graph, IEnumerable <GLBudgetLineDetail> records)
        {
            ProcessingResult generalResult = new ProcessingResult();

            var recordsByPeriod = records.GroupBy(record => record.FinPeriodID);

            foreach (var recordsByPeriodGroup in recordsByPeriod)
            {
                string finPeriodID = recordsByPeriodGroup.Key;

                int?[] orgnizationIDs = recordsByPeriodGroup.GroupBy(t => PXAccess.GetParentOrganizationID(t.BranchID))
                                        .Select(g => g.Key)
                                        .ToArray();

                ICollection <OrganizationFinPeriod> finPeriods =
                    PXSelect <OrganizationFinPeriod,
                              Where <OrganizationFinPeriod.organizationID, In <Required <OrganizationFinPeriod.organizationID> >,
                                     And <OrganizationFinPeriod.finPeriodID, Equal <Required <OrganizationFinPeriod.finPeriodID> > > > >
                    .Select(graph, orgnizationIDs, finPeriodID)
                    .RowCast <OrganizationFinPeriod>()
                    .ToArray();

                if (finPeriods.Count != orgnizationIDs.Length)
                {
                    string[] organizationCDs = orgnizationIDs.Except(finPeriods.Select(period => period.OrganizationID))
                                               .Select(PXAccess.GetOrganizationCD)
                                               .ToArray();

                    generalResult.AddErrorMessage(Messages.FinPeriodDoesNotExistForCompanies,
                                                  FinPeriodIDFormattingAttribute.FormatForError(finPeriodID),
                                                  organizationCDs.JoinIntoStringForMessageNoQuotes(20));
                }

                foreach (OrganizationFinPeriod finPeriod in finPeriods)
                {
                    ProcessingResult result = new ProcessingResult();
                    if (finPeriod.Status == FinPeriod.status.Locked)
                    {
                        result.AddErrorMessage(Messages.FinPeriodIsLockedInCompany,
                                               FinPeriodIDFormattingAttribute.FormatForError(finPeriod.FinPeriodID),
                                               PXAccess.GetOrganizationCD(finPeriod.OrganizationID));
                    }

                    generalResult.Aggregate(result);

                    if (generalResult.Messages.Count > 20)
                    {
                        return(generalResult);
                    }
                }
            }
            return(generalResult);
        }
Exemple #9
0
        private DRScheduleDetail InsertScheduleDetail(
            int?componentID,
            DRDeferredCode defCode,
            decimal amount,
            AccountSubaccountPair deferralAccountSubaccount,
            AccountSubaccountPair salesOrExpenseAccountSubaccount,
            int?overridenSubID = null)
        {
            FinPeriod detailFinPeriod = FinPeriodRepository
                                        .GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(_branchID),
                                                                      _schedule.FinPeriodID).GetValueOrRaiseError();

            DRScheduleDetail scheduleDetail = new DRScheduleDetail
            {
                ScheduleID    = _schedule.ScheduleID,
                BranchID      = _branchID,
                ComponentID   = componentID,
                CuryTotalAmt  = amount,
                CuryDefAmt    = amount,
                DefCode       = defCode.DeferredCodeID,
                Status        = _isDraft ? DRScheduleStatus.Draft : DRScheduleStatus.Open,
                IsCustom      = false,
                IsOpen        = true,
                Module        = _schedule.Module,
                DocType       = _schedule.DocType,
                RefNbr        = _schedule.RefNbr,
                LineNbr       = _schedule.LineNbr,
                FinPeriodID   = detailFinPeriod.FinPeriodID,
                TranPeriodID  = detailFinPeriod.MasterFinPeriodID,
                BAccountID    = _schedule.BAccountID,
                AccountID     = salesOrExpenseAccountSubaccount.AccountID,
                SubID         = overridenSubID ?? salesOrExpenseAccountSubaccount.SubID,
                DefAcctID     = deferralAccountSubaccount.AccountID,
                DefSubID      = deferralAccountSubaccount.SubID,
                CreditLineNbr = 0,
                DocDate       = _schedule.DocDate,
                BAccountType  =
                    _schedule.Module == BatchModule.AP
                                                ? BAccountType.VendorType
                                                : BAccountType.CustomerType,
            };

            scheduleDetail = _drEntityStorage.Insert(scheduleDetail);

            if (!_isDraft)
            {
                _drEntityStorage.CreateCreditLineTransaction(scheduleDetail, defCode, _branchID);
            }

            return(scheduleDetail);
        }
        public virtual void ValidateFinPeriod(IEnumerable <IAccountable> records, Type fieldModuleClosed = null)
        {
            var recordsByPeriod = records.AsEnumerable().GroupBy(record => record.FinPeriodID);

            ProcessingResult generalResult = new ProcessingResult();

            foreach (var recordsByPeriodGroup in recordsByPeriod)
            {
                int?[] orgnizationIDs = recordsByPeriodGroup.GroupBy(t => PXAccess.GetParentOrganizationID(t.BranchID))
                                        .Select(g => g.Key)
                                        .ToArray();

                ValidateFinPeriod(recordsByPeriodGroup.Key, orgnizationIDs, fieldModuleClosed, generalResult);
            }

            generalResult.RaiseIfHasError();
        }
        private void ValidateNotMainRowLevelSources(PXCache cache, object oldRow, object newRow, bool externalCall, FinPeriod newMainOrgFinPeriod)
        {
            ValidationResult validationResult = ValidateRowLevelSources(
                CalendarOrganizationIDProvider,
                cache,
                newRow,
                organizationID => FinPeriodRepository
                .GetFinPeriodByMasterPeriodID(organizationID, newMainOrgFinPeriod.MasterFinPeriodID).IsSuccess,
                skipMain: true);

            if (validationResult.HasErrors)
            {
                foreach (var branchValue in validationResult.BranchValuesWithErrors)
                {
                    if (branchValue.SpecificationItem.BranchSourceType != null &&
                        (branchValue.SpecificationItem.BranchSourceFormulaType != null ||
                         PXAccess.FeatureInstalled <FeaturesSet.branch>()))
                    {
                        PXCache branchCache = cache.Graph.Caches[BqlCommand.GetItemType(branchValue.SpecificationItem.BranchSourceType)];
                        object  newBranch   = branchCache.GetItemType().IsAssignableFrom(newRow.GetType())
                                                        ? newRow
                                                        : branchCache.Current;
                        object oldBranch = branchCache.GetItemType().IsAssignableFrom(oldRow.GetType())
                                                        ? oldRow
                                                        : branchCache.Current;

                        string organizationCD =
                            PXAccess.GetOrganizationCD(
                                PXAccess.GetParentOrganizationID(branchValue.SourceBranchIDs.Single()));

                        var exception = new PXSetPropertyException(
                            Messages.RelatedFinPeriodForMasterDoesNotExistForCompany,
                            FormatForError(newMainOrgFinPeriod.MasterFinPeriodID),
                            organizationCD);

                        SetErrorAndResetToOldForField(
                            branchCache,
                            oldBranch,
                            newBranch,
                            branchValue.SpecificationItem.BranchSourceType.Name,
                            exception,
                            externalCall);
                    }
                }
            }
        }
        public virtual OrganizationFinPeriod GetNearestOpenOrganizationMappedFABookPeriodInSubledger <TClosedInSubledgerField>(int?bookID, int?sourceBranchID, string sourcefinPeriodID, int?targetBranchID)
            where TClosedInSubledgerField : IBqlField
        {
            if (!FABookPeriodRepositoryHelper.IsPostingFABook(bookID))
            {
                return(null);
            }

            IFinPeriodUtils         finPeriodUtils         = Graph.GetService <IFinPeriodUtils>();
            IFinPeriodRepository    finPeriodRepository    = Graph.GetService <IFinPeriodRepository>();
            IFABookPeriodRepository faBookPeriodRepository = Graph.GetService <IFABookPeriodRepository>();

            int?sourceOrganizationID = PXAccess.GetParentOrganizationID(sourceBranchID);
            int?targetOrganizationID = PXAccess.GetParentOrganizationID(targetBranchID);

            // Mapped book period - first way:
            // FABookPeriod of sourceBranchID -> master book Period -> FABookPeriod of targetBranchID
            //
            ProcessingResult <FABookPeriod> targetFABookPeriod = faBookPeriodRepository.FindMappedFABookPeriod(
                bookID,
                sourceOrganizationID,
                sourcefinPeriodID,
                targetOrganizationID);

            // Mapped book period - second way:
            // finPeriodID of sourceBranchID -> masterFinPeriod -> FinPeriodID of targetBranchID -> FABookPeriod of targetBranchID
            //
            if (targetFABookPeriod.Result == null)
            {
                ProcessingResult <FABookPeriod> targetFABookPeriodSecondWay = faBookPeriodRepository.FindMappedFABookPeriodUsingFinPeriod(
                    bookID,
                    sourceOrganizationID,
                    sourcefinPeriodID,
                    targetOrganizationID);

                targetFABookPeriodSecondWay.RaiseIfHasError();

                targetFABookPeriod = targetFABookPeriodSecondWay;
            }

            OrganizationFinPeriod period = finPeriodUtils.GetNearestOpenOrganizationFinPeriodInSubledger <TClosedInSubledgerField>(targetFABookPeriod.ThisOrRaiseIfHasError().Result);

            return(period);
        }
        /// <summary>
        /// Adds a related transaction for every original transaction
        /// in <paramref name="originalTransactions"/> using information
        /// from the provided related <see cref="DRScheduleDetail"/>.
        /// Does not set any transaction amounts.
        /// </summary>
        /// <param name="transactionList">
        /// Transaction list where the new transaction will be put (if created).
        /// </param>
        /// <param name="lineCounter">
        /// Transaction line counter. Will be incremented if any transactions are created by this procedure.
        /// </param>
        private void AddRelatedTransactions(
            IList <DRScheduleTran> transactionList,
            DRScheduleDetail relatedScheduleDetail,
            IEnumerable <DRScheduleTran> originalTransactions,
            int?branchID,
            ref short lineCounter)
        {
            int?organizationID = PXAccess.GetParentOrganizationID(branchID);

            foreach (DRScheduleTran originalTransaction in originalTransactions)
            {
                ++lineCounter;

                DRScheduleTran relatedTransaction = new DRScheduleTran
                {
                    BranchID      = branchID,
                    AccountID     = relatedScheduleDetail.AccountID,
                    SubID         = relatedScheduleDetail.SubID,
                    LineNbr       = lineCounter,
                    DetailLineNbr = relatedScheduleDetail.DetailLineNbr,
                    ScheduleID    = relatedScheduleDetail.ScheduleID,
                    ComponentID   = relatedScheduleDetail.ComponentID,
                    Status        = DRScheduleTranStatus.Open
                };

                var maxDate = originalTransaction.RecDate.Value < relatedScheduleDetail.DocDate.Value
                                        ? relatedScheduleDetail.DocDate
                                        : originalTransaction.RecDate;

                relatedTransaction.RecDate = maxDate;

                var maxPeriod = string.CompareOrdinal(originalTransaction.FinPeriodID, relatedScheduleDetail.FinPeriodID) < 0
                                        ? relatedScheduleDetail.FinPeriodID
                                        : originalTransaction.FinPeriodID;

                FinPeriod maxFinPeriod = _finPeriodRepository.GetByID(maxPeriod, organizationID);

                relatedTransaction.FinPeriodID  = maxFinPeriod.FinPeriodID;
                relatedTransaction.TranPeriodID = maxFinPeriod.MasterFinPeriodID;

                transactionList.Add(relatedTransaction);
            }
        }
Exemple #14
0
        private void InsertResidualScheduleDetail(int?componentID, decimal amount, int?acctID, int?subID)
        {
            FinPeriod detailFinPeriod = FinPeriodRepository
                                        .GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(_branchID),
                                                                      _schedule.FinPeriodID).GetValueOrRaiseError();

            DRScheduleDetail residualScheduleDetail = new DRScheduleDetail
            {
                ScheduleID    = _schedule.ScheduleID,
                BranchID      = _branchID,
                ComponentID   = componentID,
                CuryTotalAmt  = amount,
                CuryDefAmt    = 0.0m,
                DefCode       = null,
                IsCustom      = false,
                IsResidual    = true,
                IsOpen        = false,
                Module        = _schedule.Module,
                DocType       = _schedule.DocType,
                RefNbr        = _schedule.RefNbr,
                LineNbr       = _schedule.LineNbr,
                FinPeriodID   = detailFinPeriod.FinPeriodID,
                TranPeriodID  = detailFinPeriod.MasterFinPeriodID,
                BAccountID    = _schedule.BAccountID,
                AccountID     = acctID,
                SubID         = subID,
                DefAcctID     = acctID,
                DefSubID      = subID,
                CreditLineNbr = 0,
                DocDate       = _schedule.DocDate,
                BAccountType  = _schedule.Module == BatchModule.AP ?
                                BAccountType.VendorType :
                                BAccountType.CustomerType,
                Status = _isDraft ?
                         DRScheduleStatus.Draft :
                         DRScheduleStatus.Closed,
            };

            residualScheduleDetail.CloseFinPeriodID = residualScheduleDetail.FinPeriodID;

            _drEntityStorage.Insert(residualScheduleDetail);
        }
Exemple #15
0
        protected virtual SourceValuesCollectionItem EvaluateOrganizationIDsValuesItem(SourceValuesCollectionItem calendarOrganizationIdSourceValuesItem)
        {
            if (calendarOrganizationIdSourceValuesItem == null)
            {
                return(null);
            }

            if (IsIDsUndefined(calendarOrganizationIdSourceValuesItem.OrganizationIDs))
            {
                if (calendarOrganizationIdSourceValuesItem.BranchIDs != null)
                {
                    calendarOrganizationIdSourceValuesItem.OrganizationIDs =
                        calendarOrganizationIdSourceValuesItem.BranchIDs
                        .Select(branchID => PXAccess.GetParentOrganizationID(branchID))
                        .ToList();
                }
            }

            return(calendarOrganizationIdSourceValuesItem);
        }
        public virtual OrganizationFinPeriod GetOpenOrganizationFinPeriodInSubledger <TClosedInSubledgerField>(string orgFinPeriodID, int?branchID)
            where TClosedInSubledgerField : IBqlField
        {
            int?organizationID = PXAccess.GetParentOrganizationID(branchID);
            OrganizationFinPeriod orgFinPeriod = PXSelect <
                OrganizationFinPeriod,
                Where <OrganizationFinPeriod.finPeriodID, Equal <Required <OrganizationFinPeriod.finPeriodID> >,
                       And <OrganizationFinPeriod.organizationID, Equal <Required <OrganizationFinPeriod.organizationID> >,
                            And <TClosedInSubledgerField, NotEqual <True> > > > >
                                                 .SelectWindowed(Graph, 0, 1, orgFinPeriodID, organizationID);

            if (orgFinPeriod == null)
            {
                throw new PXException(
                          Messages.FiscalPeriodClosedInOrganization,
                          FinPeriodIDFormattingAttribute.FormatForError(orgFinPeriodID),
                          PXAccess.GetOrganizationCD(organizationID));
            }
            return(orgFinPeriod);
        }
Exemple #17
0
        public virtual OrganizationFinPeriod GetNearestOpenOrganizationFinPeriodInSubledger <TClosedInSubledgerField>(string orgFinPeriodID, int?branchID, Func <bool> additionalCondition = null)
            where TClosedInSubledgerField : IBqlField
        {
            int?organizationID = PXAccess.GetParentOrganizationID(branchID);
            OrganizationFinPeriod orgFinPeriod = PXSelect <
                OrganizationFinPeriod,
                Where <OrganizationFinPeriod.finPeriodID, GreaterEqual <Required <OrganizationFinPeriod.finPeriodID> >,
                       And <OrganizationFinPeriod.organizationID, Equal <Required <OrganizationFinPeriod.organizationID> >,
                            And <TClosedInSubledgerField, NotEqual <True>,
                                 And <OrganizationFinPeriod.startDate, NotEqual <OrganizationFinPeriod.endDate> > > > >,
                OrderBy <Asc <OrganizationFinPeriod.finPeriodID> > >
                                                 .SelectWindowed(Graph, 0, 1, orgFinPeriodID, organizationID);

            if (orgFinPeriod == null && (additionalCondition == null || additionalCondition()))
            {
                throw new PXException(
                          Messages.NoOpenPeriodInOrganization,
                          PXAccess.GetOrganizationCD(organizationID));
            }
            return(orgFinPeriod);
        }
        private void ValidateDocDate(PXCache cache, TaxAdjustment doc)
        {
            if (doc.DocDate == null || doc.TaxPeriod == null || doc.BranchID == null)
            {
                return;
            }

            var taxPeriod = TaxYearMaint.FindTaxPeriodByKey(this,
                                                            PXAccess.GetParentOrganizationID(doc.BranchID),
                                                            doc.VendorID,
                                                            doc.TaxPeriod);

            if (taxPeriod == null)
            {
                return;
            }

            string errorMessage = null;

            if (vendor.Current.TaxReportFinPeriod == true)
            {
                var finPeriod = FinPeriodRepository.GetByID(doc.FinPeriodID, PXAccess.GetParentOrganizationID(doc.BranchID));

                if (finPeriod.FinDate >= taxPeriod.EndDate)
                {
                    errorMessage = Messages.SelectedDateBelongsToTheTaxPeriodThatIsGreaterThanTheSpecifiedOne;
                }
            }
            else if (doc.DocDate >= taxPeriod.EndDate)
            {
                errorMessage = Messages.SelectedDateBelongsToTheTaxPeriodThatIsGreaterThanTheSpecifiedOne;
            }

            var ex = errorMessage != null
                                ? new PXSetPropertyException(errorMessage, PXErrorLevel.Warning)
                                : null;

            cache.RaiseExceptionHandling <TaxAdjustment.docDate>(doc, doc.DocDate, ex);
        }
Exemple #19
0
        private static List <ScheduledTran> GetValidatedItems(List <ScheduledTran> items, ScheduleMaint scheduleMaint)
        {
            List <ScheduledTran> validatedItems = new List <ScheduledTran>();

            foreach (ScheduledTran item in items)
            {
                PXProcessing <ScheduledTran> .SetCurrentItem(item);

                try
                {
                    FinPeriod finPeriod = scheduleMaint.FinPeriodRepository.FindByID(PXAccess.GetParentOrganizationID(item.BranchID), item.FinPeriodID);
                    scheduleMaint.FinPeriodUtils.CanPostToPeriod(finPeriod).RaiseIfHasError();

                    validatedItems.Add(item);
                }
                catch (Exception ex)
                {
                    PXProcessing <ScheduledTran> .SetError(ex.Message);
                }
            }

            return(validatedItems);
        }
Exemple #20
0
        public virtual string GetFinPeriodByBranchAndMasterPeriodID(int?branchId, string masterFinPeriod)
        {
            if (branchId == default(int?))
            {
                throw new ArgumentNullException($"{nameof(branchId)} cannot be null");
            }
            if (masterFinPeriod == null)
            {
                throw new ArgumentNullException($"{nameof(masterFinPeriod)} cannot be null");
            }

            var orgId = PXAccess.GetParentOrganizationID(branchId);
            var getFinPeriodProcess = GetFinPeriodByMasterPeriodID(orgId, masterFinPeriod);

            if (getFinPeriodProcess.IsSuccess)
            {
                return(getFinPeriodProcess.Result.FinPeriodID);
            }
            else
            {
                throw new PXException(getFinPeriodProcess.GeneralMessage);
            }
        }
        protected override KeyWithSourceValues EvaluateRawKey(PXGraph graph, KeyWithSourceValues keyWithSourceValues)
        {
            if (keyWithSourceValues == null)
            {
                return(null);
            }

            keyWithSourceValues.KeyOrganizationIDs = keyWithSourceValues.SourceOrganizationIDs;

            if (IsIDsUndefined(keyWithSourceValues.KeyOrganizationIDs))
            {
                if (keyWithSourceValues.SourceBranchIDs != null)
                {
                    keyWithSourceValues.KeyOrganizationIDs =
                        keyWithSourceValues.SourceBranchIDs
                        .Select(branchID => PXAccess.GetParentOrganizationID(branchID))
                        .ToList();
                }
            }

            keyWithSourceValues.Key.OrganizationID = keyWithSourceValues.KeyOrganizationIDs.First();

            return(keyWithSourceValues);
        }
		public virtual ProcessingResult CheckFinPeriod(string finPeriodID, int? branchID)
		{
			ProcessingResult result = new ProcessingResult();
			int? organizationID = PXAccess.GetParentOrganizationID(branchID);
			FinPeriod period = FinPeriodRepository.FindByID(organizationID, finPeriodID);

			if (period == null)
			{
				result.AddErrorMessage(GL.Messages.FinPeriodDoesNotExistForCompany,
						FinPeriodIDFormattingAttribute.FormatForError(finPeriodID),
						PXAccess.GetOrganizationCD(PXAccess.GetParentOrganizationID(branchID)));
			}
			else
			{
				result = FinPeriodUtils.CanPostToPeriod(period);
			}

			if (!result.IsSuccess)
			{
				PXProcessing<THistory>.SetError(new PXException(result.GetGeneralMessage()));
			}

			return result;
		}
        public virtual void VerifyAndSetFirstOpenedFinPeriod <TFinPeriodField, TBranchField>(PXCache rowCache, object row, PXSelectBase <OrganizationFinPeriod> finPeriodView, Type fieldModuleClosed = null)
            where TFinPeriodField : class, IBqlField
            where TBranchField : class, IBqlField
        {
            OrganizationFinPeriod finPeriod = finPeriodView.Current as OrganizationFinPeriod;

            if (finPeriod != null)
            {
                GLSetup glsetup = PXSetup <GLSetup> .Select(Graph);

                bool isClosed = finPeriod.Status == FinPeriods.TableDefinition.FinPeriod.status.Closed;

                if (fieldModuleClosed != null)
                {
                    isClosed |= (bool?)finPeriodView.Cache.GetValue(finPeriod, fieldModuleClosed.Name) == true;
                }

                if (finPeriod.Status == FinPeriod.status.Inactive ||
                    finPeriod.Status == FinPeriod.status.Locked ||
                    isClosed && glsetup != null && glsetup.RestrictAccessToClosedPeriods == true)
                {
                    string finPeriodID    = (string)rowCache.GetValue <TFinPeriodField>(row);
                    int?   organizationID = PXAccess.GetParentOrganizationID((int?)rowCache.GetValue <TBranchField>(row));

                    OrganizationFinPeriod firstopen = rowCache.Graph.GetService <IFinPeriodRepository>().FindFirstOpenFinPeriod(finPeriodID, organizationID, fieldModuleClosed);

                    if (firstopen == null)
                    {
                        string userPeriod = Mask.Format("##-####", finPeriodView.Cache.GetValueExt <OrganizationFinPeriod.finPeriodID>(finPeriodView.Current).ToString());
                        throw new PXSetPropertyException(GL.Messages.NoActivePeriodAfter, userPeriod);
                    }

                    rowCache.SetValue <TFinPeriodField>(row, firstopen.FinPeriodID);
                }
            }
        }
        private void SetDocDateByPeriods(PXCache cache, TaxAdjustment document)
        {
            if (document.TaxPeriod == null || document.BranchID == null)
            {
                return;
            }

            var taxPeriod = TaxYearMaint.FindTaxPeriodByKey(this,
                                                            PXAccess.GetParentOrganizationID(document.BranchID),
                                                            document.VendorID,
                                                            document.TaxPeriod);

            if (taxPeriod == null)
            {
                return;
            }

            DateTime?docDate;

            if (vendor.Current.TaxReportFinPeriod == true)
            {
                var finPeriod = FinPeriodRepository.FindMaxFinPeriodWithEndDataBelongToInterval(taxPeriod.StartDate,
                                                                                                taxPeriod.EndDate,
                                                                                                PXAccess.GetParentOrganizationID(document.BranchID));

                docDate = finPeriod != null
                                                        ? finPeriod.FinDate
                                                        : Accessinfo.BusinessDate;
            }
            else
            {
                docDate = taxPeriod.EndDateUI;
            }

            cache.SetValueExt <TaxAdjustment.docDate>(document, docDate);
        }
        public int GetFABookPeriodOrganizationID(int?bookID, int?assetID, bool check = true)
        {
            if (check)
            {
                CheckNotNullIDContract(bookID, nameof(bookID));
                CheckNotNullIDContract(assetID, nameof(assetID));
            }

            if (bookID == null || !IsPostingFABook(bookID))
            {
                return(FinPeriod.organizationID.MasterValue);
            }
            else
            {
                FixedAsset asset = PXSelect <FixedAsset, Where <FixedAsset.assetID, Equal <Required <FixedAsset.assetID> > > > .Select(Graph, assetID);

                if (asset == null)
                {
                    throw new ArgumentOutOfRangeException(nameof(assetID));
                }

                return((int)PXAccess.GetParentOrganizationID(asset.BranchID));
            }
        }
        public virtual void GenerateProc(Schedule schedule, short times, DateTime runDate)
        {
            string lastBatchNbr = "0000000000";
            long   lastInfoID   = -1;

            IEnumerable <ScheduleDet> occurrences = new Scheduler(this).MakeSchedule(schedule, times, runDate);

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (ScheduleDet occurrence in occurrences)
                {
                    foreach (BatchNew scheduledBatch in PXSelect <
                                 BatchNew,
                                 Where <
                                     BatchNew.scheduleID, Equal <Optional <Schedule.scheduleID> >,
                                     And <BatchNew.scheduled, Equal <boolTrue> > > >
                             .Select(this, schedule.ScheduleID))
                    {
                        BatchNew copy = PXCache <BatchNew> .CreateCopy(scheduledBatch);

                        copy.OrigBatchNbr = copy.BatchNbr;
                        copy.OrigModule   = copy.Module;
                        copy.CuryInfoID   = null;
                        copy.NumberCode   = "GLREC";
                        copy.NoteID       = null;

                        CurrencyInfo info = (CurrencyInfo)PXSelect <
                            CurrencyInfo,
                            Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > >
                                            .Select(this, scheduledBatch.CuryInfoID);

                        if (info != null)
                        {
                            CurrencyInfo infocopy = PXCache <CurrencyInfo> .CreateCopy(info);

                            infocopy.CuryInfoID = lastInfoID;
                            copy.CuryInfoID     = lastInfoID;

                            CuryInfo_Created.Cache.Insert(infocopy);
                        }

                        copy.Posted          = false;
                        copy.Released        = false;
                        copy.Status          = BatchStatus.Balanced;
                        copy.Scheduled       = false;
                        copy.AutoReverseCopy = false;

                        copy.DateEntered = occurrence.ScheduledDate;

                        FinPeriod finPeriod =
                            FinPeriodRepository.GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(copy.BranchID), occurrence.ScheduledPeriod)
                            .GetValueOrRaiseError();
                        copy.FinPeriodID  = finPeriod.FinPeriodID;
                        copy.TranPeriodID = null;

                        copy.BatchNbr    = lastBatchNbr;
                        copy.RefBatchNbr = lastBatchNbr;

                        lastBatchNbr = AutoNumberAttribute.NextNumber(lastBatchNbr);
                        lastInfoID--;

                        copy = (BatchNew)Batch_Created.Cache.Insert(copy);

                        CurrencyInfoAttribute.SetEffectiveDate <Batch.dateEntered>(Batch_Created.Cache, new PXFieldUpdatedEventArgs(copy, null, false));
                        PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(BatchNew)], scheduledBatch, Batch_Created.Cache, copy);

                        foreach (GLTranNew scheduledBatchTransaction in PXSelect <
                                     GLTranNew,
                                     Where <
                                         GLTranNew.module, Equal <Required <GLTranNew.module> >,
                                         And <GLTranNew.batchNbr, Equal <Required <GLTranNew.batchNbr> > > > >
                                 .Select(this, scheduledBatch.Module, scheduledBatch.BatchNbr))
                        {
                            GLTranNew transactionCopy = PXCache <GLTranNew> .CreateCopy(scheduledBatchTransaction);

                            transactionCopy.OrigBatchNbr = transactionCopy.BatchNbr;
                            transactionCopy.OrigModule   = transactionCopy.Module;
                            transactionCopy.BatchNbr     = copy.BatchNbr;
                            transactionCopy.RefBatchNbr  = copy.RefBatchNbr;
                            transactionCopy.CuryInfoID   = copy.CuryInfoID;
                            transactionCopy.CATranID     = null;
                            transactionCopy.NoteID       = null;

                            transactionCopy.TranDate = occurrence.ScheduledDate;
                            FinPeriodIDAttribute.SetPeriodsByMaster <GLTranNew.finPeriodID>(Tran_Created.Cache, transactionCopy, occurrence.ScheduledPeriod);

                            transactionCopy = Tran_Created.Cache.Insert(transactionCopy) as GLTranNew;
                            PXNoteAttribute.CopyNoteAndFiles(Tran_Created.Cache, scheduledBatchTransaction, Tran_Created.Cache, transactionCopy);
                        }
                    }

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

                Running_Schedule.Cache.Persist(PXDBOperation.Update);

                Batch_Created.Cache.Persist(PXDBOperation.Insert);
                Batch_Created.Cache.Persist(PXDBOperation.Update);

                foreach (GLTranNew createdTransaction in Tran_Created.Cache.Inserted)
                {
                    foreach (BatchNew createdBatch in Batch_Created.Cache.Cached)
                    {
                        if (object.Equals(createdBatch.RefBatchNbr, createdTransaction.RefBatchNbr))
                        {
                            createdTransaction.BatchNbr   = createdBatch.BatchNbr;
                            createdTransaction.CuryInfoID = createdBatch.CuryInfoID;

                            if (!string.IsNullOrEmpty(createdBatch.RefNbr))
                            {
                                createdTransaction.RefNbr = createdBatch.RefNbr;
                            }

                            break;
                        }
                    }
                }

                Tran_Created.Cache.Normalize();

                Tran_Created.Cache.Persist(PXDBOperation.Insert);
                Tran_Created.Cache.Persist(PXDBOperation.Update);
                Caches[typeof(CA.CADailySummary)].Persist(PXDBOperation.Insert);

                ts.Complete(this);
            }

            Running_Schedule.Cache.Persisted(false);
            Batch_Created.Cache.Persisted(false);
            Tran_Created.Cache.Persisted(false);
            Caches[typeof(CA.CADailySummary)].Persisted(false);
        }
Exemple #27
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);
        }
Exemple #28
0
        protected IEnumerable orgFinYear()
        {
            if (PXView.NeedDefaultPrimaryViewObject)
            {
                OrganizationFinYear defaultYear = PXSelect <
                    OrganizationFinYear,
                    Where <OrganizationFinYear.organizationID, Equal <Required <OrganizationFinYear.organizationID> > >,
                    OrderBy <
                        Desc <OrganizationFinYear.year> > >
                                                  .SelectSingleBound(this, new object[] { }, PXAccess.GetParentOrganizationID(Accessinfo.BranchID));

                return(new object[] { defaultYear });
            }
            else
            {
                // standard data member select
                return(null);
            }
        }
 public object GetParentOrganizationID(object branchID)
 {
     return(PXAccess.GetParentOrganizationID((int?)branchID));
 }
        public void Revalue(RevalueFilter filter, List <RevaluedGLHistory> list)
        {
            JournalEntry je        = PXGraph.CreateInstance <JournalEntry>();
            PostGraph    pg        = PXGraph.CreateInstance <PostGraph>();
            PXCache      basecache = je.Caches[typeof(AcctHist)];

            je.Views.Caches.Add(typeof(AcctHist));

            string extRefNbrNumbering = je.CMSetup.Current.ExtRefNbrNumberingID;

            if (string.IsNullOrEmpty(extRefNbrNumbering) == false)
            {
                RevaluationRefNbrHelper helper = new RevaluationRefNbrHelper(extRefNbrNumbering);
                helper.Subscribe(je);
            }

            DocumentList <Batch> created = new DocumentList <Batch>(je);

            Currency currency = PXSelect <Currency, Where <Currency.curyID, Equal <Required <Currency.curyID> > > > .Select(je, filter.CuryID);

            bool hasErrors = false;

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (RevaluedGLHistory hist in list)
                {
                    PXProcessing <RevaluedGLHistory> .SetCurrentItem(hist);

                    if (hist.FinPtdRevalued == 0m)
                    {
                        PXProcessing <RevaluedGLHistory> .SetProcessed();

                        continue;
                    }

                    string FinPeriod =
                        FinPeriodRepository.GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(hist.BranchID), filter.FinPeriodID)
                        .Result
                        .FinPeriodID;

                    ProcessingResult result = CheckFinPeriod(FinPeriod, hist.BranchID);
                    if (!result.IsSuccess)
                    {
                        hasErrors = true;
                        continue;
                    }

                    if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                    {
                        je.Save.Press();

                        if (created.Find(je.BatchModule.Current) == null)
                        {
                            created.Add(je.BatchModule.Current);
                        }
                    }

                    Batch cmbatch = created.Find <Batch.branchID>(hist.BranchID) ?? new Batch();
                    if (cmbatch.BatchNbr == null)
                    {
                        je.Clear();

                        CurrencyInfo info = new CurrencyInfo();
                        info.CuryID      = hist.CuryID;
                        info.CuryEffDate = hist.CuryEffDate;
                        info.BaseCalc    = false;
                        info             = je.currencyinfo.Insert(info) ?? info;

                        cmbatch             = new Batch();
                        cmbatch.BranchID    = hist.BranchID;
                        cmbatch.Module      = "CM";
                        cmbatch.Status      = "U";
                        cmbatch.AutoReverse = false;
                        cmbatch.Released    = true;
                        cmbatch.Hold        = false;
                        cmbatch.DateEntered = filter.CuryEffDate;
                        FinPeriodIDAttribute.SetPeriodsByMaster <Batch.finPeriodID>(je.BatchModule.Cache, cmbatch, filter.FinPeriodID);

                        cmbatch.CuryID      = hist.CuryID;
                        cmbatch.CuryInfoID  = info.CuryInfoID;
                        cmbatch.DebitTotal  = 0m;
                        cmbatch.CreditTotal = 0m;
                        cmbatch.Description = filter.Description;
                        je.BatchModule.Insert(cmbatch);

                        CurrencyInfo b_info = je.currencyinfo.Select();
                        if (b_info != null)
                        {
                            b_info.CuryID         = hist.CuryID;
                            b_info.CuryEffDate    = hist.CuryEffDate;
                            b_info.CuryRateTypeID = hist.CuryRateTypeID;
                            b_info.CuryRate       = hist.CuryRate;
                            b_info.RecipRate      = hist.RateReciprocal;
                            b_info.CuryMultDiv    = hist.CuryMultDiv;
                            je.currencyinfo.Update(b_info);
                        }
                    }
                    else
                    {
                        if (!je.BatchModule.Cache.ObjectsEqual(je.BatchModule.Current, cmbatch))
                        {
                            je.Clear();
                        }

                        je.BatchModule.Current = je.BatchModule.Search <Batch.batchNbr>(cmbatch.BatchNbr, cmbatch.Module);
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = false;
                        tran.AccountID     = hist.AccountID;
                        tran.SubID         = hist.SubID;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        if (hist.AccountType == AccountType.Asset || hist.AccountType == AccountType.Expense)
                        {
                            tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;
                            tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;
                        }
                        else
                        {
                            tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;
                            tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;
                        }

                        tran.TranType  = "REV";
                        tran.TranClass = hist.AccountType;
                        tran.RefNbr    = string.Empty;
                        tran.TranDesc  = filter.Description;
                        FinPeriodIDAttribute.SetPeriodsByMaster <GLTran.finPeriodID>(je.GLTranModuleBatNbr.Cache, tran, filter.FinPeriodID);
                        tran.TranDate    = filter.CuryEffDate;
                        tran.CuryInfoID  = null;
                        tran.Released    = true;
                        tran.ReferenceID = null;
                        tran.ProjectID   = PM.ProjectDefaultAttribute.NonProject();

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    foreach (GLTran tran in je.GLTranModuleBatNbr.SearchAll <Asc <GLTran.tranClass> >(new object[] { "G" }))
                    {
                        je.GLTranModuleBatNbr.Delete(tran);
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = true;
                        tran.ZeroPost      = false;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        if (je.BatchModule.Current.DebitTotal > je.BatchModule.Current.CreditTotal)
                        {
                            tran.AccountID = currency.RevalGainAcctID;
                            tran.SubID     = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalGainSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = 0m;
                            tran.CreditAmt = (je.BatchModule.Current.DebitTotal - je.BatchModule.Current.CreditTotal);
                        }
                        else
                        {
                            tran.AccountID = currency.RevalLossAcctID;
                            tran.SubID     = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalLossSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = (je.BatchModule.Current.CreditTotal - je.BatchModule.Current.DebitTotal);
                            tran.CreditAmt = 0m;
                        }

                        tran.TranType    = "REV";
                        tran.TranClass   = GLTran.tranClass.UnrealizedAndRevaluationGOL;
                        tran.RefNbr      = string.Empty;
                        tran.TranDesc    = filter.Description;
                        tran.Released    = true;
                        tran.ReferenceID = null;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    {
                        AcctHist accthist = new AcctHist();
                        accthist.BranchID    = hist.BranchID;
                        accthist.LedgerID    = hist.LedgerID;
                        accthist.AccountID   = hist.AccountID;
                        accthist.SubID       = hist.SubID;
                        accthist.FinPeriodID = filter.FinPeriodID;
                        accthist.CuryID      = hist.CuryID;
                        accthist.BalanceType = "A";

                        accthist = (AcctHist)basecache.Insert(accthist);
                        accthist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    PXProcessing <RevaluedGLHistory> .SetProcessed();
                }

                if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                {
                    je.Save.Press();

                    if (created.Find(je.BatchModule.Current) == null)
                    {
                        created.Add(je.BatchModule.Current);
                    }
                }

                ts.Complete();
            }

            CMSetup cmsetup = PXSelect <CMSetup> .Select(je);

            for (int i = 0; i < created.Count; i++)
            {
                if (cmsetup.AutoPostOption == true)
                {
                    pg.Clear();
                    pg.PostBatchProc(created[i]);
                }
            }

            if (hasErrors)
            {
                //Clean current to prevent set exception to the last item
                PXProcessing <RevaluedGLHistory> .SetCurrentItem(null);

                throw new PXException(ErrorMessages.SeveralItemsFailed);
            }

            if (created.Count > 0)
            {
                je.BatchModule.Current = created[created.Count - 1];
                throw new PXRedirectRequiredException(je, "Preview");
            }

            decimal val = 0m;

            foreach (RevaluedGLHistory res in GLAccountList.Cache.Updated)
            {
                if ((bool)res.Selected)
                {
                    decimal sign = AccountRules.IsDEALAccount(res.AccountType) ? 1.0m : -1.0m;
                    val += sign * (decimal)res.FinPtdRevalued;
                }
            }

            if (val == 0)
            {
                throw new PXOperationCompletedWithWarningException(Messages.NoRevaluationEntryWasMade);
            }
        }