Esempio n. 1
0
        public static void RaiseRowPersistingException <Field>(PXCache cache, object row)
            where Field : IBqlField
        {
            var fieldName = typeof(Field).Name;

            cache.RaiseExceptionHandling <Field>(row,
                                                 null,
                                                 new PXSetPropertyException(PXMessages.LocalizeFormatNoPrefix(ErrorMessages.FieldIsEmpty, fieldName)));

            throw new PXRowPersistingException(fieldName, null, ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <Field>(cache));
        }
        protected virtual void EPExpenseClaimDetails_CuryEmployeePart_FieldVerifying(PXCache cache, PXFieldVerifyingEventArgs e)
        {
            Decimal?newVal = e.NewValue as Decimal?;

            if (newVal < 0)
            {
                throw new PXSetPropertyException(CS.Messages.FieldShouldNotBeNegative, PXUIFieldAttribute.GetDisplayName <EPExpenseClaimDetails.curyEmployeePart>(cache));
            }
        }
Esempio n. 3
0
        public TransferProcess()
        {
            FASetup setup = fasetup.Current;

            if (fasetup.Current.UpdateGL != true)
            {
                throw new PXSetupNotEnteredException <FASetup>(Messages.OperationNotWorkInInitMode, PXUIFieldAttribute.GetDisplayName <FASetup.updateGL>(fasetup.Cache));
            }

            PXUIFieldAttribute.SetDisplayName <Account.accountClassID>(Caches[typeof(Account)], Messages.FixedAssetsAccountClass);

            if (fasetup.Current.AutoReleaseTransfer != true)
            {
                Assets.SetProcessCaption(Messages.Prepare);
                Assets.SetProcessAllCaption(Messages.PrepareAll);
            }
        }
Esempio n. 4
0
            public override void CacheAttached(PXCache sender)
            {
                base.CacheAttached(sender);
                this.viewEmployees = new PXView(sender.Graph, true,
                                                BqlCommand.CreateInstance(
                                                    typeof(Search5 <BAccountR.bAccountID,
                                                                    InnerJoin <CREmployee, On <CREmployee.bAccountID, Equal <BAccountR.bAccountID> >,
                                                                               LeftJoin <Contact, On <Contact.bAccountID, Equal <CREmployee.parentBAccountID>,
                                                                                                      And <Contact.contactID, Equal <CREmployee.defContactID> > >,
                                                                                         LeftJoin <Address, On <Address.bAccountID, Equal <CREmployee.parentBAccountID>,
                                                                                                                And <Address.addressID, Equal <CREmployee.defAddressID> > >,
                                                                                                   LeftJoin <EPCompanyTreeMember, On <EPCompanyTreeMember.userID, Equal <CREmployee.userID> > > > > >,
                                                                    Where <CREmployee.userID, Equal <Current <AccessInfo.userID> >,
                                                                           Or <EPCompanyTreeMember.workGroupID, Owned <Current <AccessInfo.userID> > > >,
                                                                    Aggregate <GroupBy <BAccountR.bAccountID> > >)));

                this.viewCustomers = new PXView(sender.Graph, true,
                                                BqlCommand.CreateInstance(typeof(Search2 <BAccountR.bAccountID,
                                                                                          InnerJoin <Customer, On <Customer.bAccountID, Equal <BAccountR.bAccountID> >,
                                                                                                     LeftJoin <Contact, On <Contact.bAccountID, Equal <Customer.bAccountID>,
                                                                                                                            And <Contact.contactID, Equal <Customer.defContactID> > >,
                                                                                                               LeftJoin <Address, On <Address.bAccountID, Equal <Customer.bAccountID>,
                                                                                                                                      And <Address.addressID, Equal <Customer.defAddressID> > > > > >,
                                                                                          Where <Match <Customer, Current <AccessInfo.userName> > > >)));

                this.viewClass = new PXView(sender.Graph, true,
                                            BqlCommand.CreateInstance(
                                                BqlCommand.Compose(
                                                    typeof(Search <,>), typeof(RQRequestClass.reqClassID),
                                                    typeof(Where <,>), typeof(RQRequestClass.reqClassID), typeof(Equal <>), typeof(Optional <>), reqClassID ?? typeof(RQRequestClass.reqClassID))));

                if (this.reqClassID != null)
                {
                    sender.Graph.FieldUpdated.AddHandler(BqlCommand.GetItemType(reqClassID), reqClassID.Name,
                                                         ReqClassFieldUpdated);
                }
                PXUIFieldAttribute.SetDisplayName <BAccountR.acctCD>(sender.Graph.Caches[typeof(BAccountR)], Messages.Requester);
                PXUIFieldAttribute.SetDisplayName <BAccountR.acctName>(sender.Graph.Caches[typeof(BAccountR)], Messages.RequesterName);
                Type[] _fields = new Type[]
                {
                    typeof(BAccountR.acctCD),
                    typeof(BAccountR.acctName),
                    typeof(BAccountR.status),
                    typeof(Contact.phone1),
                    typeof(Address.city),
                    typeof(Address.countryID)
                };
                string[] selFields  = new string[_fields.Length];
                string[] selHeaders = new string[_fields.Length];
                for (int i = 0; i < _fields.Length; i++)
                {
                    Type    field     = _fields[i];
                    Type    cacheType = BqlCommand.GetItemType(field);
                    PXCache cache     = sender.Graph.Caches[cacheType];

                    if (cacheType.IsAssignableFrom(typeof(BAccountR)) ||
                        field.Name == typeof(BAccountR.acctCD).Name ||
                        field.Name == typeof(BAccountR.acctName).Name)
                    {
                        selFields[i] = field.Name;
                    }
                    else
                    {
                        selFields[i] = cacheType.Name + "__" + field.Name;
                    }
                    selHeaders[i] = PXUIFieldAttribute.GetDisplayName(cache, field.Name);
                }
                PXSelectorAttribute.SetColumns(sender, _FieldName, selFields, selHeaders);
            }
Esempio n. 5
0
        protected virtual void EPGenerateWeeksDialog_FromDate_FieldVerifying(PXCache cache, PXFieldVerifyingEventArgs e)
        {
            EPGenerateWeeksDialog row = (EPGenerateWeeksDialog)e.Row;

            if (e.NewValue == null || row == null)
            {
                return;
            }
            if ((DateTime)e.NewValue > row.TillDate)
            {
                e.Cancel = true;
                throw new PXSetPropertyException(ErrorMessages.StartDateGreaterThanEndDate, PXUIFieldAttribute.GetDisplayName <EPGenerateWeeksDialog.fromDate>(cache), PXUIFieldAttribute.GetDisplayName <EPGenerateWeeksDialog.tillDate>(cache), row.FromDate);
            }
            DateTime?    firstUsingDate = GetFirstUsingWeek();
            EPCustomWeek lastWeek       = (EPCustomWeek)PXSelectOrderBy <EPCustomWeek, OrderBy <Desc <EPCustomWeek.weekID> > > .SelectSingleBound(this, null);

            if (firstUsingDate != null && (DateTime)e.NewValue > firstUsingDate && lastWeek == null)
            {
                e.Cancel = true;
                throw new PXSetPropertyException(Messages.ExistsActivitiesGreateThanDate, PXUIFieldAttribute.GetDisplayName <EPGenerateWeeksDialog.fromDate>(cache), firstUsingDate);
            }
        }
Esempio n. 6
0
 public override void Persist()
 {
     foreach (APVendorPrice price in Records.Cache.Inserted)
     {
         APVendorPrice lastPrice = FindLastPrice(this, price);
         if (lastPrice != null)
         {
             if (lastPrice.EffectiveDate > price.EffectiveDate && price.ExpirationDate == null)
             {
                 Records.Cache.RaiseExceptionHandling <APVendorPrice.expirationDate>(price, price.ExpirationDate, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <APVendorPrice.expirationDate>(Records.Cache)));
                 throw new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <APVendorPrice.expirationDate>(Records.Cache));
             }
         }
         ValidateDuplicate(this, Records.Cache, price);
     }
     foreach (APVendorPrice price in Records.Cache.Updated)
     {
         APVendorPrice lastPrice = FindLastPrice(this, price);
         if (lastPrice != null)
         {
             if (lastPrice.EffectiveDate > price.EffectiveDate && price.ExpirationDate == null)
             {
                 Records.Cache.RaiseExceptionHandling <APVendorPrice.expirationDate>(price, price.ExpirationDate, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <APVendorPrice.expirationDate>(Records.Cache)));
                 throw new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <APVendorPrice.expirationDate>(Records.Cache));
             }
         }
         ValidateDuplicate(this, Records.Cache, price);
     }
     base.Persist();
     Records.Cache.Clear();
 }
Esempio n. 7
0
        public DisposalProcess()
        {
            fasetup.Current = null;
            FASetup setup = fasetup.Current;

            if (fasetup.Current.UpdateGL != true)
            {
                throw new PXSetupNotEnteredException <FASetup>(Messages.OperationNotWorkInInitMode, PXUIFieldAttribute.GetDisplayName <FASetup.updateGL>(fasetup.Cache));
            }

            PXUIFieldAttribute.SetDisplayName <FADetails.receiptDate>(Caches[typeof(FADetails)], Messages.AcquiredDate);
            PXUIFieldAttribute.SetDisplayName <Account.accountClassID>(Caches[typeof(Account)], Messages.FixedAssetsAccountClass);

            if (fasetup.Current.AutoReleaseDisp != true)
            {
                Assets.SetProcessCaption(Messages.Prepare);
                Assets.SetProcessAllCaption(Messages.PrepareAll);
            }
        }
Esempio n. 8
0
        protected virtual void EPCustomWeek_EndDate_FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
        {
            EPCustomWeek row = (EPCustomWeek)e.Row;

            if (row == null || e.NewValue == null || row.StartDate == null)
            {
                return;
            }
            if (((DateTime)e.NewValue).Subtract(row.StartDate.Value).TotalDays > 7d)
            {
                sender.RaiseExceptionHandling <EPCustomWeek.endDate>(e.Row, null, new PXException(Messages.StartDateGreaterThanEndDate, PXUIFieldAttribute.GetDisplayName <EPCustomWeek.endDate>(sender), row.StartDate.Value.AddDays(6d)));
                e.NewValue = null;
                e.Cancel   = true;
            }
        }
        /// <summary>
        /// Validates the CalendarWeekCodeGeneration.startDate value.
        /// </summary>
        /// <param name="calendarWeekCodeGenrationRow">CalendarWeekCodeGeneration Row.</param>
        /// <param name="cache">Cache of the View.</param>
        /// <returns>true: valid value | false: invalid value.</returns>
        public virtual bool ValidateStartGenerationDate(CalendarWeekCodeGeneration calendarWeekCodeGenrationRow, PXCache cache)
        {
            bool isValid = true;

            if (calendarWeekCodeGenrationRow.StartDate == null)
            {
                cache.RaiseExceptionHandling <CalendarWeekCodeGeneration.startDate>(calendarWeekCodeGenrationRow,
                                                                                    calendarWeekCodeGenrationRow.StartDate,
                                                                                    new PXException(PXMessages.LocalizeFormatNoPrefix(TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                                                                                                                                      PXUIFieldAttribute.GetDisplayName <CalendarWeekCodeGeneration.endDate>(cache))));

                isValid = false;
            }
            else
            {
                if (calendarWeekCodeGenrationRow.StartDate < calendarWeekCodeGenrationRow.DefaultStartDate)
                {
                    cache.RaiseExceptionHandling <CalendarWeekCodeGeneration.startDate>(calendarWeekCodeGenrationRow,
                                                                                        calendarWeekCodeGenrationRow.StartDate,
                                                                                        new PXException(TX.Error.START_DATE_LESSER_THAN_DEFAULT_DATE));
                    isValid = false;
                }
            }

            return(isValid);
        }
Esempio n. 10
0
        public static void CreatePPDCreditMemos(PXCache cache, ARPPDCreditMemoParameters filter, ARSetup setup, List <PendingPPDCreditMemoApp> docs)
        {
            int  i      = 0;
            bool failed = false;

            List <ARRegister> toRelease = new List <ARRegister>();
            ARInvoiceEntry    ie        = PXGraph.CreateInstance <ARInvoiceEntry>();

            ie.ARSetup.Current = setup;

            if (filter.GenerateOnePerCustomer == true)
            {
                if (filter.CreditMemoDate == null)
                {
                    throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat,
                                                     PXUIFieldAttribute.GetDisplayName <ARPPDCreditMemoParameters.creditMemoDate>(cache));
                }

                if (filter.FinPeriodID == null)
                {
                    throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat,
                                                     PXUIFieldAttribute.GetDisplayName <ARPPDCreditMemoParameters.finPeriodID>(cache));
                }

                Dictionary <PPDApplicationKey, List <PendingPPDCreditMemoApp> > dict = new Dictionary <PPDApplicationKey, List <PendingPPDCreditMemoApp> >();
                foreach (PendingPPDCreditMemoApp doc in docs)
                {
                    CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(ie, doc.InvCuryInfoID);

                    PPDApplicationKey key = new PPDApplicationKey();
                    doc.Index      = i++;
                    key.BranchID   = doc.AdjdBranchID;
                    key.BAccountID = doc.AdjdCustomerID;
                    key.LocationID = doc.InvCustomerLocationID;
                    key.CuryID     = info.CuryID;
                    key.CuryRate   = info.CuryRate;
                    key.AccountID  = doc.AdjdARAcct;
                    key.SubID      = doc.AdjdARSub;
                    key.TaxZoneID  = doc.InvTaxZoneID;

                    List <PendingPPDCreditMemoApp> list;
                    if (!dict.TryGetValue(key, out list))
                    {
                        dict[key] = list = new List <PendingPPDCreditMemoApp>();
                    }

                    list.Add(doc);
                }

                foreach (List <PendingPPDCreditMemoApp> list in dict.Values)
                {
                    ARInvoice invoice = CreatePPDCreditMemo(ie, filter, list);
                    if (invoice != null)
                    {
                        toRelease.Add(invoice);
                    }
                    else
                    {
                        failed = true;
                    }
                }
            }
            else
            {
                foreach (PendingPPDCreditMemoApp doc in docs)
                {
                    List <PendingPPDCreditMemoApp> list = new List <PendingPPDCreditMemoApp>(1);
                    doc.Index = i++;
                    list.Add(doc);

                    ARInvoice invoice = CreatePPDCreditMemo(ie, filter, list);
                    if (invoice != null)
                    {
                        toRelease.Add(invoice);
                    }
                    else
                    {
                        failed = true;
                    }
                }
            }

            if (setup.AutoReleasePPDCreditMemo == true && toRelease.Count > 0)
            {
                using (new PXTimeStampScope(null))
                {
                    ARDocumentRelease.ReleaseDoc(toRelease, true);
                }
            }

            if (failed)
            {
                throw new PXException(GL.Messages.DocumentsNotReleased);
            }
        }
Esempio n. 11
0
        public virtual List <APRegister> ReleaseClaimDetails
        <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>
            (ExpenseClaimEntry expenseClaimGraph, EPExpenseClaim claim, IEnumerable <EPExpenseClaimDetails> receipts, string receiptGroupPaidWithType)
            where TGraph : PXGraph, new()
            where TAPDocument : InvoiceBase, new()
            where TInvoiceMapping : IBqlMapping
            where TAPDocumentGraphExtension : PX.Objects.Common.GraphExtensions.Abstract.InvoiceBaseGraphExtension <TGraph, TAPDocument, TInvoiceMapping>
        {
            #region prepare required variable

            var docgraph = PXGraph.CreateInstance <TGraph>();

            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

            TAPDocumentGraphExtension apDocumentGraphExtension = docgraph.FindImplementation <TAPDocumentGraphExtension>();

            List <List <EPExpenseClaimDetails> > receiptsForDocument = new List <List <EPExpenseClaimDetails> >();

            if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
            {
                receiptsForDocument = receipts.GroupBy(item => new { item.TaxZoneID, item.TaxCalcMode })
                                      .Select(group => group.ToList())
                                      .ToList();
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
            {
                if (epsetup.PostSummarizedCorpCardExpenseReceipts == true)
                {
                    receiptsForDocument = receipts.GroupBy(item =>
                                                           new
                    {
                        item.TaxZoneID,
                        item.TaxCalcMode,
                        item.CorpCardID,
                        item.ExpenseDate,
                        item.ExpenseRefNbr
                    })
                                          .Select(group => group.ToList())
                                          .ToList();
                }
                else
                {
                    receiptsForDocument = receipts.Select(receipt => receipt.SingleToList()).ToList();
                }
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
            {
                receiptsForDocument = new List <List <EPExpenseClaimDetails> >()
                {
                    receipts.ToList()
                };
            }
            else
            {
                throw new NotImplementedException();
            }

            if (!receiptsForDocument.Any())
            {
                receiptsForDocument.Add(new List <EPExpenseClaimDetails>());
            }

            APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph);

            EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID);

            Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();


            if (claim.FinPeriodID != null)
            {
                FinPeriodUtils.ValidateFinPeriod(claim.SingleToArray());
            }
            #endregion

            foreach (var receiptGroup in receiptsForDocument)
            {
                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count > 1)
                {
                    EPExpenseClaimDetails[] matchedReceipts = receiptGroup.Where(receipt => receipt.BankTranDate != null).Take(11).ToArray();

                    if (matchedReceipts.Any())
                    {
                        PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran>[] rows =
                            PXSelectJoin <EPExpenseClaimDetails,
                                          InnerJoin <CABankTranMatch,
                                                     On <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                                         And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                              And <CABankTranMatch.docRefNbr, Equal <EPExpenseClaimDetails.claimDetailCD> > > >,
                                                     InnerJoin <CABankTran,
                                                                On <CABankTran.tranID, Equal <CABankTranMatch.tranID> > > >,
                                          Where <EPExpenseClaimDetails.claimDetailCD, In <Required <EPExpenseClaimDetails.claimDetailCD> > > >
                            .Select(expenseClaimGraph, matchedReceipts.Select(receipt => receipt.ClaimDetailCD).ToArray())
                            .Cast <PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran> >()
                            .ToArray();

                        throw new PXException(Messages.ExpenseReceiptCannotBeSummarized,
                                              rows.Select(row => String.Concat(PXMessages.LocalizeNoPrefix(Messages.Receipt),
                                                                               " ",
                                                                               ((EPExpenseClaimDetails)row).ClaimDetailCD,
                                                                               " - ",
                                                                               ((CABankTran)row).GetFriendlyKeyImage(Caches[typeof(CABankTran)])))
                                              .ToArray()
                                              .JoinIntoStringForMessageNoQuotes(maxCount: 10));
                    }
                }

                docgraph.Clear(PXClearOption.ClearAll);
                docgraph.SelectTimeStamp();
                apDocumentGraphExtension.Contragent.Current = apDocumentGraphExtension.Contragent.Cache.GetExtension <Contragent>(employee);
                apDocumentGraphExtension.Location.Current   = emplocation;

                CurrencyInfo infoOriginal = PXSelect <CurrencyInfo,
                                                      Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID);

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

                info.CuryInfoID = null;
                info            = apDocumentGraphExtension.CurrencyInfo.Insert(info);

                #region CreateInvoiceHeader

                var invoice = new TAPDocument();

                CABankTranMatch bankTranMatch = null;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
                {
                    invoice.DocType = receiptGroup.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0
                        ? APInvoiceType.DebitAdj
                        : APInvoiceType.Invoice;
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
                {
                    EPExpenseClaimDetails receipt = receiptGroup.First();

                    invoice.DocType = APDocType.QuickCheck;

                    CACorpCard card = CACorpCard.PKID.Find(this, receipt.CorpCardID);

                    PaymentMethodAccount paymentMethodAccount = PXSelect <PaymentMethodAccount,
                                                                          Where <PaymentMethodAccount.cashAccountID, Equal <Required <PaymentMethodAccount.cashAccountID> > > >
                                                                .Select(this, card.CashAccountID);

                    invoice.CashAccountID   = card.CashAccountID;
                    invoice.PaymentMethodID = paymentMethodAccount.PaymentMethodID;
                    invoice.ExtRefNbr       = receipt.ExpenseRefNbr;

                    if (receiptGroup.Count == 1)
                    {
                        bankTranMatch =
                            PXSelect <CABankTranMatch,
                                      Where <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                             And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                  And <CABankTranMatch.docRefNbr, Equal <Required <CABankTranMatch.docRefNbr> > > > > >
                            .Select(expenseClaimGraph, receipt.ClaimDetailCD);

                        if (bankTranMatch != null)
                        {
                            CABankTran bankTran = CABankTran.PK.Find(expenseClaimGraph, bankTranMatch.TranID);

                            invoice.ClearDate = bankTran.ClearDate;
                            invoice.Cleared   = true;
                        }
                    }
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.DocType = APDocType.DebitAdj;
                }
                else
                {
                    throw new NotImplementedException();
                }

                invoice.CuryInfoID = info.CuryInfoID;

                invoice.Hold     = true;
                invoice.Released = false;
                invoice.Printed  = invoice.DocType == APDocType.QuickCheck;
                invoice.OpenDoc  = true;

                invoice.HeaderDocDate        = claim.DocDate;
                invoice.FinPeriodID          = claim.FinPeriodID;
                invoice.InvoiceNbr           = claim.RefNbr;
                invoice.DocDesc              = claim.DocDesc;
                invoice.ContragentID         = claim.EmployeeID;
                invoice.CuryID               = info.CuryID;
                invoice.ContragentLocationID = claim.LocationID;
                invoice.ModuleAccountID      = emplocation != null ? emplocation.APAccountID : null;
                invoice.ModuleSubID          = emplocation != null ? emplocation.APSubID : null;
                invoice.TaxCalcMode          = receiptGroup.Any() ? receiptGroup.First().TaxCalcMode: claim.TaxCalcMode;
                invoice.BranchID             = claim.BranchID;
                invoice.OrigModule           = BatchModule.EP;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1)
                {
                    invoice.OrigDocType = EPExpenseClaimDetails.DocType;
                    invoice.OrigRefNbr  = receiptGroup.Single().ClaimDetailCD;
                }
                else
                {
                    invoice.OrigDocType = EPExpenseClaim.DocType;
                    invoice.OrigRefNbr  = claim.RefNbr;
                }

                bool reversedDocument = invoice.DocType == APInvoiceType.DebitAdj && receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount;

                decimal signOperation = reversedDocument ? -1 : 1;

                invoice = apDocumentGraphExtension.Documents.Insert(invoice);
                (apDocumentGraphExtension.Documents.Cache as PXModelExtension <TAPDocument>)?.UpdateExtensionMapping(invoice, MappingSyncDirection.BaseToExtension);

                invoice.TaxZoneID = receiptGroup.Any() ? receiptGroup.First().TaxZoneID : claim.TaxZoneID;

                invoice = apDocumentGraphExtension.Documents.Update(invoice);

                PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                info.CuryInfoID = invoice.CuryInfoID;

                PXCache claimcache       = docgraph.Caches[typeof(EPExpenseClaim)];
                PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)];

                PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, apDocumentGraphExtension.Documents.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                #endregion

                TaxAttribute.SetTaxCalc <InvoiceTran.taxCategoryID>(apDocumentGraphExtension.InvoiceTrans.Cache, null, TaxCalc.ManualCalc);

                decimal?claimCuryTaxRoundDiff = 0m;
                decimal?claimTaxRoundDiff     = 0m;
                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    #region AddDetails

                    decimal tipQty;
                    if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                    {
                        tipQty = 1;
                    }
                    else
                    {
                        tipQty = -1;
                    }
                    Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

                    if (claimdetail.TaskID != null)
                    {
                        PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, claimdetail.TaskID);

                        if (task != null && !(bool)task.VisibleInAP)
                        {
                            throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP);
                        }
                    }

                    InvoiceTran tran = new InvoiceTran();
                    tran.InventoryID = claimdetail.InventoryID;
                    tran.TranDesc    = claimdetail.TranDesc;
                    decimal unitCost;
                    decimal amount;
                    decimal taxableAmt;
                    decimal taxAmt;
                    if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                    {
                        unitCost   = claimdetail.CuryUnitCost ?? 0m;
                        amount     = claimdetail.CuryTaxableAmt ?? 0m;
                        taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                        taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                    }
                    else
                    {
                        if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                        {
                            unitCost = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                        }
                        if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                        {
                            amount = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                        }
                        if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                        {
                            taxableAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                        }
                        if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                        {
                            taxAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                        }
                    }

                    tran.ManualPrice       = true;
                    tran.CuryUnitCost      = unitCost;
                    tran.Qty               = claimdetail.Qty * signOperation;
                    tran.UOM               = claimdetail.UOM;
                    tran.NonBillable       = claimdetail.Billable != true;
                    claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                    claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                    tran.Date              = claimdetail.ExpenseDate;

                    if (contract.BaseType == CT.CTPRType.Project)
                    {
                        tran.ProjectID = claimdetail.ContractID;
                    }
                    else
                    {
                        tran.ProjectID = ProjectDefaultAttribute.NonProject();
                    }

                    tran.TaskID     = claimdetail.TaskID;
                    tran.CostCodeID = claimdetail.CostCodeID;

                    if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        CACorpCard  card        = CACorpCard.PKID.Find(this, claimdetail.CorpCardID);
                        CashAccount cashAccount = CashAccount.PK.Find(this, card.CashAccountID);

                        tran.AccountID = cashAccount.AccountID;
                        tran.SubID     = cashAccount.SubID;
                    }
                    else
                    {
                        tran.AccountID = claimdetail.ExpenseAccountID;
                        tran.SubID     = claimdetail.ExpenseSubID;
                    }

                    tran.BranchID = claimdetail.BranchID;


                    tran = InsertInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });

                    if (claimdetail.PaidWith == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        claimdetail.APLineNbr = tran.LineNbr;
                    }

                    tran.CuryLineAmt    = amount * signOperation;
                    tran.CuryTaxAmt     = 0;
                    tran.CuryTaxableAmt = taxableAmt * signOperation;
                    tran.CuryTaxAmt     = taxAmt * signOperation;
                    tran.TaxCategoryID  = claimdetail.TaxCategoryID;


                    tran = UpdateInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });


                    if ((claimdetail.CuryTipAmt ?? 0) != 0)
                    {
                        InvoiceTran tranTip = new InvoiceTran();
                        if (epsetup.NonTaxableTipItem == null)
                        {
                            throw new PXException(Messages.TipItemIsNotDefined);
                        }
                        IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                             Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                        if (tipItem == null)
                        {
                            string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                            throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                        }
                        tranTip.InventoryID = epsetup.NonTaxableTipItem;
                        tranTip.TranDesc    = tipItem.Descr;
                        if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                            tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                        }
                        else
                        {
                            decimal tipAmt;
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                            tranTip.CuryUnitCost = Math.Abs(tipAmt);
                            tranTip.CuryTranAmt  = tipAmt * signOperation;
                        }
                        tranTip.Qty         = tipQty;
                        tranTip.UOM         = tipItem.BaseUnit;
                        tranTip.NonBillable = claimdetail.Billable != true;
                        tranTip.Date        = claimdetail.ExpenseDate;

                        tranTip.BranchID = claimdetail.BranchID;

                        tranTip = InsertInvoiceTipTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                              new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });


                        if (epsetup.UseReceiptAccountForTips == true)
                        {
                            tranTip.AccountID = claimdetail.ExpenseAccountID;
                            tranTip.SubID     = claimdetail.ExpenseSubID;
                        }
                        else
                        {
                            tranTip.AccountID = tipItem.COGSAcctID;
                            Location companyloc = (Location)PXSelectJoin <Location,
                                                                          InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                    And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                     InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                          Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                            PMTask task = PXSelect <PMTask,
                                                    Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                           And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                            Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                            int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                            int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                            int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                            int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                            int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                            int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                            object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                    new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                    new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                            docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                            tranTip.SubID = (int?)value;
                        }

                        tranTip = UpdateInvoiceTipTransactionAccounts(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                      new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });

                        tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                        tranTip.ProjectID     = tran.ProjectID;
                        tranTip.TaskID        = tran.TaskID;
                        tranTip = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tranTip, true);


                        tranTip = UpdateInvoiceTipTransactionTaxesAndProject(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                             new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });
                    }

                    PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, apDocumentGraphExtension.InvoiceTrans.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    claimdetail.Released = true;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    #endregion

                    if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        tran = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tran, false);
                    }
                }

                #region legacy taxes
                foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                 Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                {
                    #region Add taxes
                    GenericTaxTran new_aptax = apDocumentGraphExtension.TaxTrans.Search <GenericTaxTran.taxID>(tax.TaxID);

                    if (new_aptax == null)
                    {
                        new_aptax       = new GenericTaxTran();
                        new_aptax.TaxID = tax.TaxID;
                        new_aptax       = apDocumentGraphExtension.TaxTrans.Insert(new_aptax);
                        if (new_aptax != null)
                        {
                            new_aptax = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                            new_aptax.CuryTaxableAmt = 0m;
                            new_aptax.CuryTaxAmt     = 0m;
                            new_aptax.CuryExpenseAmt = 0m;
                            new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                        }
                    }

                    if (new_aptax != null)
                    {
                        new_aptax                = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                        new_aptax.TaxRate        = tax.TaxRate;
                        new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                        new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                        new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                        new_aptax                = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                    }
                    #endregion
                }
                #endregion

                invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                invoice.Hold           = false;
                apDocumentGraphExtension.SuppressApproval();
                apDocumentGraphExtension.Documents.Update(invoice);

                if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (InvoiceTran line in apDocumentGraphExtension.InvoiceTrans.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }
                }

                invoice = apDocumentGraphExtension.Documents.Update(invoice);
                docgraph.Actions.PressSave();

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1 &&
                    bankTranMatch != null)
                {
                    CABankTransactionsMaint.RematchFromExpenseReceipt(this, bankTranMatch, invoice.CATranID, invoice.ContragentID, receiptGroup.Single());
                }

                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    claimdetail.APDocType = invoice.DocType;
                    claimdetail.APRefNbr  = invoice.RefNbr;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                }

                claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                claim.Released = true;

                expenseClaimGraph.ExpenseClaim.Update(claim);


                #region EP History Update
                EPHistory hist = new EPHistory();
                hist.EmployeeID  = invoice.ContragentID;
                hist.FinPeriodID = invoice.FinPeriodID;
                hist             = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(hist);

                hist.FinPtdClaimed += invoice.DocBal;
                hist.FinYtdClaimed += invoice.DocBal;
                if (invoice.FinPeriodID == invoice.HeaderTranPeriodID)
                {
                    hist.TranPtdClaimed += invoice.DocBal;
                    hist.TranYtdClaimed += invoice.DocBal;
                }
                else
                {
                    EPHistory tranhist = new EPHistory();
                    tranhist.EmployeeID      = invoice.ContragentID;
                    tranhist.FinPeriodID     = invoice.HeaderTranPeriodID;
                    tranhist                 = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist);
                    tranhist.TranPtdClaimed += invoice.DocBal;
                    tranhist.TranYtdClaimed += invoice.DocBal;
                }
                expenseClaimGraph.Views.Caches.Add(typeof(EPHistory));
                #endregion

                expenseClaimGraph.Save.Press();

                Actions.PressSave();

                doclist.Add((APRegister)apDocumentGraphExtension.Documents.Current.Base);
            }

            return(doclist);
        }
        protected virtual void EPEarningType_IsActive_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            EPEarningType row = e.Row as EPEarningType;

            if (row == null)
            {
                return;
            }

            if (row.IsActive == false)
            {
                if (Setup.Current.RegularHoursType == row.TypeCD)
                {
                    throw new PXException(String.Format(EP.Messages.EarningTypeDeactivate, row.TypeCD, PXUIFieldAttribute.GetDisplayName <EPSetup.regularHoursType>(Setup.Cache)));
                }
                if (Setup.Current.HolidaysType == row.TypeCD)
                {
                    throw new PXException(String.Format(EP.Messages.EarningTypeDeactivate, row.TypeCD, PXUIFieldAttribute.GetDisplayName <EPSetup.holidaysType>(Setup.Cache)));
                }
                if (Setup.Current.VacationsType == row.TypeCD)
                {
                    throw new PXException(String.Format(EP.Messages.EarningTypeDeactivate, row.TypeCD, PXUIFieldAttribute.GetDisplayName <EPSetup.vacationsType>(Setup.Cache)));
                }
            }
        }
Esempio n. 13
0
        public static void CreatePPDDebitAdjs(PXCache cache, APPPDDebitAdjParameters filter, APSetup setup, List <PendingPPDDebitAdjApp> docs)
        {
            int            i      = 0;
            bool           failed = false;
            APInvoiceEntry ie     = PXGraph.CreateInstance <APInvoiceEntry>();

            ie.APSetup.Current = setup;

            if (filter.GenerateOnePerVendor == true)
            {
                if (filter.DebitAdjDate == null)
                {
                    throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat,
                                                     PXUIFieldAttribute.GetDisplayName <APPPDDebitAdjParameters.debitAdjDate>(cache));
                }

                if (filter.FinPeriodID == null)
                {
                    throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat,
                                                     PXUIFieldAttribute.GetDisplayName <APPPDDebitAdjParameters.finPeriodID>(cache));
                }

                Dictionary <PPDApplicationKey, List <PendingPPDDebitAdjApp> > dict = new Dictionary <PPDApplicationKey, List <PendingPPDDebitAdjApp> >();
                foreach (PendingPPDDebitAdjApp pendingPPDDebitAdjApp in docs)
                {
                    CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(ie, pendingPPDDebitAdjApp.InvCuryInfoID);

                    PPDApplicationKey key = new PPDApplicationKey();
                    pendingPPDDebitAdjApp.Index = i++;
                    key.BranchID   = pendingPPDDebitAdjApp.AdjdBranchID;
                    key.BAccountID = pendingPPDDebitAdjApp.VendorID;
                    key.LocationID = pendingPPDDebitAdjApp.InvVendorLocationID;
                    key.CuryID     = info.CuryID;
                    key.CuryRate   = info.CuryRate;
                    key.AccountID  = pendingPPDDebitAdjApp.AdjdAPAcct;
                    key.SubID      = pendingPPDDebitAdjApp.AdjdAPSub;
                    key.TaxZoneID  = pendingPPDDebitAdjApp.InvTaxZoneID;

                    List <PendingPPDDebitAdjApp> list;
                    if (!dict.TryGetValue(key, out list))
                    {
                        dict[key] = list = new List <PendingPPDDebitAdjApp>();
                    }

                    list.Add(pendingPPDDebitAdjApp);
                }

                foreach (List <PendingPPDDebitAdjApp> list in dict.Values)
                {
                    APInvoice invoice = CreateAndReleasePPDDebitAdj(ie, filter, list, AutoReleaseDebitAdjustments);

                    if (invoice == null)
                    {
                        failed = true;
                    }
                }
            }
            else
            {
                foreach (PendingPPDDebitAdjApp pendingPPDDebitAdjApp in docs)
                {
                    List <PendingPPDDebitAdjApp> list = new List <PendingPPDDebitAdjApp>(1);
                    pendingPPDDebitAdjApp.Index = i++;
                    list.Add(pendingPPDDebitAdjApp);

                    APInvoice invoice = CreateAndReleasePPDDebitAdj(ie, filter, list, AutoReleaseDebitAdjustments);

                    if (invoice == null)
                    {
                        failed = true;
                    }
                }
            }

            if (failed)
            {
                throw new PXException(GL.Messages.DocumentsNotReleased);
            }
        }
Esempio n. 14
0
        protected virtual void EPSetup_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
        {
            var row = e.Row as EPSetup;

            if (row == null || e.Operation == PXDBOperation.Delete)
            {
                return;
            }
            if (row.PostingOption == EPPostOptions.PostToOffBalance && row.OffBalanceAccountGroupID == null)
            {
                if (cache.RaiseExceptionHandling <EPSetup.offBalanceAccountGroupID>(e.Row, row.OffBalanceAccountGroupID, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <EPSetup.offBalanceAccountGroupID>(cache))))
                {
                    throw new PXRowPersistingException(typeof(EPSetup.offBalanceAccountGroupID).Name, row.OffBalanceAccountGroupID, ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <EPSetup.offBalanceAccountGroupID>(cache));
                }
            }
            if (row.CustomWeek == true)
            {
                DateTime?firstUsing = GetFirstActivityDate();
                DateTime?lastUsing  = GetLasttUsingWeek();

                if (firstUsing != null && lastUsing != null)
                {
                    EPCustomWeek firstWeek = PXSelectOrderBy <EPCustomWeek, OrderBy <Asc <EPCustomWeek.weekID> > > .SelectWindowed(this, 0, 1);

                    EPCustomWeek lastWeek = PXSelectOrderBy <EPCustomWeek, OrderBy <Desc <EPCustomWeek.weekID> > > .SelectWindowed(this, 0, 1);

                    foreach (EPCustomWeek week in CustomWeek.Cache.Inserted)
                    {
                        if (lastWeek == null)
                        {
                            lastWeek = week;
                        }

                        if (week.WeekID > lastWeek.WeekID)
                        {
                            lastWeek = week;
                        }
                    }

                    if (firstWeek == null || firstUsing < firstWeek.StartDate || lastWeek == null || lastWeek.EndDate < lastUsing)
                    {
                        throw new PXRowPersistingException(typeof(EPSetup.customWeek).Name, row.CustomWeek, Messages.CustomWeekNotCreated, firstUsing, lastUsing);
                    }
                }
            }
        }
Esempio n. 15
0
        protected virtual void FixedAsset_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            FixedAsset asset = (FixedAsset)e.Row;

            // AssetID can be <0 when the datasource inserts a temporary record on redirect from selector
            if (asset == null || asset.AssetID < 0)
            {
                return;
            }

            FADetails assetdet = PXSelect <FADetails, Where <FADetails.assetID, Equal <Required <FADetails.assetID> > > > .Select(this, asset.AssetID);

            try
            {
                AssetProcess.ThrowDisabled_Dispose(this, asset, assetdet, fasetup.Current, (DateTime)Filter.Current.DisposalDate, Filter.Current.DisposalPeriodID, Filter.Current.DeprBeforeDisposal == true);
            }
            catch (PXException exc)
            {
                PXUIFieldAttribute.SetEnabled <FixedAsset.selected>(sender, asset, false);
                sender.RaiseExceptionHandling <FixedAsset.selected>(asset, null, new PXSetPropertyException(exc.MessageNoNumber, PXErrorLevel.RowWarning));
            }
            if (Filter.Current.DisposalAmtMode == DisposalFilter.disposalAmtMode.Manual && asset.Selected == true && asset.DisposalAmt == null)
            {
                sender.RaiseExceptionHandling <FixedAsset.disposalAmt>(asset, null, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <FixedAsset.disposalAmt>(sender)));
            }
        }
Esempio n. 16
0
        protected virtual void EPSetup_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
        {
            var row = e.Row as EPSetup;

            if (row == null)
            {
                return;
            }
            if (row.PostToOffBalance == true && row.OffBalanceAccountGroupID == null)
            {
                if (cache.RaiseExceptionHandling <EPSetup.offBalanceAccountGroupID>(e.Row, row.OffBalanceAccountGroupID, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <EPSetup.offBalanceAccountGroupID>(cache))))
                {
                    throw new PXRowPersistingException(typeof(EPSetup.offBalanceAccountGroupID).Name, row.OffBalanceAccountGroupID, ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <EPSetup.offBalanceAccountGroupID>(cache));
                }
            }
            if (row.CustomWeek == true)
            {
                DateTime?firsUsing = GetFirstUsingWeek();
                DateTime?lastUsing = GetLasttUsingWeek();

                if (firsUsing != null && lastUsing != null)
                {
                    EPCustomWeek firstWeek = (EPCustomWeek)PXSelectOrderBy <EPCustomWeek, OrderBy <Asc <EPCustomWeek.weekID> > > .SelectSingleBound(this, null);

                    EPCustomWeek lastWeek = (EPCustomWeek)PXSelectOrderBy <EPCustomWeek, OrderBy <Desc <EPCustomWeek.weekID> > > .SelectSingleBound(this, null);

                    if (firstWeek == null || firsUsing < firstWeek.StartDate || lastWeek == null || lastWeek.EndDate < lastUsing)
                    {
                        throw new PXRowPersistingException(typeof(EPSetup.customWeek).Name, row.CustomWeek, Messages.CustomWeekNotCreated, firsUsing, lastUsing);
                    }
                }
            }
        }
Esempio n. 17
0
        public virtual void VerifyBeforeTransaction(string action, string type)
        {
            int  itemsSelectedCount = 0;
            bool canPerformAction   = false;

            if (action == ID.LogActions.START)
            {
                if (type == ID.Type_Log.TRAVEL || type == ID.Type_Log.SERVICE)
                {
                    itemsSelectedCount = StaffMemberLogStartAction.Select().RowCast <FSAppointmentEmployeeFSLogStart>().Where(x => x.Selected == true).Count();
                    canPerformAction   = LogActionFilter.Current.Me == true || itemsSelectedCount > 0;

                    if (type == ID.Type_Log.SERVICE && LogActionFilter.Current.DetLineRef == null)
                    {
                        LogActionFilter.Cache.RaiseExceptionHandling <FSLogActionFilter.detLineRef>(LogActionFilter.Current,
                                                                                                    LogActionFilter.Current.DetLineRef,
                                                                                                    new PXSetPropertyException(PXMessages.LocalizeFormatNoPrefix(TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                                                                                                                                                                 PXUIFieldAttribute.GetDisplayName <FSLogActionFilter.detLineRef>(LogActionFilter.Cache))));

                        canPerformAction = false;
                    }
                }
                else if (type == ID.Type_Log.STAFF_ASSIGMENT)
                {
                    itemsSelectedCount = LogStaffActionDetails.Select().RowCast <FSStaffLogActionDetail>().Where(x => x.Selected == true).Count();
                    canPerformAction   = itemsSelectedCount > 0;
                }
                else if (type == ID.Type_Log.SERV_BASED_ASSIGMENT)
                {
                    itemsSelectedCount = ServicesLogAction.Select().RowCast <FSDetailFSLogAction>().Where(x => x.Selected == true).Count();
                    canPerformAction   = itemsSelectedCount > 0;
                }
            }
            else if (action == ID.LogActions.COMPLETE)
            {
                if (type == ID.Type_Log.TRAVEL)
                {
                    itemsSelectedCount = LogActionTravelDetails.Select().RowCast <FSLogActionTravelDetail>().Where(x => x.Selected == true).Count();
                }
                else if (type == ID.Type_Log.SERVICE || type == ID.Type_Log.STAFF_ASSIGMENT)
                {
                    itemsSelectedCount = LogActionServiceDetails.Select().RowCast <NoTravelLogInProcess>().Where(x => x.Selected == true).Count();
                }

                canPerformAction = itemsSelectedCount > 0;
            }

            if (canPerformAction == false)
            {
                LogActionFilter.Cache.RaiseExceptionHandling <FSLogActionFilter.action>(LogActionFilter.Current,
                                                                                        LogActionFilter.Current.Action,
                                                                                        new PXSetPropertyException(TX.Error.CANNOT_PERFORM_LOG_ACTION_RECORD_NOT_SELECTED));

                throw new PXRowPersistingException(null, null, TX.Error.CANNOT_PERFORM_LOG_ACTION_RECORD_NOT_SELECTED);
            }
        }
Esempio n. 18
0
        protected virtual void EPGenerateWeeksDialog_TillDate_FieldVerifying(PXCache cache, PXFieldVerifyingEventArgs e)
        {
            EPGenerateWeeksDialog row = (EPGenerateWeeksDialog)e.Row;

            if (e.NewValue == null || row == null)
            {
                return;
            }
            if ((DateTime)e.NewValue < row.FromDate)
            {
                e.Cancel = true;
                throw new PXSetPropertyException(ErrorMessages.EndDateLessThanStartDate, PXUIFieldAttribute.GetDisplayName <EPGenerateWeeksDialog.tillDate>(cache), PXUIFieldAttribute.GetDisplayName <EPGenerateWeeksDialog.fromDate>(cache), row.FromDate);
            }
            DateTime?lastUsingDate = GetLasttUsingWeek();

            if (lastUsingDate != null && (DateTime)e.NewValue < lastUsingDate)
            {
                e.Cancel = true;
                throw new PXSetPropertyException(Messages.ExistsActivitiesLessThanDate, PXUIFieldAttribute.GetDisplayName <EPGenerateWeeksDialog.tillDate>(cache), lastUsingDate);
            }
        }
        public virtual IEnumerable Clone(PXAdapter adapter)
        {
            if (this.Filter.Current.ScheduledEndTime == null)
            {
                Filter.Cache.RaiseExceptionHandling <FSCloneAppointmentFilter.scheduledEndTime>(
                    Filter.Current,
                    null,
                    new PXSetPropertyException(
                        PXMessages.LocalizeFormat(
                            TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                            PXUIFieldAttribute.GetDisplayName <FSCloneAppointmentFilter.scheduledEndTime>(Filter.Cache)),
                        PXErrorLevel.Error));

                return(adapter.Get());
            }

            if (this.Filter.Current.CloningType == ID.CloningType_CloneAppointment.MULTIPLE)
            {
                if (this.Filter.Current.ScheduledFromDate == null)
                {
                    Filter.Cache.RaiseExceptionHandling <FSCloneAppointmentFilter.scheduledFromDate>(
                        Filter.Current,
                        null,
                        new PXSetPropertyException(
                            PXMessages.LocalizeFormat(
                                TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                                PXUIFieldAttribute.GetDisplayName <FSCloneAppointmentFilter.scheduledFromDate>(Filter.Cache)),
                            PXErrorLevel.Error));

                    return(adapter.Get());
                }

                if (this.Filter.Current.ScheduledToDate == null)
                {
                    Filter.Cache.RaiseExceptionHandling <FSCloneAppointmentFilter.scheduledToDate>(
                        Filter.Current,
                        null,
                        new PXSetPropertyException(
                            PXMessages.LocalizeFormat(
                                TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                                PXUIFieldAttribute.GetDisplayName <FSCloneAppointmentFilter.scheduledToDate>(Filter.Cache)),
                            PXErrorLevel.Error));

                    return(adapter.Get());
                }
            }

            FSServiceOrder fsServiceOrderRow = PXSelectJoin <FSServiceOrder,
                                                             InnerJoin <
                                                                 FSAppointment, On <FSAppointment.sOID, Equal <FSServiceOrder.sOID> > >,
                                                             Where <
                                                                 FSAppointment.appointmentID, Equal <Required <FSAppointment.appointmentID> > > >
                                               .Select(this, this.Filter.Current.AppointmentID);

            if (fsServiceOrderRow != null &&
                fsServiceOrderRow.Status == ID.Status_ServiceOrder.COMPLETED)
            {
                throw new PXException(TX.Error.CANNOT_CLONE_APPOINMENT_SERVICE_ORDER_COMPLETED);
            }

            CloneAppointmentProcess graphCloneAppointmentProcess = PXGraph.CreateInstance <CloneAppointmentProcess>();

            graphCloneAppointmentProcess.Filter.Current.SrvOrdType         = this.Filter.Current.SrvOrdType;
            graphCloneAppointmentProcess.Filter.Current.RefNbr             = this.Filter.Current.RefNbr;
            graphCloneAppointmentProcess.Filter.Current.KeepTimeDuration   = this.Filter.Current.KeepTimeDuration;
            graphCloneAppointmentProcess.Filter.Current.ScheduledDate      = this.Filter.Current.ScheduledDate;
            graphCloneAppointmentProcess.Filter.Current.ScheduledStartTime = this.Filter.Current.ScheduledStartTime;
            graphCloneAppointmentProcess.Filter.Current.ScheduledEndTime   = this.Filter.Current.ScheduledEndTime;

            graphCloneAppointmentProcess.Filter.Current.ScheduledFromDate = this.Filter.Current.ScheduledFromDate;
            graphCloneAppointmentProcess.Filter.Current.ScheduledToDate   = this.Filter.Current.ScheduledToDate;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnMonday    = this.Filter.Current.ActiveOnMonday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnThursday  = this.Filter.Current.ActiveOnThursday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnWednesday = this.Filter.Current.ActiveOnWednesday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnTuesday   = this.Filter.Current.ActiveOnTuesday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnFriday    = this.Filter.Current.ActiveOnFriday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnSaturday  = this.Filter.Current.ActiveOnSaturday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnSunday    = this.Filter.Current.ActiveOnSunday;

            graphCloneAppointmentProcess.AppointmentSelected.Current = this.AppointmentSelected.Current;

            PXLongOperation.StartOperation(
                this,
                delegate
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    if (this.Filter.Current.CloningType == ID.CloningType_CloneAppointment.SINGLE)
                    {
                        AppointmentEntry graphOriginalAppointment = PXGraph.CreateInstance <AppointmentEntry>();

                        graphOriginalAppointment.AppointmentSelected.Current = graphOriginalAppointment.AppointmentRecords.Search <FSAppointment.appointmentID>
                                                                                   (AppointmentSelected.Current.AppointmentID, AppointmentSelected.Current.SrvOrdType);

                        graphCloneAppointmentProcess.CloneAppointment(graphOriginalAppointment, PXGraph.CreateInstance <AppointmentEntry>());
                    }

                    if (this.Filter.Current.CloningType == ID.CloningType_CloneAppointment.MULTIPLE)
                    {
                        graphCloneAppointmentProcess.CloneMultipleAppointments(graphCloneAppointmentProcess);
                    }

                    ts.Complete();
                }
            });

            return(adapter.Get());
        }
Esempio n. 20
0
 protected void ThrowFieldIsEmpty <Field>(PXCache sender, PXRowPersistingEventArgs e)
     where Field : IBqlField
 {
     sender.RaiseExceptionHandling <Field>(e.Row, null, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <Field>(sender)));
 }
Esempio n. 21
0
        public static bool SetErrorEmptyIfNull <TField>(PXCache cache, object row, object value)
            where TField : IBqlField
        {
            if (value == null)
            {
                cache.RaiseExceptionHandling <TField>(row, null, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName <TField>(cache)));
                return(false);
            }

            return(true);
        }
Esempio n. 22
0
        protected virtual void ARRegisterEx_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            ARRegisterEx row = e.Row as ARRegisterEx;

            if (row == null)
            {
                return;
            }

            bool WODate_GT_DocDate     = DateTime.Compare((DateTime)Filter.Current.WODate, (DateTime)((ARRegisterEx)e.Row).DocDate) >= 0;
            bool WOPeriod_GT_DocPeriod = string.Compare(Filter.Current.WOFinPeriodID, ((ARRegisterEx)e.Row).FinPeriodID) >= 0;

            PXUIFieldAttribute.SetEnabled <ARRegisterEx.selected>(sender, e.Row, WODate_GT_DocDate && WOPeriod_GT_DocPeriod);

            sender.RaiseExceptionHandling <ARRegisterEx.docDate>(e.Row, null, !WODate_GT_DocDate ? new PXSetPropertyException(Messages.WriteOff_ApplDate_Less_DocDate, PXErrorLevel.RowError, PXUIFieldAttribute.GetDisplayName <ARWriteOffFilter.wODate>(Filter.Cache)) : null);
            sender.RaiseExceptionHandling <ARRegisterEx.finPeriodID>(e.Row, null, !WOPeriod_GT_DocPeriod ? new PXSetPropertyException(Messages.ApplPeriod_Less_DocPeriod, PXErrorLevel.RowError, PXUIFieldAttribute.GetDisplayName <ARWriteOffFilter.wOFinPeriodID>(Filter.Cache)) : null);

            if (string.IsNullOrEmpty(row.ReasonCode))
            {
                row.ReasonCode = Filter.Current.ReasonCode;
            }
        }
Esempio n. 23
0
        public static void ReleaseDoc(EPExpenseClaim claim)
        {
            #region prepare required variables
            APInvoiceEntry    docgraph          = PXGraph.CreateInstance <APInvoiceEntry>();
            ExpenseClaimEntry expenseClaimGraph = PXGraph.CreateInstance <ExpenseClaimEntry>();


            var receipts = PXSelect <EPExpenseClaimDetails,
                                     Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr).Select(
                result => (EPExpenseClaimDetails)result).GroupBy(
                item => Tuple.Create(
                    item.TaxZoneID,
                    item.TaxCalcMode
                    )).ToDictionary(x => x.Key, group => group.ToList());

            if (receipts.Count() == 0)
            {
                receipts.Add(Tuple.Create(claim.TaxZoneID, claim.TaxCalcMode), new List <EPExpenseClaimDetails>());
            }
            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

            APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph);

            EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID);

            Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();
            #endregion

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (var res in receipts)
                {
                    docgraph.Clear(PXClearOption.ClearAll);
                    docgraph.SelectTimeStamp();
                    docgraph.vendor.Current   = employee;
                    docgraph.location.Current = emplocation;

                    CurrencyInfo infoOriginal = PXSelect <CurrencyInfo,
                                                          Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID);

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

                    info.CuryInfoID = null;
                    info            = docgraph.currencyinfo.Insert(info);
                    #region CreateInoiceHeader
                    APInvoice invoice = new APInvoice();


                    bool reversedDocument = false;
                    if (res.Value.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0)
                    {
                        invoice.DocType  = APInvoiceType.DebitAdj;
                        reversedDocument = true;
                    }
                    else
                    {
                        invoice.DocType = APInvoiceType.Invoice;
                    }
                    decimal signOperation;
                    if (reversedDocument)
                    {
                        signOperation = -1;
                    }
                    else
                    {
                        signOperation = 1;
                    }

                    invoice.CuryInfoID = info.CuryInfoID;

                    invoice.Hold     = true;
                    invoice.Released = false;
                    invoice.Printed  = false;
                    invoice.OpenDoc  = true;

                    invoice.DocDate          = claim.DocDate;
                    invoice.FinPeriodID      = claim.FinPeriodID;
                    invoice.InvoiceNbr       = claim.RefNbr;
                    invoice.DocDesc          = claim.DocDesc;
                    invoice.VendorID         = claim.EmployeeID;
                    invoice.CuryID           = info.CuryID;
                    invoice.VendorLocationID = claim.LocationID;
                    invoice.APAccountID      = emplocation != null ? emplocation.APAccountID : null;
                    invoice.APSubID          = emplocation != null ? emplocation.APSubID : null;
                    invoice.TaxZoneID        = res.Key.Item1;
                    invoice.TaxCalcMode      = res.Key.Item2;
                    invoice.BranchID         = claim.BranchID;
                    invoice.OrigModule       = BatchModule.EP;
                    invoice.OrigRefNbr       = claim.RefNbr;

                    invoice = docgraph.Document.Insert(invoice);

                    PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                    info.CuryInfoID = invoice.CuryInfoID;

                    PXCache claimcache       = docgraph.Caches[typeof(EPExpenseClaim)];
                    PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)];

                    PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, docgraph.Document.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    #endregion
                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID, APTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    decimal?claimCuryTaxRoundDiff = 0m;
                    decimal?claimTaxRoundDiff     = 0m;
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        #region AddDetails

                        decimal tipQty;
                        if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                        {
                            tipQty = 1;
                        }
                        else
                        {
                            tipQty = -1;
                        }
                        Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

                        if (claimdetail.TaskID != null)
                        {
                            PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, claimdetail.TaskID);

                            if (task != null && !(bool)task.VisibleInAP)
                            {
                                throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP);
                            }
                        }

                        APTran tran = new APTran();
                        tran.InventoryID = claimdetail.InventoryID;
                        tran.TranDesc    = claimdetail.TranDesc;
                        decimal unitCost;
                        decimal amount;
                        decimal taxableAmt;
                        decimal taxAmt;
                        if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            unitCost   = claimdetail.CuryUnitCost ?? 0m;
                            amount     = claimdetail.CuryTaxableAmt ?? 0m;
                            taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                            taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                        }
                        else
                        {
                            if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                            {
                                unitCost = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                            }
                            if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                            {
                                amount = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                            }
                            if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                            {
                                taxableAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                            }
                            if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                            {
                                taxAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                            }
                        }

                        tran.ManualPrice       = true;
                        tran.CuryUnitCost      = unitCost;
                        tran.Qty               = claimdetail.Qty * signOperation;
                        tran.UOM               = claimdetail.UOM;
                        tran.NonBillable       = claimdetail.Billable != true;
                        claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                        claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                        tran.Date              = claimdetail.ExpenseDate;

                        if (contract.BaseType == PMProject.ProjectBaseType.Project)
                        {
                            tran.ProjectID = claimdetail.ContractID;
                        }
                        else
                        {
                            tran.ProjectID = ProjectDefaultAttribute.NonProject();
                        }

                        tran.TaskID        = claimdetail.TaskID;
                        tran.CostCodeID    = claimdetail.CostCodeID;
                        tran.AccountID     = claimdetail.ExpenseAccountID;
                        tran.SubID         = claimdetail.ExpenseSubID;
                        tran.TaxCategoryID = claimdetail.TaxCategoryID;
                        tran.BranchID      = claimdetail.BranchID;
                        tran                = docgraph.Transactions.Insert(tran);
                        tran.CuryLineAmt    = amount * signOperation;
                        tran.CuryTaxAmt     = 0;
                        tran.CuryTaxableAmt = taxableAmt * signOperation;
                        tran.CuryTaxAmt     = taxAmt * signOperation;
                        tran                = docgraph.Transactions.Update(tran);


                        if ((claimdetail.CuryTipAmt ?? 0) != 0)
                        {
                            APTran tranTip = new APTran();
                            if (epsetup.NonTaxableTipItem == null)
                            {
                                throw new PXException(Messages.TipItemIsNotDefined);
                            }
                            IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                                 Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                            if (tipItem == null)
                            {
                                string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                                throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                            }
                            tranTip.InventoryID = epsetup.NonTaxableTipItem;
                            tranTip.TranDesc    = tipItem.Descr;
                            if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                            {
                                tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                                tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                            }
                            else
                            {
                                decimal tipAmt;
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                                tranTip.CuryUnitCost = Math.Abs(tipAmt);
                                tranTip.CuryTranAmt  = tipAmt * signOperation;
                            }
                            tranTip.Qty         = tipQty;
                            tranTip.UOM         = tipItem.BaseUnit;
                            tranTip.NonBillable = claimdetail.Billable != true;
                            tranTip.Date        = claimdetail.ExpenseDate;

                            tranTip.BranchID = claimdetail.BranchID;
                            tranTip          = docgraph.Transactions.Insert(tranTip);

                            if (epsetup.UseReceiptAccountForTips == true)
                            {
                                tranTip.AccountID = claimdetail.ExpenseAccountID;
                                tranTip.SubID     = claimdetail.ExpenseSubID;
                            }
                            else
                            {
                                tranTip.AccountID = tipItem.COGSAcctID;
                                Location companyloc = (Location)PXSelectJoin <Location,
                                                                              InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                        And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                         InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                              Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                                PMTask task = PXSelect <PMTask,
                                                        Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                               And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                                Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                                int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                                int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                                int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                                int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                                int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                                int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                                object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                        new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                        new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                                docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                                tranTip.SubID = (int?)value;
                            }
                            tranTip = docgraph.Transactions.Update(tranTip);
                            tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                            tranTip.ProjectID     = tran.ProjectID;
                            tranTip.TaskID        = tran.TaskID;
                            tranTip = AddTaxes(docgraph, invoice, signOperation, claimdetail, tranTip, true);
                            tranTip = docgraph.Transactions.Update(tranTip);
                        }

                        PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, docgraph.Transactions.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                        claimdetail.Released = true;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                        #endregion


                        tran = AddTaxes(docgraph, invoice, signOperation, claimdetail, tran, false);
                    }

                    #region legacy taxes
                    foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                     Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                    {
                        #region Add taxes
                        APTaxTran new_aptax = docgraph.Taxes.Search <APTaxTran.taxID>(tax.TaxID);

                        if (new_aptax == null)
                        {
                            new_aptax       = new APTaxTran();
                            new_aptax.TaxID = tax.TaxID;
                            new_aptax       = docgraph.Taxes.Insert(new_aptax);
                            if (new_aptax != null)
                            {
                                new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                                new_aptax.CuryTaxableAmt = 0m;
                                new_aptax.CuryTaxAmt     = 0m;
                                new_aptax.CuryExpenseAmt = 0m;
                                new_aptax = docgraph.Taxes.Update(new_aptax);
                            }
                        }

                        if (new_aptax != null)
                        {
                            new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                            new_aptax.TaxRate        = tax.TaxRate;
                            new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                            new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                            new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                            new_aptax = docgraph.Taxes.Update(new_aptax);
                        }
                        #endregion
                    }
                    #endregion

                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                    invoice.Hold           = false;
                    docgraph.Document.Update(invoice);
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (APTran line in docgraph.Transactions.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }

                    docgraph.Document.Update(invoice);
                    docgraph.Save.Press();
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        claimdetail.APDocType = invoice.DocType;
                        claimdetail.APRefNbr  = invoice.RefNbr;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    }
                    claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                    claim.Released = true;
                    expenseClaimGraph.ExpenseClaim.Update(claim);

                    #region EP History Update
                    EPHistory hist = new EPHistory();
                    hist.EmployeeID  = invoice.VendorID;
                    hist.FinPeriodID = invoice.FinPeriodID;
                    hist             = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(hist);

                    hist.FinPtdClaimed += invoice.DocBal;
                    hist.FinYtdClaimed += invoice.DocBal;
                    if (invoice.FinPeriodID == invoice.TranPeriodID)
                    {
                        hist.TranPtdClaimed += invoice.DocBal;
                        hist.TranYtdClaimed += invoice.DocBal;
                    }
                    else
                    {
                        EPHistory tranhist = new EPHistory();
                        tranhist.EmployeeID      = invoice.VendorID;
                        tranhist.FinPeriodID     = invoice.TranPeriodID;
                        tranhist                 = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist);
                        tranhist.TranPtdClaimed += invoice.DocBal;
                        tranhist.TranYtdClaimed += invoice.DocBal;
                    }
                    expenseClaimGraph.Views.Caches.Add(typeof(EPHistory));
                    #endregion

                    expenseClaimGraph.Save.Press();

                    doclist.Add(docgraph.Document.Current);
                }

                ts.Complete();
            }

            if ((bool)epsetup.AutomaticReleaseAP == true)
            {
                APDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
        protected virtual IEnumerable items()
        {
            CRPurgeFilter filter = Filter.Current;

            if (filter == null)
            {
                return(new Contact[0]);
            }

            if (setup.Current != null)
            {
                bool PurgeAgeOfNotConvertedLeadsWrongValue = setup.Current.PurgeAgeOfNotConvertedLeads == null || setup.Current.PurgeAgeOfNotConvertedLeads <= 0;
                bool PurgePeriodWithoutActivityWrongValue  = setup.Current.PurgePeriodWithoutActivity == null || setup.Current.PurgePeriodWithoutActivity <= 0;

                if (PurgeAgeOfNotConvertedLeadsWrongValue || PurgePeriodWithoutActivityWrongValue)
                {
                    string message = String.Empty;

                    if (PurgeAgeOfNotConvertedLeadsWrongValue)
                    {
                        message += "'" + PXUIFieldAttribute.GetDisplayName <CRSetup.purgeAgeOfNotConvertedLeads>(setup.Cache) + "' ";
                    }
                    if (PurgePeriodWithoutActivityWrongValue)
                    {
                        message += "'" + PXUIFieldAttribute.GetDisplayName <CRSetup.purgePeriodWithoutActivity>(setup.Cache) + "' ";
                    }

                    throw new PXSetupNotEnteredException(Messages.CRSetupFieldsAreEmpty, typeof(CRSetup), typeof(CRSetup).Name, message);
                }
            }

            return(PXSelectJoin <Contact,
                                 LeftJoin <BAccount, On <BAccount.bAccountID, Equal <Contact.bAccountID> >,
                                           LeftJoin <CRActivityStatistics, On <CRActivityStatistics.noteID, Equal <Contact.noteID> > > >,
                                 Where <Contact.contactType, Equal <ContactTypesAttribute.lead>, Or <Contact.contactType, Equal <ContactTypesAttribute.person> > > > .Select(this)
                   .Where(res =>
            {
                Contact contact = res;
                CRActivityStatistics activityStatistic = res.GetItem <CRActivityStatistics>();
                return (                                 //Purge Not Converted Leads that are older than
                    filter.PurgeOldNotConvertedLeads == true && filter.PurgeAgeOfNotConvertedLeads != null &&
                    contact.CreatedDateTime != null &&
                    contact.ContactType == ContactTypesAttribute.Lead &&
                    contact.Status != LeadStatusesAttribute.Closed &&
                    ((DateTime)contact.CreatedDateTime).AddMonths((int)filter.PurgeAgeOfNotConvertedLeads) < Accessinfo.BusinessDate
                    )
                ||
                (                                        //Purge Not Active Contacts with no activities for more than
                    filter.PurgeOldInertContacts == true && filter.PurgePeriodWithoutActivity != null &&
                    activityStatistic.LastActivityDate != null &&
                    contact.ContactType == ContactTypesAttribute.Person
                    &&
                    ((DateTime)activityStatistic.LastActivityDate).AddMonths((int)filter.PurgePeriodWithoutActivity) <
                    Accessinfo.BusinessDate &&
                    contact.IsActive != true
                )
                ||
                //Purge Closed Contacts
                (filter.PurgeClosedContacts == true && (contact.Status == LeadStatusesAttribute.Closed ||
                                                        (contact.IsActive != true && contact.DuplicateStatus == DuplicateStatusAttribute.Duplicated)));
            }));
        }
Esempio n. 25
0
        public SplitProcess()
        {
            object setup = fasetup.Current;

            if (fasetup.Current.UpdateGL != true)
            {
                throw new PXSetupNotEnteredException <FASetup>(Messages.OperationNotWorkInInitMode, PXUIFieldAttribute.GetDisplayName <FASetup.updateGL>(fasetup.Cache));
            }
        }
Esempio n. 26
0
 public static string MakeSub <Field>(PXGraph graph, string mask, object[] sources, Type[] fields)
     where Field : IBqlField
 {
     try
     {
         return(PXDimensionMaskAttribute.MakeSub <Field>(graph, mask, new RQAcctSubDefault.ClassListAttribute().AllowedValues, 0, sources));
     }
     catch (PXMaskArgumentException ex)
     {
         PXCache cache     = graph.Caches[BqlCommand.GetItemType(fields[ex.SourceIdx])];
         string  fieldName = fields[ex.SourceIdx].Name;
         throw new PXMaskArgumentException(new RQAcctSubDefault.ClassListAttribute().AllowedLabels[ex.SourceIdx], PXUIFieldAttribute.GetDisplayName(cache, fieldName));
     }
 }
Esempio n. 27
0
        protected virtual void PrintPayments(List <APPayment> list, PrintChecksFilter filter, PaymentMethod paymentMethod)
        {
            if (list.Count == 0)
            {
                return;
            }

            if (paymentMethod.UseForAP == true)
            {
                if (paymentMethod.APPrintChecks == true && string.IsNullOrEmpty(paymentMethod.APCheckReportID))
                {
                    throw new PXException(Messages.FieldNotSetInPaymentMethod, PXUIFieldAttribute.GetDisplayName <PaymentMethod.aPCheckReportID>(paymenttype.Cache), paymentMethod.PaymentMethodID);
                }

                if (paymentMethod.APPrintChecks == true && paymentMethod.APPrintRemittance == true && string.IsNullOrEmpty(paymentMethod.APRemittanceReportID))
                {
                    throw new PXException(Messages.FieldNotSetInPaymentMethod, PXUIFieldAttribute.GetDisplayName <PaymentMethod.aPRemittanceReportID>(paymenttype.Cache), paymentMethod.PaymentMethodID);
                }
            }

            bool printAdditionRemit = false;

            if (paymentMethod.APCreateBatchPayment == true)
            {
                CABatch batch = CreateBatchPayment(list, filter);
                if (batch != null)
                {
                    bool           failed = false;
                    APPaymentEntry pe     = CreateInstance <APPaymentEntry>();

                    string NextCheckNbr = filter.NextCheckNbr;
                    foreach (APPayment pmt in list)
                    {
                        APPayment payment = pmt;
                        PXProcessing <APPayment> .SetCurrentItem(payment);

                        try
                        {
                            payment = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType);
                            if (payment.PrintCheck != true)
                            {
                                throw new PXException(Messages.CantPrintNonprintableCheck);
                            }
                            if ((payment.DocType == APDocType.Check || payment.DocType == APDocType.QuickCheck) &&
                                payment.Status != APDocStatus.PendingPrint)
                            {
                                throw new PXException(Messages.ChecksMayBePrintedInPendingPrintStatus);
                            }

                            AssignNumbers(pe, payment, ref NextCheckNbr, true);

                            if (payment.Passed == true)
                            {
                                pe.TimeStamp = payment.tstamp;
                            }
                            pe.Save.Press();
                            payment.tstamp = pe.TimeStamp;
                            pe.Clear();
                        }
                        catch (PXException e)
                        {
                            PXProcessing <APPayment> .SetError(e);

                            failed = true;
                        }
                    }
                    if (failed)
                    {
                        throw new PXOperationCompletedWithErrorException(Messages.APPaymentsAreAddedToTheBatchButWasNotUpdatedCorrectly, batch.BatchNbr);
                    }
                    RedirectToResultWithCreateBatch(batch);
                }
            }
            else
            {
                APReleaseChecks     pp          = CreateInstance <APReleaseChecks>();
                ReleaseChecksFilter filter_copy = PXCache <ReleaseChecksFilter> .CreateCopy(pp.Filter.Current);

                filter_copy.PayAccountID = filter.PayAccountID;
                filter_copy.PayTypeID    = filter.PayTypeID;
                filter_copy.CuryID       = filter.CuryID;
                pp.Filter.Cache.Update(filter_copy);

                APPaymentEntry pe             = CreateInstance <APPaymentEntry>();
                bool           failed         = false;
                Dictionary <string, string> d = new Dictionary <string, string>();

                string nextCheckNbr = filter.NextCheckNbr;
                string prevCheckNbr = nextCheckNbr;

                int idxReportFilter = 0;
                foreach (APPayment pmt in list)
                {
                    APPayment payment = pmt;
                    PXProcessing <APPayment> .SetCurrentItem(payment);

                    try
                    {
                        prevCheckNbr = nextCheckNbr;
                        if (filter.IsNextNumberDuplicated(this, nextCheckNbr))
                        {
                            string duplicate = nextCheckNbr;
                            nextCheckNbr = AutoNumberAttribute.NextNumber(nextCheckNbr);
                            throw new PXException(Messages.ConflictWithExistingCheckNumber, duplicate);
                        }

                        payment = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType);
                        if (payment.PrintCheck != true)
                        {
                            throw new PXException(Messages.CantPrintNonprintableCheck);
                        }
                        if ((payment.DocType == APDocType.Check || payment.DocType == APDocType.QuickCheck) &&
                            payment.Status != APDocStatus.PendingPrint)
                        {
                            throw new PXException(Messages.ChecksMayBePrintedInPendingPrintStatus);
                        }
                        AssignNumbers(pe, payment, ref nextCheckNbr);

                        if (payment.Passed == true)
                        {
                            pe.TimeStamp = payment.tstamp;
                        }
                        pe.Save.Press();
                        payment.tstamp = pe.TimeStamp;
                        pe.Clear();

                        APPayment seldoc = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType);
                        seldoc.Selected = true;
                        seldoc.Passed   = true;
                        seldoc.tstamp   = payment.tstamp;
                        pp.APPaymentList.Cache.Update(seldoc);
                        pp.APPaymentList.Cache.SetStatus(seldoc, PXEntryStatus.Updated);

                        printAdditionRemit |= seldoc.BillCntr > paymentMethod.APStubLines;

                        StringBuilder sbDocType = new StringBuilder("APPayment.DocType");
                        sbDocType.Append(Convert.ToString(idxReportFilter));
                        StringBuilder sbRefNbr = new StringBuilder("APPayment.RefNbr");
                        sbRefNbr.Append(Convert.ToString(idxReportFilter));

                        idxReportFilter++;

                        d[sbDocType.ToString()] = payment.DocType == APDocType.QuickCheck ? APDocType.QuickCheck : APDocType.Check;
                        d[sbRefNbr.ToString()]  = payment.RefNbr;
                        PXProcessing <APPayment> .SetProcessed();
                    }
                    catch (PXException e)
                    {
                        PXProcessing <APPayment> .SetError(e);

                        failed       = true;
                        nextCheckNbr = prevCheckNbr;
                    }
                }

                if (failed)
                {
                    PXReportRequiredException report = null;
                    if (d.Count > 0)
                    {
                        d[ReportMessages.CheckReportFlag] = ReportMessages.CheckReportFlagValue;
                        report = new PXReportRequiredException(d, paymentMethod.APCheckReportID, PXBaseRedirectException.WindowMode.New, "Check");
                    }
                    throw new PXOperationCompletedWithErrorException(GL.Messages.DocumentsNotReleased, report);
                }
                else
                {
                    if (d.Count > 0)
                    {
                        RedirectToResultNoBatch(pp, d, paymentMethod, printAdditionRemit, nextCheckNbr);
                    }
                }
            }
        }
Esempio n. 28
0
        public static void SetValueExtIfDifferent <Field>(this PXCache cache, object data, object newValue, bool verifyAcceptanceOfNewValue = true)
            where Field : IBqlField
        {
            object currentValue = cache.GetValue <Field>(data);

            if ((currentValue == null && newValue != null) ||
                (currentValue != null && newValue == null) ||
                (currentValue != null && currentValue.Equals(newValue) == false))
            {
                cache.SetValueExt <Field>(data, newValue);

                if (verifyAcceptanceOfNewValue)
                {
                    currentValue = cache.GetValue <Field>(data);

                    if (AreEquivalentValues(currentValue, newValue) == false)
                    {
                        PXFieldState fieldState;
                        string       fieldMessage = string.Empty;

                        try
                        {
                            fieldState = (PXFieldState)cache.GetStateExt <Field>(data);
                        }
                        catch
                        {
                            fieldState = null;
                        }

                        if (fieldState != null && fieldState.Error != null)
                        {
                            fieldMessage = fieldState.Error;
                        }

                        throw new PXException(TX.Messages.ERROR_TRYING_TO_SET_A_NEWVALUE, PXUIFieldAttribute.GetDisplayName <Field>(cache), fieldMessage);
                    }
                }
            }
        }
        public virtual RecordInfo BuildRecordInfo(PXCache sender, object row)
        {
            List <Type> allFields = new List <Type>();

            allFields.AddRange(titleFields);
            if (Line1Fields != null)
            {
                foreach (Type field in Line1Fields)
                {
                    if (!allFields.Contains(field))
                    {
                        allFields.Add(field);
                    }
                }
            }

            if (Line2Fields != null)
            {
                foreach (Type field in Line2Fields)
                {
                    if (!allFields.Contains(field))
                    {
                        allFields.Add(field);
                    }
                }
            }

            Dictionary <Type, object> values = ExtractValues(sender, row, null, allFields);

            //Title:
            List <object> titleArgs = new List <object>();
            string        title     = string.Empty;

            if (titleFields != null && titleFields.Length > 0)
            {
                foreach (Type field in titleFields)
                {
                    if (values.ContainsKey(field))
                    {
                        titleArgs.Add(values[field]);
                    }
                    else
                    {
                        titleArgs.Add(string.Empty);
                    }
                }
            }
            if (titlePrefix != null)
            {
                title = string.Format(PXMessages.LocalizeNoPrefix(titlePrefix), titleArgs.ToArray());
                if (title.Trim().EndsWith("-"))
                {
                    title = title.Trim().TrimEnd('-');
                }
            }

            //Line 1:
            List <object> line1Args         = new List <object>();
            List <string> line1DisplayNames = new List <string>();
            string        line1             = string.Empty;

            if (Line1Fields != null && Line1Fields.Length > 0)
            {
                for (int i = 0; i < Line1Fields.Length; i++)
                {
                    Type field = Line1Fields[i];

                    if (values.ContainsKey(field) && values[field] != null && !string.IsNullOrWhiteSpace(values[field].ToString()))
                    {
                        string displayName = PXUIFieldAttribute.GetDisplayName(sender.Graph.Caches[BqlCommand.GetItemType(field)], field.Name);
                        if (string.IsNullOrWhiteSpace(displayName))
                        {
                            displayName = field.Name;
                        }

                        line1Args.Add(values[field]);
                        line1DisplayNames.Add(displayName);
                    }
                    else
                    {
                        line1Args.Add(null);
                        line1DisplayNames.Add(string.Empty);
                    }
                }
            }
            line1 = BuildFormatedLine(Line1Format, line1Args, line1DisplayNames);


            //Line 2:
            List <object> line2Args         = new List <object>();
            List <string> line2DisplayNames = new List <string>();
            string        line2             = string.Empty;

            if (Line2Fields != null && Line2Fields.Length > 0)
            {
                for (int i = 0; i < Line2Fields.Length; i++)
                {
                    Type field = Line2Fields[i];

                    if (values.ContainsKey(field) && values[field] != null && !string.IsNullOrWhiteSpace(values[field].ToString()))
                    {
                        string displayName = PXUIFieldAttribute.GetDisplayName(sender.Graph.Caches[BqlCommand.GetItemType(field)], field.Name);
                        if (string.IsNullOrWhiteSpace(displayName))
                        {
                            displayName = field.Name;
                        }

                        line2Args.Add(values[field]);
                        line2DisplayNames.Add(displayName);
                    }
                    else
                    {
                        line2Args.Add(null);
                        line2DisplayNames.Add(string.Empty);
                    }
                }
            }
            line2 = BuildFormatedLine(Line2Format, line2Args, line2DisplayNames);

            return(new RecordInfo(title, line1, line2));
        }