private Dictionary <Type, object> ExtractValues(PXCache sender, object row, PXResult res, IEnumerable <Type> fieldTypes, bool buildTranslations)
        {
            Dictionary <Type, object> result = new Dictionary <Type, object>();
            Dictionary <Type, Type>   selectorFieldByTable = new Dictionary <Type, Type>();

            Type lastField = null;

            foreach (Type field in fieldTypes)
            {
                Type tableType = BqlCommand.GetItemType(field);

                if (tableType != null)
                {
                    if (sender.GetItemType().IsAssignableFrom(tableType) || tableType.IsAssignableFrom(sender.GetItemType()))                    //field of the given table or a base dac/table
                    {
                        if (!result.ContainsKey(field))
                        {
                            result.Add(field, GetFieldValue(sender, row, field, res != null, buildTranslations));
                        }

                        lastField = field;
                    }
                    else if (lastField != null && typeof(IBqlTable).IsAssignableFrom(BqlCommand.GetItemType(field)))                    //field of any other table
                    {
                        object foreign = null;
                        if (res != null)
                        {
                            //mass processing - The values are searched in the joined resultset.
                            foreign = res[BqlCommand.GetItemType(field)];

                            if (foreign != null)
                            {
                                PXCache fcache = sender.Graph.Caches[foreign.GetType()];
                                if (!result.ContainsKey(field))
                                {
                                    result.Add(field, GetFieldValue(fcache, foreign, field, false, buildTranslations));
                                }
                            }
                        }

                        if (foreign == null)
                        {
                            //lazy loading - The values are selected through the selectors, with a call to DB

                            string selectorFieldName;
                            if (selectorFieldByTable.ContainsKey(tableType))
                            {
                                selectorFieldName = selectorFieldByTable[tableType].Name;
                            }
                            else
                            {
                                selectorFieldName = lastField.Name;
                            }

                            foreign = PXSelectorAttribute.Select(sender, row, selectorFieldName);
                            if (foreign == null)
                            {
                                foreach (PXEventSubscriberAttribute attr in sender.GetAttributesReadonly(selectorFieldName))
                                {
                                    PXAggregateAttribute aggatt = attr as PXAggregateAttribute;

                                    if (aggatt != null)
                                    {
                                        PXDimensionSelectorAttribute dimAttr = aggatt.GetAttribute <PXDimensionSelectorAttribute>();
                                        PXSelectorAttribute          selAttr = aggatt.GetAttribute <PXSelectorAttribute>();
                                        if (dimAttr != null)
                                        {
                                            selAttr = dimAttr.GetAttribute <PXSelectorAttribute>();
                                        }

                                        if (selAttr != null)
                                        {
                                            PXView   select = sender.Graph.TypedViews.GetView(selAttr.PrimarySelect, !selAttr.DirtyRead);
                                            object[] pars   = new object[selAttr.ParsCount + 1];
                                            pars[pars.Length - 1] = sender.GetValue(row, selAttr.FieldOrdinal);
                                            foreign = PXSelectorAttribute.SelectSingleBound(select, new object[] { row, sender.Graph.Accessinfo }, pars);
                                        }
                                    }
                                }
                            }

                            if (foreign is PXResult)
                            {
                                foreign = ((PXResult)foreign)[0];
                            }

                            if (foreign != null)
                            {
                                if (!selectorFieldByTable.ContainsKey(tableType))
                                {
                                    selectorFieldByTable.Add(tableType, lastField);
                                    //result.Remove(lastField);
                                }

                                PXCache fcache = sender.Graph.Caches[foreign.GetType()];
                                if (!result.ContainsKey(field))
                                {
                                    result.Add(field, GetFieldValue(fcache, foreign, field, false, buildTranslations));
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
        protected virtual void EPExpenseClaimDetails_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
        {
            EPExpenseClaimDetails row = (EPExpenseClaimDetails)e.Row;

            if (row != null)
            {
                EPExpenseClaim claim = (EPExpenseClaim)PXSelect <EPExpenseClaim, Where <EPExpenseClaim.refNbr, Equal <Required <EPExpenseClaimDetails.refNbr> > > > .SelectSingleBound(this, new object[] { null }, row.RefNbr);

                bool enabledApprovalReceipt   = PXAccess.FeatureInstalled <FeaturesSet.approvalWorkflow>() && epsetup.Current.ClaimDetailsAssignmentMapID != null;
                bool legacyClaim              = row.LegacyReceipt == true && !String.IsNullOrEmpty(row.RefNbr);
                bool enabledEditReceipt       = (row.Hold == true || !enabledApprovalReceipt) && !legacyClaim;
                bool enabledRefNbr            = true;
                bool enabledEmployeeAndBranch = enabledEditReceipt && !(row.ClaimCuryInfoID == null && cache.AllowUpdate && !string.IsNullOrEmpty(row.RefNbr));
                bool enabledFinancialDetails  = (row.Rejected != true) && (row.Released != true);
                bool NonProject    = (CurrentContract.SelectSingle()?.ContractCD ?? PMSetup.DefaultNonProjectCode).Trim() == PMSetup.DefaultNonProjectCode;
                bool claimExist    = false;
                bool claimReleased = false;
                if (claim != null)
                {
                    claimExist = true;
                    bool enabledEditClaim = (row.HoldClaim == true);
                    enabledEditReceipt       = enabledEditReceipt && enabledEditClaim;
                    enabledRefNbr            = enabledEditClaim;
                    enabledEmployeeAndBranch = false;
                    enabledFinancialDetails  = enabledFinancialDetails && enabledEditClaim;
                    claimReleased            = claim.Released == true;
                }
                enabledRefNbr = enabledRefNbr && row.LegacyReceipt == false;

                Approval.AllowSelect = enabledApprovalReceipt;
                Delete.SetEnabled(enabledEditReceipt && claim == null);
                PXUIFieldAttribute.SetEnabled(cache, row, enabledEditReceipt);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.claimDetailID>(cache, row, true);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.refNbr>(cache, row, enabledRefNbr);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.employeeID>(cache, row, enabledEmployeeAndBranch);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.branchID>(cache, row, enabledEmployeeAndBranch);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.expenseAccountID>(cache, row, enabledFinancialDetails);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.expenseSubID>(cache, row, enabledFinancialDetails);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.salesAccountID>(cache, row, enabledFinancialDetails && (row.Billable == true));
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.salesSubID>(cache, row, enabledFinancialDetails && (row.Billable == true));
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.taxCategoryID>(cache, row, enabledFinancialDetails);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.customerID>(cache, row, NonProject && !claimReleased);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.customerLocationID>(cache, row, NonProject && !claimReleased);
                action.SetEnabled("Submit", cache.GetStatus(row) != PXEntryStatus.Inserted && row.Hold == true);
                Claim.SetEnabled(cache.GetStatus(row) != PXEntryStatus.Inserted && row.Approved == true && claimExist == false);

                if (row.ContractID != null && (bool)row.Billable && row.TaskID != null)
                {
                    PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(this, row.TaskID);

                    if (task != null && !(bool)task.VisibleInAP)
                    {
                        cache.RaiseExceptionHandling <EPExpenseClaimDetails.taskID>(e.Row, task.TaskCD, new PXSetPropertyException(PM.Messages.TaskInvisibleInModule, task.TaskCD, GL.BatchModule.AP));
                    }
                }

                CurrencyInfo info = (CurrencyInfo)PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Current <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(this, new object[] { row });

                if (info != null && info.CuryRateTypeID != null && info.CuryEffDate != null && row.ExpenseDate != null && info.CuryEffDate < row.ExpenseDate)
                {
                    CurrencyRateType ratetype = (CurrencyRateType)PXSelectorAttribute.Select <CurrencyInfo.curyRateTypeID>(currencyinfo.Cache, info);
                    if (ratetype != null && ratetype.RateEffDays > 0 &&
                        ((TimeSpan)(row.ExpenseDate - info.CuryEffDate)).Days > ratetype.RateEffDays)
                    {
                        PXRateIsNotDefinedForThisDateException exc = new PXRateIsNotDefinedForThisDateException(info.CuryRateTypeID, info.BaseCuryID, info.CuryID, (DateTime)row.ExpenseDate);
                        cache.RaiseExceptionHandling <EPExpenseClaimDetails.expenseDate>(e.Row, ((EPExpenseClaimDetails)e.Row).ExpenseDate, exc);
                    }
                }
                string message = PXUIFieldAttribute.GetError <CurrencyInfo.curyID>(currencyinfo.Cache, info);
                if (string.IsNullOrEmpty(message) && info != null && info.CuryRate == null)
                {
                    message = CM.Messages.RateNotFound;
                }
                if (string.IsNullOrEmpty(message))
                {
                    cache.RaiseExceptionHandling <EPExpenseClaimDetails.curyID>(e.Row, null, null);
                }
                else
                {
                    cache.RaiseExceptionHandling <EPExpenseClaimDetails.curyID>(e.Row, null, new PXSetPropertyException(message, PXErrorLevel.Warning));
                }

                bool allowEdit = this.Accessinfo.UserID == row.CreatedByID;

                if (Employee.Current != null)
                {
                    if (!allowEdit && this.Accessinfo.UserID == Employee.Current.UserID)
                    {
                        allowEdit = true;
                    }

                    if (!allowEdit)
                    {
                        EPWingman wingMan = PXSelectJoin <EPWingman,
                                                          InnerJoin <EPEmployee, On <EPWingman.wingmanID, Equal <EPEmployee.bAccountID> > >,
                                                          Where <EPWingman.employeeID, Equal <Required <EPWingman.employeeID> >,
                                                                 And <EPEmployee.userID, Equal <Required <EPEmployee.userID> > > > > .Select(this, row.EmployeeID, Accessinfo.UserID);

                        if (wingMan != null)
                        {
                            allowEdit = true;
                        }
                    }
                }

                //Another conditions in automation steps
                if (!allowEdit)
                {
                    action.SetEnabled(MsgNotLocalizable.PutOnHold, false);
                }

                bool taxSettingsEnabled = enabledEditReceipt && (epsetup.Current.AllowMixedTaxSettingInClaims == true || CurrentClaimDetails.Current.RefNbr == null);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.taxZoneID>(cache, row, taxSettingsEnabled);
                ValidateProjectAndProjectTask(row);

                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.taxCalcMode>(cache, row, taxSettingsEnabled);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.taxCategoryID>(cache, row, enabledEditReceipt);

                PXUIFieldAttribute.SetVisible <EPExpenseClaimDetails.curyTipAmt>(ClaimDetails.Cache, null, epsetup.Current.NonTaxableTipItem.HasValue || (row.CuryTipAmt ?? 0) != 0);
                Taxes.Cache.SetAllEditPermissions(enabledEditReceipt);
                RaiseOrHideError <EPExpenseClaimDetails.refNbr>(cache, row, legacyClaim && row.Released == false, Messages.LegacyClaim, PXErrorLevel.Warning, row.RefNbr);
                RaiseOrHideError <EPExpenseClaimDetails.claimDetailID>(cache, row, row.LegacyReceipt == true && row.Released == false && !String.IsNullOrEmpty(row.TaxZoneID), Messages.LegacyReceipt, PXErrorLevel.Warning);

                EPEmployee employeeRow     = Employee.Select();
                string     taxZoneID       = EPClaimReceiptController.GetTaxZoneID(this, employeeRow);
                bool       notMatchtaxZone = String.IsNullOrEmpty(row.TaxZoneID) && !String.IsNullOrEmpty(taxZoneID);
                RaiseOrHideError <EPExpenseClaimDetails.taxZoneID>(cache, row, notMatchtaxZone && row.Released == false, Messages.TaxZoneEmpty, PXErrorLevel.Warning);
                if (UseTaxes.Select().Count != 0)
                {
                    cache.RaiseExceptionHandling <EPExpenseClaimDetails.curyTaxTotal>(row, row.CuryTaxTotal,
                                                                                      new PXSetPropertyException(TX.Messages.UseTaxExcludedFromTotals, PXErrorLevel.Warning));
                }
                else
                {
                    cache.RaiseExceptionHandling <EPExpenseClaimDetails.curyTaxTotal>(row, row.CuryTaxTotal, null);
                }
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.claimDetailCD>(cache, row, true);
            }
        }
        public decimal AllocateOverRCTLine(List <POReceiptLineAdjustment> result, POReceiptLine aLine, decimal toDistribute, Int32?branchID)
        {
            var aLCCode = new LandedCostCode();

            aLCCode.AllocationMethod = LandedCostAllocationMethod.ByQuantity;
            decimal baseTotal = GetBaseValue(aLCCode, aLine);

            decimal shareAmt      = Decimal.Zero;
            decimal allocatedAmt  = Decimal.Zero;
            decimal allocatedBase = Decimal.Zero;

            List <Type> bql = new List <Type>
            {
                typeof(Select4 <, ,>),
                typeof(POReceiptLineSplit),
                typeof(Where <POReceiptLineSplit.receiptNbr, Equal <Required <POReceiptLine.receiptNbr> >, And <POReceiptLineSplit.lineNbr, Equal <Required <POReceiptLine.lineNbr> > > >),
                typeof(Aggregate <>),
                typeof(GroupBy <,>),
                typeof(POReceiptLineSplit.locationID),
                typeof(GroupBy <,>),
                typeof(POReceiptLineSplit.subItemID),
                typeof(Sum <,>),
                typeof(POReceiptLineSplit.baseQty),
                typeof(GroupBy <>),
                typeof(POReceiptLineSplit.lotSerialNbr)
            };

            InventoryItem ii = (InventoryItem)PXSelectorAttribute.Select <POReceiptLine.inventoryID>(_graph.Caches[typeof(POReceiptLine)], aLine);
            bool          requierelotserial = ii.ValMethod == INValMethod.Specific;

            if (!requierelotserial)
            {
                bql.RemoveAt(bql.Count - 1);
                bql.RemoveAt(bql.Count - 1);
                bql[bql.Count - 2] = typeof(Sum <>);
            }

            PXView splitsView = new PXView(_graph, false, BqlCommand.CreateInstance(bql.ToArray()));

            bool hasSplits = false;

            foreach (POReceiptLineSplit split in splitsView.SelectMulti(aLine.ReceiptNbr, aLine.LineNbr))
            {
                hasSplits = true;
                decimal allocatingBase = split.BaseQty ?? 0m;
                shareAmt = CalcAllocationValue(aLCCode, split, aLine, baseTotal, toDistribute);
                shareAmt = PXDBCurrencyAttribute.BaseRound(_graph, shareAmt);

                //accu rounding
                shareAmt += PXCurrencyAttribute.BaseRound(_graph, (allocatedBase + allocatingBase) * toDistribute / baseTotal - shareAmt - allocatedAmt);

                if (shareAmt != Decimal.Zero)
                {
                    POReceiptLine newPOReceiptLine = (POReceiptLine)_graph.Caches[typeof(POReceiptLine)].CreateCopy(aLine);
                    newPOReceiptLine.LocationID   = split.LocationID;
                    newPOReceiptLine.SiteID       = split.SiteID;
                    newPOReceiptLine.SubItemID    = split.SubItemID;
                    newPOReceiptLine.LotSerialNbr = requierelotserial ? split.LotSerialNbr : null;
                    result.Add(new POReceiptLineAdjustment(newPOReceiptLine, shareAmt, branchID));
                    allocatedAmt  += shareAmt;
                    allocatedBase += allocatingBase;
                }
            }
            if (!hasSplits)
            {
                shareAmt = toDistribute;
                shareAmt = PXDBCurrencyAttribute.BaseRound(_graph, shareAmt);
                if (shareAmt != Decimal.Zero)
                {
                    result.Add(new POReceiptLineAdjustment(aLine, shareAmt, branchID));
                }

                allocatedAmt = shareAmt;
            }
            return(allocatedAmt);
        }
Пример #4
0
        protected virtual void CATransfer_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            CATransfer transfer = (CATransfer)e.Row;

            if (transfer == null)
            {
                return;
            }
            CMSetup setup = cmsetup.Current;

            transfer.RGOLAmt = transfer.TranIn - transfer.TranOut;

            bool transferOnHold      = (transfer.Hold == true);
            bool transferNotReleased = (transfer.Released != true);
            bool transferReleased    = (transfer.Released == true);
            bool msActivated         = (setup.MCActivated == true);

            PXUIFieldAttribute.SetVisible <CATransfer.inCuryID>                             (sender, transfer, msActivated);
            PXUIFieldAttribute.SetVisible <CATransfer.outCuryID>                            (sender, transfer, msActivated);
            PXUIFieldAttribute.SetVisible <CATransfer.rGOLAmt>                              (sender, transfer, msActivated);
            PXUIFieldAttribute.SetVisible <CATransfer.inGLBalance>                          (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.outGLBalance>                     (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.cashBalanceIn>                    (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.cashBalanceOut>                   (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.tranIDIn_CATran_batchNbr> (sender, transfer, transferReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.tranIDOut_CATran_batchNbr>(sender, transfer, transferReleased);

            PXUIFieldAttribute.SetEnabled(sender, transfer, false);


            AddTrxFilter filter = AddFilter.Current;

            if (filter != null)
            {
                PXUIFieldAttribute.SetEnabled(AddFilter.Cache, filter, transferNotReleased);
                AddFilter.Cache.AllowUpdate = transferNotReleased;
            }

            sender.AllowDelete             = transferNotReleased;
            sender.AllowUpdate             = transferNotReleased;
            TransferTran.Cache.AllowDelete = transferNotReleased;


            CashAccount cashaccountOut = (CashAccount)PXSelectorAttribute.Select <CATransfer.outAccountID>(sender, e.Row);
            CashAccount cashaccountIn  = (CashAccount)PXSelectorAttribute.Select <CATransfer.inAccountID>(sender, e.Row);

            bool clearEnabledIn  = transferNotReleased && (cashaccountIn != null) && (cashaccountIn.Reconcile == true);
            bool clearEnabledOut = transferNotReleased && (cashaccountOut != null) && (cashaccountOut.Reconcile == true);

            PXUIFieldAttribute.SetEnabled <CATransfer.hold>        (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.transferNbr> (sender, transfer, true);
            PXUIFieldAttribute.SetEnabled <CATransfer.descr>       (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.curyTranIn>  (sender, transfer, transferNotReleased && (transfer.OutCuryID != transfer.InCuryID));
            PXUIFieldAttribute.SetEnabled <CATransfer.inAccountID> (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.inDate>      (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.inExtRefNbr> (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.curyTranOut> (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outAccountID>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outDate>     (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outExtRefNbr>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearedOut>  (sender, transfer, clearEnabledOut);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearDateOut>(sender, transfer, clearEnabledOut && transfer.ClearedOut == true);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearedIn>   (sender, transfer, clearEnabledIn);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearDateIn> (sender, transfer, clearEnabledIn && transfer.ClearedIn == true);


            TransferTran.Cache.AllowInsert = false;
            TransferTran.Cache.AllowUpdate = false;

            AddFilter.Cache.RaiseRowSelected(AddFilter.Current);

            Release.SetEnabled(transferNotReleased && !transferOnHold);
            PrepareAdd.SetEnabled(transferNotReleased);
        }
Пример #5
0
        private static void CreateMemo(ARInvoiceEntry graph, ARRegister doc, RUTROT rutrot, string docType, bool OnRelease = false)
        {
            DuplicateFilter filter = PXCache <DuplicateFilter> .CreateCopy(graph.duplicatefilter.Current);

            foreach (PXResult <ARInvoice, CurrencyInfo, Terms, Customer> res in ARInvoice_CurrencyInfo_Terms_Customer.Select(graph, (object)doc.DocType, doc.RefNbr, doc.CustomerID))
            {
                CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy((CurrencyInfo)res);

                info.CuryInfoID = null;
                info.IsReadOnly = false;
                info            = PXCache <CurrencyInfo> .CreateCopy(graph.currencyinfo.Insert(info));

                ARInvoice invoice = (ARInvoice)graph.Document.Cache.CreateInstance();

                if (docType == ARDocType.CreditMemo)
                {
                    invoice.DueDate     = null;
                    invoice.DiscDate    = null;
                    invoice.CustomerID  = doc.CustomerID;
                    invoice.ARAccountID = doc.ARAccountID;
                    invoice.ARSubID     = doc.ARSubID;
                }

                if (docType == ARInvoiceType.DebitMemo)
                {
                    invoice.DueDate  = ((ARInvoice)res).DueDate;
                    invoice.DiscDate = ((ARInvoice)res).DiscDate;

                    BranchRUTROT branchRUTROT = GetBranchRUTROT(graph);

                    invoice.CustomerID  = branchRUTROT.TaxAgencyAccountID;
                    invoice.ARAccountID = null;
                    invoice.ARSubID     = null;
                }

                ARInvoiceRUTROT invoiceRUTROT = RUTROTHelper.GetExtensionNullable <ARInvoice, ARInvoiceRUTROT>(invoice);
                invoiceRUTROT.IsRUTROTDeductible = false;

                invoice.CuryInfoID = info.CuryInfoID;
                invoice.DocType    = docType;
                invoice.OrigModule = GL.BatchModule.AR;
                invoice.RefNbr     = null;
                invoice.OrigModule = GL.BatchModule.AR;
                invoice.DocDesc    = PXLocalizer.LocalizeFormat(RUTROTMessages.MemoDescription, doc.RefNbr);

                invoice.OpenDoc    = true;
                invoice.Released   = false;
                invoice.Hold       = false;
                invoice.Printed    = false;
                invoice.Emailed    = false;
                invoice.BatchNbr   = null;
                invoice.ScheduleID = null;
                invoice.Scheduled  = false;
                invoice.NoteID     = null;
                invoice.RefNoteID  = null;

                invoice.TermsID             = null;
                invoice.InstallmentCntr     = null;
                invoice.InstallmentNbr      = null;
                invoice.CuryOrigDiscAmt     = 0m;
                invoice.FinPeriodID         = doc.FinPeriodID;
                invoice.OrigDocDate         = invoice.DocDate;
                invoice.CuryLineTotal       = 0m;
                invoice.IsTaxPosted         = false;
                invoice.IsTaxValid          = false;
                invoice.CuryVatTaxableTotal = 0m;
                invoice.CuryVatExemptTotal  = 0m;
                invoice.StatementDate       = null;
                invoice.PendingPPD          = false;
                invoice.CustomerLocationID  = null;

                if (!string.IsNullOrEmpty(invoice.PaymentMethodID))
                {
                    CA.PaymentMethod pm = null;

                    if (invoice.CashAccountID.HasValue)
                    {
                        CA.PaymentMethodAccount pmAccount = null;
                        PXResult <CA.PaymentMethod, CA.PaymentMethodAccount> pmResult = (PXResult <CA.PaymentMethod, CA.PaymentMethodAccount>)
                                                                                        PXSelectJoin <CA.PaymentMethod,
                                                                                                      LeftJoin <
                                                                                                          CA.PaymentMethodAccount, On <CA.PaymentMethod.paymentMethodID, Equal <CA.PaymentMethodAccount.paymentMethodID> > >,
                                                                                                      Where <
                                                                                                          CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> >,
                                                                                                          And <CA.PaymentMethodAccount.cashAccountID, Equal <Required <CA.PaymentMethodAccount.cashAccountID> > > > > .
                                                                                        Select(graph, invoice.PaymentMethodID, invoice.CashAccountID);

                        pm        = pmResult;
                        pmAccount = pmResult;

                        if (pm == null || pm.UseForAR == false || pm.IsActive == false)
                        {
                            invoice.PaymentMethodID = null;
                            invoice.CashAccountID   = null;
                        }
                        else if (pmAccount == null || pmAccount.CashAccountID == null || pmAccount.UseForAR != true)
                        {
                            invoice.CashAccountID = null;
                        }
                    }
                    else
                    {
                        pm = PXSelect <CA.PaymentMethod,
                                       Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > >
                             .Select(graph, invoice.PaymentMethodID);

                        if (pm == null || pm.UseForAR == false || pm.IsActive == false)
                        {
                            invoice.PaymentMethodID = null;
                            invoice.CashAccountID   = null;
                            invoice.PMInstanceID    = null;
                        }
                    }

                    if (invoice.PMInstanceID.HasValue)
                    {
                        CustomerPaymentMethod cpm = PXSelect <CustomerPaymentMethod,
                                                              Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .
                                                    Select(graph, invoice.PMInstanceID);

                        if (string.IsNullOrEmpty(invoice.PaymentMethodID) || cpm == null || cpm.IsActive == false || cpm.PaymentMethodID != invoice.PaymentMethodID)
                        {
                            invoice.PMInstanceID = null;
                        }
                    }
                }
                else
                {
                    invoice.CashAccountID = null;
                    invoice.PMInstanceID  = null;
                }

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARInvoice.salesPersonID>(graph.Document.Cache, invoice);

                if (sp == null || sp.IsActive == false)
                {
                    invoice.SalesPersonID = null;
                }

                invoice = graph.Document.Insert(invoice);
            }

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

            graph.FieldDefaulting.AddHandler <ARTran.salesPersonID>((sender, e) =>
            {
                e.NewValue = null;
                e.Cancel   = true;
            });

            decimal roundedTotalDistributedLinesAmt = 0m;

            foreach (ARTran srcTran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >,
                                                                And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr))
            {
                ARTran tran = PXCache <ARTran> .CreateCopy(srcTran);

                ARTranRUTROT tranRR = RUTROTHelper.GetExtensionNullable <ARTran, ARTranRUTROT>(tran);

                if (tranRR.IsRUTROTDeductible != true)
                {
                    continue;
                }

                tran.TranType = graph.Document.Current.DocType;
                tran.RefNbr   = graph.Document.Current.RefNbr;
                string origDrCr = tran.DrCr;
                tran.DrCr                        = null;
                tran.Released                    = null;
                tran.CuryInfoID                  = null;
                tran.SOOrderNbr                  = null;
                tran.SOShipmentNbr               = null;
                tran.OrigInvoiceDate             = tran.TranDate;
                tran.NoteID                      = null;
                tran.ManualPrice                 = true;
                tran.CuryTranAmt                 = Math.Floor(tranRR.CuryRUTROTAvailableAmt ?? 0m);
                roundedTotalDistributedLinesAmt += tran.CuryTranAmt ?? 0m;
                tranRR.IsRUTROTDeductible        = false;

                if (!string.IsNullOrEmpty(tran.DeferredCode))
                {
                    DRSchedule schedule = PXSelect <DRSchedule,
                                                    Where <DRSchedule.module, Equal <BQLConstants.moduleAR>,
                                                           And <DRSchedule.docType, Equal <Required <DRSchedule.docType> >,
                                                                And <DRSchedule.refNbr, Equal <Required <DRSchedule.refNbr> >,
                                                                     And <DRSchedule.lineNbr, Equal <Required <DRSchedule.lineNbr> > > > > > > .
                                          Select(graph, doc.DocType, doc.RefNbr, tran.LineNbr);

                    if (schedule != null)
                    {
                        tran.DefScheduleID = schedule.ScheduleID;
                    }
                }

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARTran.salesPersonID>(graph.Transactions.Cache, tran);

                if (sp == null || sp.IsActive == false)
                {
                    tran.SalesPersonID = null;
                }

                ARTran insertedTran = graph.Transactions.Insert(tran);
                PXNoteAttribute.CopyNoteAndFiles(graph.Transactions.Cache, srcTran, graph.Transactions.Cache, insertedTran);

                insertedTran.ManualDisc = true;

                insertedTran.TaxCategoryID = null;
                graph.Transactions.Update(insertedTran);
            }

            decimal distributedFee = (rutrot.CuryDistributedAmt ?? 0m) - roundedTotalDistributedLinesAmt;

            if (distributedFee != 0m)
            {
                foreach (ARTran artran in graph.Transactions.Cache.Inserted)
                {
                    if (Math.Round(distributedFee) == 0m)
                    {
                        break;
                    }
                    if (artran.CuryTranAmt != 0m)
                    {
                        artran.CuryTranAmt += Math.Sign(distributedFee);
                        distributedFee     -= Math.Sign(distributedFee);
                    }

                    graph.Transactions.Update(artran);
                }
            }

            graph.Document.Current.CuryOrigDocAmt = graph.Document.Current.CuryDocBal;
            graph.Document.Cache.Update(graph.Document.Current);

            graph.RowInserting.AddHandler <ARSalesPerTran>((sender, e) => { e.Cancel = true; });

            foreach (ARSalesPerTran salespertran in PXSelect <ARSalesPerTran, Where <ARSalesPerTran.docType, Equal <Required <ARSalesPerTran.docType> >,
                                                                                     And <ARSalesPerTran.refNbr, Equal <Required <ARSalesPerTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr))
            {
                ARSalesPerTran newtran = PXCache <ARSalesPerTran> .CreateCopy(salespertran);

                newtran.DocType         = graph.Document.Current.DocType;
                newtran.RefNbr          = graph.Document.Current.RefNbr;
                newtran.Released        = false;
                newtran.CuryInfoID      = null;
                newtran.CuryCommnblAmt *= -1m;
                newtran.CuryCommnAmt   *= -1m;

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARSalesPerTran.salespersonID>(graph.salesPerTrans.Cache, newtran);

                if (!(sp == null || sp.IsActive == false))
                {
                    graph.salesPerTrans.Update(newtran);
                }
            }

            var discountDetailsSet = PXSelect <ARInvoiceDiscountDetail,
                                               Where <ARInvoiceDiscountDetail.docType, Equal <Required <ARInvoice.docType> >,
                                                      And <ARInvoiceDiscountDetail.refNbr, Equal <Required <ARInvoice.refNbr> > > >,
                                               OrderBy <Asc <ARInvoiceDiscountDetail.docType,
                                                             Asc <ARInvoiceDiscountDetail.refNbr> > > >
                                     .Select(graph, doc.DocType, doc.RefNbr);

            foreach (ARInvoiceDiscountDetail discountDetail in discountDetailsSet)
            {
                ARInvoiceDiscountDetail newDiscountDetail = PXCache <ARInvoiceDiscountDetail> .CreateCopy(discountDetail);

                newDiscountDetail.DocType  = graph.Document.Current.DocType;
                newDiscountDetail.RefNbr   = graph.Document.Current.RefNbr;
                newDiscountDetail.IsManual = true;
                DiscountEngineProvider.GetEngineFor <ARTran, ARInvoiceDiscountDetail>().UpdateDiscountDetail(graph.ARDiscountDetails.Cache, graph.ARDiscountDetails, newDiscountDetail);
            }

            graph.Save.Press();

            if (docType == ARDocType.CreditMemo && !OnRelease)
            {
                CreateAdjustment(graph, doc, graph.Document.Current);
            }
        }
Пример #6
0
        /// <summary>
        /// Launches the AppointmentEntry screen with some preloaded values.
        /// </summary>
        /// <param name="fsWrkProcessRow"><c>FSWrkProcess</c> row.</param>
        public static int?LaunchAppointmentEntryScreen(PXGraph graph, FSWrkProcess fsWrkProcessRow, bool redirect = true)
        {
            AppointmentEntry graphAppointmentEntry = PXGraph.CreateInstance <AppointmentEntry>();

            List <string> soDetIDList  = GetParameterList(fsWrkProcessRow.LineRefList, SEPARATOR);
            List <string> employeeList = GetParameterList(fsWrkProcessRow.EmployeeIDList, SEPARATOR);

            if (fsWrkProcessRow.AppointmentID != null)
            {
                graphAppointmentEntry.AppointmentRecords.Current = graphAppointmentEntry.AppointmentRecords.Search <FSAppointment.appointmentID>(fsWrkProcessRow.AppointmentID, fsWrkProcessRow.SrvOrdType);
                AssignAppointmentRoom(graphAppointmentEntry, fsWrkProcessRow);
                AssignAppointmentEmployeeByList(graphAppointmentEntry, employeeList, soDetIDList);
            }
            else
            {
                FSAppointment  fsAppointmentRow  = new FSAppointment();
                FSServiceOrder fsServiceOrderRow = GetServiceOrder(graph, fsWrkProcessRow);
                fsAppointmentRow.SrvOrdType = GetSrvOrdType(graph, fsWrkProcessRow, fsServiceOrderRow);

                if (fsAppointmentRow.SrvOrdType == null)
                {
                    throw new PXException(TX.Error.DEFAULT_SERVICE_ORDER_TYPE_NOT_DEFINED);
                }

                if (fsAppointmentRow.SOID == null)
                {
                    SharedFunctions.ValidateSrvOrdTypeNumberingSequence(graph, fsAppointmentRow.SrvOrdType);
                }

                graphAppointmentEntry.AppointmentRecords.Current = graphAppointmentEntry.AppointmentRecords.Insert(fsAppointmentRow);

                #region ScheduleDateTime Fields
                // to know if we want to set false to the flag KeepTotalServicesDuration
                bool scheduleTimeFlag = true;

                if (fsWrkProcessRow.ScheduledDateTimeBegin.HasValue == true)
                {
                    graphAppointmentEntry.AppointmentRecords.SetValueExt <FSAppointment.scheduledDateTimeBegin>
                        (graphAppointmentEntry.AppointmentRecords.Current,
                        fsWrkProcessRow.ScheduledDateTimeBegin);
                }
                else
                {
                    scheduleTimeFlag = false;
                }

                if (fsWrkProcessRow.ScheduledDateTimeEnd.HasValue && scheduleTimeFlag)
                {
                    graphAppointmentEntry.AppointmentRecords.SetValueExt <FSAppointment.handleManuallyScheduleTime>
                        (graphAppointmentEntry.AppointmentRecords.Current, true);

                    if (fsWrkProcessRow.ScheduledDateTimeBegin != fsWrkProcessRow.ScheduledDateTimeEnd)
                    {
                        graphAppointmentEntry.AppointmentRecords.SetValueExt <FSAppointment.scheduledDateTimeEnd>
                            (graphAppointmentEntry.AppointmentRecords.Current,
                            fsWrkProcessRow.ScheduledDateTimeEnd);
                    }
                    else
                    {
                        graphAppointmentEntry.AppointmentRecords.SetValueExt <FSAppointment.scheduledDateTimeEnd>
                            (graphAppointmentEntry.AppointmentRecords.Current,
                            fsWrkProcessRow.ScheduledDateTimeBegin.Value.AddHours(1));
                    }
                }

                #endregion

                #region ServiceOrder Fields

                if (fsServiceOrderRow == null)
                {
                    if (fsWrkProcessRow.BranchID.HasValue == true)
                    {
                        graphAppointmentEntry.ServiceOrderRelated.SetValueExt <FSServiceOrder.branchID>
                            (graphAppointmentEntry.ServiceOrderRelated.Current,
                            fsWrkProcessRow.BranchID);
                    }

                    if (fsWrkProcessRow.BranchLocationID.HasValue == true && fsWrkProcessRow.BranchLocationID > 0)
                    {
                        graphAppointmentEntry.ServiceOrderRelated.SetValueExt <FSServiceOrder.branchLocationID>
                            (graphAppointmentEntry.ServiceOrderRelated.Current,
                            fsWrkProcessRow.BranchLocationID);
                    }

                    if (fsWrkProcessRow.CustomerID.HasValue == true && fsWrkProcessRow.CustomerID > 0)
                    {
                        graphAppointmentEntry.ServiceOrderRelated.SetValueExt <FSServiceOrder.customerID>
                            (graphAppointmentEntry.ServiceOrderRelated.Current,
                            fsWrkProcessRow.CustomerID);
                    }
                }
                else
                {
                    graphAppointmentEntry.AppointmentRecords.SetValueExt <FSAppointment.soRefNbr>
                        (graphAppointmentEntry.AppointmentRecords.Current,
                        fsServiceOrderRow.RefNbr);
                }

                AssignAppointmentRoom(graphAppointmentEntry, fsWrkProcessRow, fsServiceOrderRow);

                #endregion

                #region Get Appointment Values

                #region Services
                soDetIDList.Reverse();

                if (soDetIDList.Count > 0)
                {
                    var appointmentDetails = graphAppointmentEntry.AppointmentDetails.Select().RowCast <FSAppointmentDet>()
                                             .Where(x => x.IsInventoryItem == false);

                    foreach (FSAppointmentDet fsAppointmentDetRow in appointmentDetails)
                    {
                        if (soDetIDList.Contains(fsAppointmentDetRow.SODetID.ToString()) == false)
                        {
                            graphAppointmentEntry.AppointmentDetails.Delete(fsAppointmentDetRow);
                        }
                        else
                        {
                            InsertEmployeeLinkedToService(graphAppointmentEntry, employeeList, fsAppointmentDetRow.LineRef);
                        }
                    }

                    var employees = graphAppointmentEntry.AppointmentServiceEmployees.Select()
                                    .RowCast <FSAppointmentEmployee>()
                                    .Where(_ => _.ServiceLineRef != null);

                    foreach (FSAppointmentEmployee fsAppointmentEmployeeRow in employees)
                    {
                        FSAppointmentDet fsAppointmentDetRow = (FSAppointmentDet)PXSelectorAttribute.Select <FSAppointmentEmployee.serviceLineRef>
                                                                   (graphAppointmentEntry.AppointmentServiceEmployees.Cache,
                                                                   fsAppointmentEmployeeRow);

                        if (fsAppointmentDetRow != null && soDetIDList.Contains(fsAppointmentDetRow.SODetID.ToString()) == false)
                        {
                            graphAppointmentEntry.AppointmentServiceEmployees.Delete(fsAppointmentEmployeeRow);
                        }
                    }
                }
                #endregion
                #region Employees

                AssignAppointmentEmployeeByList(graphAppointmentEntry, employeeList, soDetIDList);

                #endregion
                #region Equipment
                List <string> equipmentList = GetParameterList(fsWrkProcessRow.EquipmentIDList, SEPARATOR);
                equipmentList.Reverse();

                if (equipmentList.Count > 0)
                {
                    for (int i = 0; i < equipmentList.Count; i++)
                    {
                        FSAppointmentResource fsAppointmentResourceRow = new FSAppointmentResource();

                        fsAppointmentResourceRow.SMEquipmentID = (int?)Convert.ToInt32(equipmentList[i]);
                        graphAppointmentEntry.AppointmentResources.Insert(fsAppointmentResourceRow);
                    }
                }
                #endregion
                #endregion
            }

            if (fsWrkProcessRow.SMEquipmentID.HasValue == true)
            {
                graphAppointmentEntry.AppointmentRecords.SetValueExt <FSAppointment.mem_SMequipmentID>
                    (graphAppointmentEntry.AppointmentRecords.Current,
                    fsWrkProcessRow.SMEquipmentID);

                redirect = true;
            }

            if (redirect == true)
            {
                throw new PXRedirectRequiredException(graphAppointmentEntry, null)
                      {
                          Mode = PXBaseRedirectException.WindowMode.Same
                      };
            }
            else
            {
                try
                {
                    graphAppointmentEntry.RecalculateExternalTaxesSync = true;
                    graphAppointmentEntry.Actions.PressSave();
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    graphAppointmentEntry.RecalculateExternalTaxesSync = false;
                }

                return(graphAppointmentEntry.AppointmentRecords.Current?.AppointmentID);
            }
        }
Пример #7
0
        protected virtual void CATransfer_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            CATransfer transfer = (CATransfer)e.Row;

            if (transfer == null)
            {
                return;
            }

            transfer.RGOLAmt = transfer.TranIn - transfer.TranOut;

            bool transferOnHold      = (transfer.Hold == true);
            bool transferNotReleased = (transfer.Released != true);
            bool transferReleased    = (transfer.Released == true);
            bool msFeatureInstalled  = PXAccess.FeatureInstalled <FeaturesSet.multicurrency>();

            PXUIFieldAttribute.SetVisible <CATransfer.inCuryID>                             (sender, transfer, msFeatureInstalled);
            PXUIFieldAttribute.SetVisible <CATransfer.outCuryID>                            (sender, transfer, msFeatureInstalled);
            PXUIFieldAttribute.SetVisible <CATransfer.rGOLAmt>                              (sender, transfer, msFeatureInstalled);
            PXUIFieldAttribute.SetVisible <CATransfer.inGLBalance>                          (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.outGLBalance>                     (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.cashBalanceIn>                    (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.cashBalanceOut>                   (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.tranIDIn_CATran_batchNbr> (sender, transfer, transferReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.tranIDOut_CATran_batchNbr>(sender, transfer, transferReleased);

            PXUIFieldAttribute.SetEnabled(sender, transfer, false);


            AddTrxFilter filter = AddFilter.Current;

            if (filter != null)
            {
                PXUIFieldAttribute.SetEnabled(AddFilter.Cache, filter, transferNotReleased);
                AddFilter.Cache.AllowUpdate = transferNotReleased;
            }

            sender.AllowDelete             = transferNotReleased;
            sender.AllowUpdate             = transferNotReleased;
            TransferTran.Cache.AllowDelete = transferNotReleased;


            CashAccount cashaccountOut = (CashAccount)PXSelectorAttribute.Select <CATransfer.outAccountID>(sender, e.Row);
            CashAccount cashaccountIn  = (CashAccount)PXSelectorAttribute.Select <CATransfer.inAccountID>(sender, e.Row);

            bool clearEnabledIn  = transferNotReleased && (cashaccountIn != null) && (cashaccountIn.Reconcile == true);
            bool clearEnabledOut = transferNotReleased && (cashaccountOut != null) && (cashaccountOut.Reconcile == true);

            PXUIFieldAttribute.SetEnabled <CATransfer.hold>        (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.transferNbr> (sender, transfer, true);
            PXUIFieldAttribute.SetEnabled <CATransfer.descr>       (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.curyTranIn>  (sender, transfer, transferNotReleased && (transfer.OutCuryID != transfer.InCuryID));
            PXUIFieldAttribute.SetEnabled <CATransfer.inAccountID> (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.inDate>      (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.inExtRefNbr> (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.curyTranOut> (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outAccountID>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outDate>     (sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outExtRefNbr>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearedOut>  (sender, transfer, clearEnabledOut);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearDateOut>(sender, transfer, clearEnabledOut && transfer.ClearedOut == true);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearedIn>   (sender, transfer, clearEnabledIn);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearDateIn> (sender, transfer, clearEnabledIn && transfer.ClearedIn == true);


            TransferTran.Cache.AllowInsert = false;
            TransferTran.Cache.AllowUpdate = false;

            AddFilter.Cache.RaiseRowSelected(AddFilter.Current);
            Release.SetEnabled(transferNotReleased && !transferOnHold);
            PrepareAdd.SetEnabled(transferNotReleased && cashaccountIn != null && cashaccountOut != null && !(String.IsNullOrEmpty(transfer.InExtRefNbr)) && !(String.IsNullOrEmpty(transfer.OutExtRefNbr)) && transfer.InDate.HasValue && transfer.OutDate.HasValue);

            if (transfer.Released != true && transfer.OutDate > transfer.InDate)
            {
                sender.RaiseExceptionHandling <CATransfer.inDate>(transfer, transfer.InDate, new PXSetPropertyException(Messages.EarlyInDate, PXErrorLevel.Warning));
            }
            else
            {
                sender.RaiseExceptionHandling <CATransfer.inDate>(transfer, transfer.InDate, null);
            }
        }
Пример #8
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);
        }
Пример #9
0
        protected virtual void EPExpenseClaimDetails_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
        {
            EPExpenseClaimDetails row = (EPExpenseClaimDetails)e.Row;

            if (row != null)
            {
                EPExpenseClaim claim = (EPExpenseClaim)PXSelect <EPExpenseClaim, Where <EPExpenseClaim.refNbr, Equal <Required <EPExpenseClaimDetails.refNbr> > > > .SelectSingleBound(this, new object[] { null }, row.RefNbr);

                bool enabledApprovalReceipt   = PXAccess.FeatureInstalled <FeaturesSet.approvalWorkflow>() && epsetup.Current.ClaimDetailsAssignmentMapID != null;
                bool enabledEditReceipt       = row.Hold == true || !enabledApprovalReceipt;
                bool enabledRefNbr            = true;
                bool enabledEmployeeAndBranch = enabledEditReceipt && !(row.ClaimCuryInfoID == null && cache.AllowUpdate && !string.IsNullOrEmpty(row.RefNbr));
                bool enabledFinancialDetails  = (row.Rejected != true) && (row.Released != true);

                if (claim != null)
                {
                    bool enabledEditClaim = (row.HoldClaim == true);
                    enabledEditReceipt = enabledEditReceipt && enabledEditClaim;
                    EPExpenseClaimDetails receiptnBase = (EPExpenseClaimDetails)PXSelectReadonly <EPExpenseClaimDetails, Where <EPExpenseClaimDetails.claimDetailID, Equal <Required <EPExpenseClaimDetails.claimDetailID> > > > .SelectSingleBound(this, new object[] { null }, row.ClaimDetailID);

                    enabledRefNbr            = (receiptnBase?.RefNbr == null);
                    enabledEmployeeAndBranch = false;
                    enabledFinancialDetails  = enabledFinancialDetails && enabledEditClaim;
                }

                Approval.AllowSelect = enabledApprovalReceipt;
                Delete.SetEnabled(enabledEditReceipt && claim == null);
                PXUIFieldAttribute.SetEnabled(cache, row, enabledEditReceipt);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.claimDetailID>(cache, row, true);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.refNbr>(cache, row, enabledRefNbr);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.employeeID>(cache, row, enabledEmployeeAndBranch);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.branchID>(cache, row, enabledEmployeeAndBranch);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.expenseAccountID>(cache, row, enabledFinancialDetails);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.expenseSubID>(cache, row, enabledFinancialDetails);
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.salesAccountID>(cache, row, enabledFinancialDetails && (row.Billable == true));
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.salesSubID>(cache, row, enabledFinancialDetails && (row.Billable == true));
                PXUIFieldAttribute.SetEnabled <EPExpenseClaimDetails.taxCategoryID>(cache, row, enabledFinancialDetails);
                action.SetEnabled("Submit", cache.GetStatus(row) != PXEntryStatus.Inserted && row.Hold == true);

                if (row.ContractID != null && (bool)row.Billable && row.TaskID != null)
                {
                    PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(this, row.TaskID);

                    if (task != null && !(bool)task.VisibleInAP)
                    {
                        cache.RaiseExceptionHandling <EPExpenseClaimDetails.taskID>(e.Row, task.TaskCD, new PXSetPropertyException(PM.Messages.TaskInvisibleInModule, task.TaskCD, GL.BatchModule.AP));
                    }
                }

                CurrencyInfo info = (CurrencyInfo)PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Current <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(this, new object[] { row });

                if (info != null && info.CuryRateTypeID != null && info.CuryEffDate != null && row.ExpenseDate != null && info.CuryEffDate < row.ExpenseDate)
                {
                    CurrencyRateType ratetype = (CurrencyRateType)PXSelectorAttribute.Select <CurrencyInfo.curyRateTypeID>(currencyinfo.Cache, info);
                    if (ratetype != null && ratetype.RateEffDays > 0 &&
                        ((TimeSpan)(row.ExpenseDate - info.CuryEffDate)).Days > ratetype.RateEffDays)
                    {
                        PXRateIsNotDefinedForThisDateException exc = new PXRateIsNotDefinedForThisDateException(info.CuryRateTypeID, info.BaseCuryID, info.CuryID, (DateTime)row.ExpenseDate);
                        cache.RaiseExceptionHandling <EPExpenseClaimDetails.expenseDate>(e.Row, ((EPExpenseClaimDetails)e.Row).ExpenseDate, exc);
                    }
                }
                string message = PXUIFieldAttribute.GetError <CurrencyInfo.curyID>(currencyinfo.Cache, info);
                if (string.IsNullOrEmpty(message) && info != null && info.CuryRate == null)
                {
                    message = CM.Messages.RateNotFound;
                }
                if (string.IsNullOrEmpty(message))
                {
                    cache.RaiseExceptionHandling <EPExpenseClaimDetails.curyID>(e.Row, null, null);
                }
                else
                {
                    cache.RaiseExceptionHandling <EPExpenseClaimDetails.curyID>(e.Row, null, new PXSetPropertyException(message, PXErrorLevel.Warning));
                }
            }
        }
Пример #10
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);
            }
Пример #11
0
        public virtual Result Calculate(PMProject project, PMTran pmt, PMAccountGroup ag, string accountType, int amountSign, int qtySign)
        {
            PMBudgetLite target = null;
            bool         isExisting;

            target = service.SelectProjectBalance(pmt, ag, project, out isExisting);

            var rollupQty = CalculateRollupQty(pmt, target);

            List <PMHistory>  list     = new List <PMHistory>();
            PMTaskTotal       ta       = null;
            PMBudget          ps       = null;
            PMForecastHistory forecast = null;

            if (pmt.TaskID != null && (rollupQty != 0 || pmt.Amount != 0))             //TaskID will be null for Contract
            {
                ps                = new PMBudget();
                ps.ProjectID      = target.ProjectID;
                ps.ProjectTaskID  = target.TaskID;
                ps.AccountGroupID = target.AccountGroupID;
                ps.Type           = target.Type;
                ps.InventoryID    = target.InventoryID;
                ps.CostCodeID     = target.CostCodeID;
                ps.UOM            = target.UOM;
                ps.IsProduction   = target.IsProduction;
                ps.Description    = target.Description;
                if (ps.CuryInfoID == null)
                {
                    ps.CuryInfoID = project.CuryInfoID;
                }
                decimal amt     = amountSign * pmt.Amount.GetValueOrDefault();
                decimal curyAmt = amountSign * pmt.ProjectCuryAmount.GetValueOrDefault();

                ps.ActualQty        = rollupQty * qtySign;
                ps.ActualAmount     = amt;
                ps.CuryActualAmount = curyAmt;

                #region PMTask Totals Update

                ta           = new PMTaskTotal();
                ta.ProjectID = ps.ProjectID;
                ta.TaskID    = ps.TaskID;

                string accType = ag.IsExpense == true ? AccountType.Expense : ag.Type;
                switch (accType)
                {
                case AccountType.Asset:
                    ta.CuryAsset = curyAmt;
                    ta.Asset     = amt;
                    break;

                case AccountType.Liability:
                    ta.CuryLiability = curyAmt;
                    ta.Liability     = amt;
                    break;

                case AccountType.Income:
                    ta.CuryIncome = curyAmt;
                    ta.Income     = amt;
                    break;

                case AccountType.Expense:
                    ta.CuryExpense = curyAmt;
                    ta.Expense     = amt;
                    break;
                }

                #endregion

                #region History
                PMHistory hist = new PMHistory();
                hist.ProjectID      = ps.ProjectID;
                hist.ProjectTaskID  = ps.TaskID;
                hist.AccountGroupID = ps.AccountGroupID;
                hist.InventoryID    = pmt.InventoryID ?? ps.InventoryID;
                hist.CostCodeID     = pmt.CostCodeID ?? ps.CostCodeID;
                hist.PeriodID       = pmt.FinPeriodID;
                hist.BranchID       = pmt.BranchID;
                decimal baseQty = 0;
                list.Add(hist);
                if (pmt.InventoryID != null && pmt.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID && pmt.Qty != 0)
                {
                    if (PXAccess.FeatureInstalled <FeaturesSet.multipleUnitMeasure>())
                    {
                        baseQty = qtySign * IN.INUnitAttribute.ConvertToBase(graph.Caches[typeof(PMHistory)], pmt.InventoryID, pmt.UOM, pmt.Qty.Value, PX.Objects.IN.INPrecision.QUANTITY);
                    }
                    else
                    {
                        IN.InventoryItem initem = PXSelectorAttribute.Select <PMTran.inventoryID>(graph.Caches[typeof(PMTran)], pmt) as IN.InventoryItem;
                        if (initem != null && !string.IsNullOrEmpty(pmt.UOM))
                        {
                            baseQty = qtySign * IN.INUnitAttribute.ConvertGlobalUnits(graph, pmt.UOM, initem.BaseUnit, pmt.Qty ?? 0, IN.INPrecision.QUANTITY);
                        }
                    }
                }
                hist.FinPTDCuryAmount = curyAmt;
                hist.FinPTDAmount     = amt;
                hist.FinYTDCuryAmount = curyAmt;
                hist.FinYTDAmount     = amt;
                hist.FinPTDQty        = baseQty;
                hist.FinYTDQty        = baseQty;
                if (pmt.FinPeriodID == pmt.TranPeriodID)
                {
                    hist.TranPTDCuryAmount = curyAmt;
                    hist.TranPTDAmount     = amt;
                    hist.TranYTDCuryAmount = curyAmt;
                    hist.TranYTDAmount     = amt;
                    hist.TranPTDQty        = baseQty;
                    hist.TranYTDQty        = baseQty;
                }
                else
                {
                    PMHistory tranHist = new PMHistory();
                    tranHist.ProjectID      = ps.ProjectID;
                    tranHist.ProjectTaskID  = ps.TaskID;
                    tranHist.AccountGroupID = ps.AccountGroupID;
                    tranHist.InventoryID    = pmt.InventoryID ?? PM.PMInventorySelectorAttribute.EmptyInventoryID;
                    tranHist.CostCodeID     = pmt.CostCodeID ?? CostCodeAttribute.GetDefaultCostCode();
                    tranHist.PeriodID       = pmt.TranPeriodID;
                    tranHist.BranchID       = pmt.BranchID;
                    list.Add(tranHist);
                    tranHist.TranPTDCuryAmount = curyAmt;
                    tranHist.TranPTDAmount     = amt;
                    tranHist.TranYTDCuryAmount = curyAmt;
                    tranHist.TranYTDAmount     = amt;
                    tranHist.TranPTDQty        = baseQty;
                    tranHist.TranYTDQty        = baseQty;
                }
                #endregion

                forecast                  = new PMForecastHistory();
                forecast.ProjectID        = ps.ProjectID;
                forecast.ProjectTaskID    = ps.ProjectTaskID;
                forecast.AccountGroupID   = ps.AccountGroupID;
                forecast.InventoryID      = ps.InventoryID;
                forecast.CostCodeID       = ps.CostCodeID;
                forecast.PeriodID         = pmt.TranPeriodID;
                forecast.ActualQty        = ps.ActualQty;
                forecast.CuryActualAmount = ps.CuryActualAmount;
                forecast.ActualAmount     = ps.ActualAmount;
            }
            return(new Result(list, ps, ta, forecast));
        }
        public static void ReleaseDoc(EPExpenseClaim claim)
        {
            #region prepare required variables
            APInvoiceEntry    docgraph          = PXGraph.CreateInstance <APInvoiceEntry>();
            ExpenseClaimEntry expenseClaimGraph = PXGraph.CreateInstance <ExpenseClaimEntry>();

            EPExpenseClaim checkClaim = PXSelect <EPExpenseClaim, Where <EPExpenseClaim.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr);


            if (checkClaim.Released == true)
            {
                throw new PXException(Messages.AlreadyReleased);
            }

            var receiptsResult = PXSelect <EPExpenseClaimDetails,
                                           Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr);

            IFinPeriodUtils finPeriodUtils = expenseClaimGraph.GetService <IFinPeriodUtils>();

            if (claim.FinPeriodID != null)
            {
                finPeriodUtils.ValidateFinPeriod <EPExpenseClaimDetails>(receiptsResult.RowCast <EPExpenseClaimDetails>(), m => claim.FinPeriodID, m => m.BranchID.SingleToArray());
            }

            var receipts = receiptsResult.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

            if (claim.FinPeriodID != null)
            {
                finPeriodUtils.ValidateFinPeriod(claim.SingleToArray());
            }

            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;
                    if (claim.FinPeriodID == null)
                    {
                        APOpenPeriodAttribute.DefaultFirstOpenPeriod <APInvoice.finPeriodID>(docgraph.Document.Cache);
                    }
                    else
                    {
                        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>(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 == CT.CTPRType.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, expenseClaimGraph, 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, 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
                        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;
                    }

                    invoice.Approved = true;

                    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);
            }
        }
Пример #13
0
        protected virtual void CATransfer_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            CATransfer transfer = (CATransfer)e.Row;

            if (transfer == null)
            {
                return;
            }

            transfer.RGOLAmt = transfer.TranIn - transfer.TranOut;

            bool transferOnHold      = (transfer.Hold == true);
            bool transferNotReleased = (transfer.Released != true);
            bool transferReleased    = (transfer.Released == true);
            bool msFeatureInstalled  = PXAccess.FeatureInstalled <FeaturesSet.multicurrency>();

            PXUIFieldAttribute.SetVisible <CATransfer.inCuryID>(sender, transfer, msFeatureInstalled);
            PXUIFieldAttribute.SetVisible <CATransfer.outCuryID>(sender, transfer, msFeatureInstalled);
            PXUIFieldAttribute.SetVisible <CATransfer.rGOLAmt>(sender, transfer, msFeatureInstalled);
            PXUIFieldAttribute.SetVisible <CATransfer.inGLBalance>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.outGLBalance>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.cashBalanceIn>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.cashBalanceOut>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.tranIDIn_CATran_batchNbr>(sender, transfer, transferReleased);
            PXUIFieldAttribute.SetVisible <CATransfer.tranIDOut_CATran_batchNbr>(sender, transfer, transferReleased);

            PXUIFieldAttribute.SetEnabled(sender, transfer, false);

            sender.AllowDelete = transferNotReleased;
            sender.AllowUpdate = transferNotReleased;
            Expenses.Cache.SetAllEditPermissions(transferNotReleased);

            CashAccount cashaccountOut = (CashAccount)PXSelectorAttribute.Select <CATransfer.outAccountID>(sender, e.Row);
            CashAccount cashaccountIn  = (CashAccount)PXSelectorAttribute.Select <CATransfer.inAccountID>(sender, e.Row);

            bool clearEnabledIn  = transferNotReleased && (cashaccountIn != null) && (cashaccountIn.Reconcile == true);
            bool clearEnabledOut = transferNotReleased && (cashaccountOut != null) && (cashaccountOut.Reconcile == true);

            PXUIFieldAttribute.SetEnabled <CATransfer.hold>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.transferNbr>(sender, transfer, true);
            PXUIFieldAttribute.SetEnabled <CATransfer.descr>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.curyTranIn>(sender, transfer, transferNotReleased && (transfer.OutCuryID != transfer.InCuryID));
            PXUIFieldAttribute.SetEnabled <CATransfer.inAccountID>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.inDate>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.inExtRefNbr>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.curyTranOut>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outAccountID>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outDate>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.outExtRefNbr>(sender, transfer, transferNotReleased);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearedOut>(sender, transfer, clearEnabledOut);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearDateOut>(sender, transfer, clearEnabledOut && transfer.ClearedOut == true);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearedIn>(sender, transfer, clearEnabledIn);
            PXUIFieldAttribute.SetEnabled <CATransfer.clearDateIn>(sender, transfer, clearEnabledIn && transfer.ClearedIn == true);

            Release.SetEnabled(transferNotReleased && !transferOnHold);
            Reverse.SetEnabled(transferReleased);

            UIState.RaiseOrHideErrorByErrorLevelPriority <CATransfer.inDate>(sender, transfer, transfer.Released != true && transfer.OutDate > transfer.InDate, Messages.EarlyInDate, PXErrorLevel.Warning);

            SetAdjRefNbrVisibility();
        }
Пример #14
0
        protected virtual void INTran_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            InventoryItem item = (InventoryItem)PXSelectorAttribute.Select <INTran.inventoryID>(sender, e.Row);

            PXUIFieldAttribute.SetEnabled <INTran.unitCost>(sender, e.Row, (item == null || item.ValMethod != INValMethod.Standard));
        }
Пример #15
0
        protected virtual IEnumerable enqResult()
        {
            GLHistoryEnqFilter filter = (GLHistoryEnqFilter)this.Filter.Current;
            bool showCurrency         = filter.ShowCuryDetail.HasValue && filter.ShowCuryDetail.Value;

            PXUIFieldAttribute.SetVisible <GLHistoryEnquiryResult.curyID>(EnqResult.Cache, null, showCurrency);
            PXUIFieldAttribute.SetVisible <GLHistoryEnquiryResult.curyPtdCreditTotal>(EnqResult.Cache, null, showCurrency);
            PXUIFieldAttribute.SetVisible <GLHistoryEnquiryResult.curyPtdDebitTotal>(EnqResult.Cache, null, showCurrency);
            PXUIFieldAttribute.SetVisible <GLHistoryEnquiryResult.curyBegBalance>(EnqResult.Cache, null, showCurrency);
            PXUIFieldAttribute.SetVisible <GLHistoryEnquiryResult.curyEndBalance>(EnqResult.Cache, null, showCurrency);
            PXUIFieldAttribute.SetVisible <GLHistoryEnquiryResult.signCuryBegBalance>(EnqResult.Cache, null, showCurrency);
            PXUIFieldAttribute.SetVisible <GLHistoryEnquiryResult.signCuryEndBalance>(EnqResult.Cache, null, showCurrency);
            if (filter.LedgerID == null || filter.FinPeriodID == null)
            {
                yield break;                 //Prevent code from accessing database;
            }
            #region cmd
            PXSelectBase <GLHistoryByPeriod> cmd = new PXSelectJoinGroupBy <GLHistoryByPeriod,
                                                                            InnerJoin <Account,
                                                                                       On <GLHistoryByPeriod.accountID, Equal <Account.accountID>, And <Match <Account, Current <AccessInfo.userName> > > >,
                                                                                       InnerJoin <Sub,
                                                                                                  On <GLHistoryByPeriod.subID, Equal <Sub.subID>, And <Match <Sub, Current <AccessInfo.userName> > > >,
                                                                                                  LeftJoin <GLHistory, On <GLHistoryByPeriod.accountID, Equal <GLHistory.accountID>,
                                                                                                                           And <GLHistoryByPeriod.ledgerID, Equal <GLHistory.ledgerID>,
                                                                                                                                And <GLHistoryByPeriod.branchID, Equal <GLHistory.branchID>,
                                                                                                                                     And <GLHistoryByPeriod.subID, Equal <GLHistory.subID>,
                                                                                                                                          And <GLHistoryByPeriod.finPeriodID, Equal <GLHistory.finPeriodID> > > > > >,
                                                                                                            LeftJoin <AH, On <GLHistoryByPeriod.ledgerID, Equal <AH.ledgerID>,
                                                                                                                              And <GLHistoryByPeriod.branchID, Equal <AH.branchID>,
                                                                                                                                   And <GLHistoryByPeriod.accountID, Equal <AH.accountID>,
                                                                                                                                        And <GLHistoryByPeriod.subID, Equal <AH.subID>,
                                                                                                                                             And <GLHistoryByPeriod.lastActivityPeriod, Equal <AH.finPeriodID> > > > > > > > > >,
                                                                            Where <GLHistoryByPeriod.ledgerID, Equal <Current <GLHistoryEnqFilter.ledgerID> >,
                                                                                   And <GLHistoryByPeriod.finPeriodID, Equal <Current <GLHistoryEnqFilter.finPeriodID> >,
                                                                                        And <
                                                                                            Where2 <
                                                                                                Where <Account.accountID, NotEqual <Current <GLSetup.ytdNetIncAccountID> >, And <Where <Account.type, Equal <AccountType.asset>,
                                                                                                                                                                                        Or <Account.type, Equal <AccountType.liability> > > > >,
                                                                                                Or <Where <GLHistoryByPeriod.lastActivityPeriod, GreaterEqual <Required <GLHistoryByPeriod.lastActivityPeriod> >,
                                                                                                           And <Where <Account.type, Equal <AccountType.expense>,
                                                                                                                       Or <Account.type, Equal <AccountType.income>,
                                                                                                                           Or <Account.accountID, Equal <Current <GLSetup.ytdNetIncAccountID> > > > > > > > > > > >,
                                                                            Aggregate <
                                                                                Sum <AH.finYtdBalance,
                                                                                     Sum <AH.tranYtdBalance,
                                                                                          Sum <AH.curyFinYtdBalance,
                                                                                               Sum <AH.curyTranYtdBalance,
                                                                                                    Sum <GLHistory.finPtdDebit,
                                                                                                         Sum <GLHistory.tranPtdDebit,
                                                                                                              Sum <GLHistory.finPtdCredit,
                                                                                                                   Sum <GLHistory.tranPtdCredit,
                                                                                                                        Sum <GLHistory.finBegBalance,
                                                                                                                             Sum <GLHistory.tranBegBalance,
                                                                                                                                  Sum <GLHistory.finYtdBalance,
                                                                                                                                       Sum <GLHistory.tranYtdBalance,
                                                                                                                                            Sum <GLHistory.curyFinBegBalance,
                                                                                                                                                 Sum <GLHistory.curyTranBegBalance,
                                                                                                                                                      Sum <GLHistory.curyFinYtdBalance,
                                                                                                                                                           Sum <GLHistory.curyTranYtdBalance,
                                                                                                                                                                Sum <GLHistory.curyFinPtdCredit,
                                                                                                                                                                     Sum <GLHistory.curyTranPtdCredit,
                                                                                                                                                                          Sum <GLHistory.curyFinPtdDebit,
                                                                                                                                                                               Sum <GLHistory.curyTranPtdDebit,
                                                                                                                                                                                    GroupBy <GLHistoryByPeriod.branchID,
                                                                                                                                                                                             GroupBy <GLHistoryByPeriod.ledgerID,
                                                                                                                                                                                                      GroupBy <GLHistoryByPeriod.accountID,
                                                                                                                                                                                                               GroupBy <GLHistoryByPeriod.finPeriodID
                                                                                                                                                                                                                        > > > > > > > > > > > > > > > > > > > > > > > > > >(this);

            if (filter.LedgerID != null)
            {
                Ledger ledger = (Ledger)PXSelectorAttribute.Select <GLHistoryEnqFilter.ledgerID>(Filter.Cache, filter);
                if (ledger?.BalanceType == LedgerBalanceType.Budget)
                {
                    // we shouldn't select history from the previous years for the budget ledgers
                    cmd.WhereAnd <Where <Substring <GLHistoryByPeriod.finPeriodID, int1, int4>, Equal <Substring <GLHistoryByPeriod.lastActivityPeriod, int1, int4> > > >();
                }
            }
            if (filter.AccountID != null)
            {
                cmd.WhereAnd <Where <GLHistoryByPeriod.accountID, Equal <Current <GLHistoryEnqFilter.accountID> > > >();
            }
            if (filter.AccountClassID != null)
            {
                cmd.WhereAnd <Where <Account.accountClassID, Equal <Current <GLHistoryEnqFilter.accountClassID> > > >();
            }

            if (filter.SubID != null)
            {
                cmd.WhereAnd <Where <GLHistoryByPeriod.subID, Equal <Current <GLHistoryEnqFilter.subID> > > >();
            }

            int[] branchIDs = null;

            if (filter.BranchID != null)
            {
                cmd.WhereAnd <Where <GLHistoryByPeriod.branchID, Equal <Current <GLHistoryEnqFilter.branchID> > > >();
            }
            else if (filter.OrganizationID != null)
            {
                branchIDs = PXAccess.GetChildBranchIDs(filter.OrganizationID, false);

                cmd.WhereAnd <Where <GLHistoryByPeriod.branchID, In <Required <GLHistoryEnqFilter.branchID> >,
                                     And <MatchWithBranch <GLHistoryByPeriod.branchID> > > >();
            }

            if (!SubCDUtils.IsSubCDEmpty(filter.SubCD))
            {
                cmd.WhereAnd <Where <Sub.subCD, Like <Current <GLHistoryEnqFilter.subCDWildcard> > > >();
            }
            //cmd.WhereAnd<Where<Match<Current<AccessInfo.userName>>>>();
            #endregion
            string  yearBegPeriod = filter.BegFinPeriod;
            GLSetup glSetup       = glsetup.Current;
            bool    reverseSign   = (glSetup != null) && (glSetup.TrialBalanceSign == GLSetup.trialBalanceSign.Reversed);
            foreach (PXResult <GLHistoryByPeriod, Account, Sub, GLHistory, AH> it in cmd.Select(yearBegPeriod, branchIDs))
            {
                GLHistoryByPeriod baseview = (GLHistoryByPeriod)it;
                Account           acct     = (Account)it;
                GLHistory         ah       = (GLHistory)it;
                AH ah1 = (AH)it;
                ah.FinFlag  = filter.UseMasterCalendar != true;
                ah1.FinFlag = filter.UseMasterCalendar != true;

                if (reverseSign && acct.AccountID == glSetup.YtdNetIncAccountID)
                {
                    continue;
                }

                GLHistoryEnquiryResult item = new GLHistoryEnquiryResult();
                item.BranchID           = baseview.BranchID;
                item.LedgerID           = baseview.LedgerID;
                item.AccountID          = baseview.AccountID;
                item.AccountCD          = acct.AccountCD;
                item.Type               = acct.Type;
                item.Description        = acct.Description;
                item.LastActivityPeriod = baseview.LastActivityPeriod;
                item.PtdCreditTotal     = ah.PtdCredit ?? 0m;
                item.PtdDebitTotal      = ah.PtdDebit ?? 0m;
                item.EndBalance         = ah1.YtdBalance ?? 0m;
                item.ConsolAccountCD    = acct.GLConsolAccountCD;
                item.AccountClassID     = acct.AccountClassID;
                if (!(string.IsNullOrEmpty(ah.CuryID) && string.IsNullOrEmpty(ah1.CuryID)))
                {
                    item.CuryEndBalance     = ah1.CuryYtdBalance ?? 0m;
                    item.CuryPtdCreditTotal = ah.CuryPtdCredit ?? 0m;
                    item.CuryPtdDebitTotal  = ah.CuryPtdDebit ?? 0m;
                    item.CuryID             = string.IsNullOrEmpty(ah.CuryID) ? ah1.CuryID : ah.CuryID;
                }
                else
                {
                    item.CuryEndBalance     = null;
                    item.CuryPtdCreditTotal = null;
                    item.CuryPtdDebitTotal  = null;
                    item.CuryID             = null;
                }

                item.recalculate(true);                 // End balance is considered as correct digit - so we need to calculate begBalance base on ending one
                item.recalculateSignAmount(reverseSign);
                yield return(item);
            }
        }
Пример #16
0
        protected virtual void DefaultUnitCost(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            if (adjustment.Current != null && adjustment.Current.OrigModule == INRegister.origModule.PI)
            {
                return;
            }

            object UnitCost = null;

            InventoryItem item = (InventoryItem)PXSelectorAttribute.Select <INTran.inventoryID>(sender, e.Row);

            if (item.ValMethod == INValMethod.Specific && string.IsNullOrEmpty(((INTran)e.Row).LotSerialNbr) == false)
            {
                INCostStatus status = PXSelectJoin <INCostStatus,
                                                    LeftJoin <INLocation, On <INLocation.locationID, Equal <Current <INTran.locationID> > >,
                                                              InnerJoin <INCostSubItemXRef, On <INCostSubItemXRef.costSubItemID, Equal <INCostStatus.costSubItemID> > > >,
                                                    Where <INCostStatus.inventoryID, Equal <Current <INTran.inventoryID> >, And2 <Where <INLocation.isCosted, Equal <boolFalse>, And <INCostStatus.costSiteID, Equal <Current <INTran.siteID> >, Or <INCostStatus.costSiteID, Equal <Current <INTran.locationID> > > > >, And <INCostSubItemXRef.subItemID, Equal <Current <INTran.subItemID> >, And <INCostStatus.lotSerialNbr, Equal <Current <INTran.lotSerialNbr> > > > > > > .SelectSingleBound(this, new object[] { e.Row });

                if (status != null && status.QtyOnHand != 0m)
                {
                    UnitCost = PXDBPriceCostAttribute.Round((decimal)(status.TotalCost / status.QtyOnHand));
                }
            }
            else if (item.ValMethod == INValMethod.FIFO && string.IsNullOrEmpty(((INTran)e.Row).OrigRefNbr) == false)
            {
                INCostStatus status = PXSelectJoin <INCostStatus,
                                                    LeftJoin <INLocation, On <INLocation.locationID, Equal <Current <INTran.locationID> > >,
                                                              InnerJoin <INCostSubItemXRef, On <INCostSubItemXRef.costSubItemID, Equal <INCostStatus.costSubItemID> > > >,
                                                    Where <INCostStatus.inventoryID, Equal <Current <INTran.inventoryID> >, And2 <Where <INLocation.isCosted, Equal <boolFalse>, And <INCostStatus.costSiteID, Equal <Current <INTran.siteID> >, Or <INCostStatus.costSiteID, Equal <Current <INTran.locationID> > > > >, And <INCostSubItemXRef.subItemID, Equal <Current <INTran.subItemID> >, And <INCostStatus.receiptNbr, Equal <Current <INTran.origRefNbr> > > > > > > .SelectSingleBound(this, new object[] { e.Row });

                if (status != null && status.QtyOnHand != 0m)
                {
                    UnitCost = PXDBPriceCostAttribute.Round((decimal)(status.TotalCost / status.QtyOnHand));
                }
            }
            else
            {
                if (item.ValMethod == INValMethod.Average)
                {
                    sender.RaiseFieldDefaulting <INTran.avgCost>(e.Row, out UnitCost);
                }
                if (UnitCost == null || (decimal)UnitCost == 0m)
                {
                    sender.RaiseFieldDefaulting <INTran.unitCost>(e.Row, out UnitCost);
                }
            }


            decimal?qty = (decimal?)sender.GetValue <INTran.qty>(e.Row);

            if (UnitCost != null && ((decimal)UnitCost != 0m || qty < 0m))
            {
                if ((decimal)UnitCost < 0m)
                {
                    sender.RaiseFieldDefaulting <INTran.unitCost>(e.Row, out UnitCost);
                }

                decimal?unitcost = INUnitAttribute.ConvertToBase <INTran.inventoryID>(sender, e.Row, ((INTran)e.Row).UOM, (decimal)UnitCost, INPrecision.UNITCOST);

                //suppress trancost recalculation for cost only adjustments
                if (qty == 0m)
                {
                    sender.SetValue <INTran.unitCost>(e.Row, unitcost);
                }
                else
                {
                    sender.SetValueExt <INTran.unitCost>(e.Row, unitcost);
                }
            }
        }
Пример #17
0
        protected virtual void InsertARTran(ARInvoiceEntry arGraph, EPExpenseClaimDetails row, decimal signOperation, decimal tipQty = 1m, bool isTipTransaction = false)
        {
            CurrencyInfo curyInfo = PXSelect <CurrencyInfo> .Search <CurrencyInfo.curyInfoID>(arGraph, row.CuryInfoID);

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


            ARTran tran = arGraph.Transactions.Insert();

            if (isTipTransaction)
            {
                IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                     Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(arGraph, epsetup.NonTaxableTipItem);

                tran.InventoryID = epsetup.NonTaxableTipItem;
                tran.Qty         = tipQty;
                tran.UOM         = tipItem.BaseUnit;
                tran.TranDesc    = tipItem.Descr;

                SetAmount(arGraph, row.CuryTipAmt, row.TipAmt, tipQty, signOperation, curyInfo, tran);
                tran = arGraph.Transactions.Update(tran);

                if (epsetup.UseReceiptAccountForTips == true)
                {
                    tran.AccountID = row.SalesAccountID;
                    tran.SubID     = row.SalesSubID;
                }
                else
                {
                    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 <ARTran.branchID> > > > .Select(arGraph);

                    Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <Contract.contractID> > > > .Select(this, row.ContractID);

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

                    EPEmployee employee = (EPEmployee)PXSelect <EPEmployee> .Search <EPEmployee.bAccountID>(this, row != null?row.EmployeeID : null);

                    Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(arGraph.Caches[typeof(EPExpenseClaimDetails)], row);

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

                    object value = SubAccountMaskAttribute.MakeSub <EPSetup.salesSubMask>(arGraph, epsetup.SalesSubMask,
                                                                                          new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                          new Type[] { typeof(EPEmployee.salesSubID), typeof(IN.InventoryItem.salesSubID), typeof(Location.cSalesSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                    arGraph.Caches[typeof(ARTran)].RaiseFieldUpdating <ARTran.subID>(tran, ref value);
                    tran.SubID = (int?)value;
                }
            }
            else
            {
                tran.InventoryID = row.InventoryID;
                tran.Qty         = row.Qty * signOperation;
                tran.UOM         = row.UOM;
                tran             = arGraph.Transactions.Update(tran);
                tran.AccountID   = row.SalesAccountID;
                tran.SubID       = row.SalesSubID;
                tran.TranDesc    = row.TranDesc;

                //For gross taxes we can't put tranAmt. So we should use taxable amount
                EPTaxTran firstLevelTaxTran = null;
                foreach (EPTaxTran taxRow in PXSelect <EPTaxTran,
                                                       Where <EPTaxTran.claimDetailID, Equal <Required <EPTaxTran.claimDetailID> >,
                                                              And <EPTaxTran.isTipTax, Equal <False> > > > .Select(this, row.ClaimDetailID))
                {
                    if (firstLevelTaxTran == null || Math.Abs(firstLevelTaxTran.CuryTaxableAmt ?? 0m) > Math.Abs(taxRow.CuryTaxableAmt ?? 0m))
                    {
                        firstLevelTaxTran = taxRow;
                    }
                }
                decimal?curyAmt = firstLevelTaxTran?.CuryTaxableAmt ?? row.CuryTaxableAmt;
                decimal?amt     = firstLevelTaxTran?.TaxableAmt ?? row.TaxableAmt;
                SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran);
                tran = arGraph.Transactions.Update(tran);
                if (tran.CuryTaxableAmt != 0 && tran.CuryTaxableAmt != curyAmt)                 // indicates that we have gross/ iclusive taxes. In this case recalculation is required
                {
                    curyAmt = row.CuryTaxableAmt;
                    amt     = row.TaxableAmt;
                    SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran);
                }
            }
            tran.Date        = row.ExpenseDate;
            tran.ManualPrice = true;
            tran             = arGraph.Transactions.Update(tran);
            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], row, arGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.ar>());
        }
Пример #18
0
        public virtual GetTaxRequest BuildGetTaxRequest(PMProforma doc)
        {
            if (doc == null)
            {
                throw new PXArgumentException(ErrorMessages.ArgumentNullException);
            }

            Customer cust = (Customer)Base.Customer.View.SelectSingleBound(new object[] { doc });
            Location loc  = (Location)Base.Location.View.SelectSingleBound(new object[] { doc });

            IAddressBase fromAddress = GetFromAddress(doc);
            IAddressBase toAddress   = GetToAddress(doc);

            if (fromAddress == null)
            {
                throw new PXException(Messages.FailedGetFromAddress);
            }

            if (toAddress == null)
            {
                throw new PXException(Messages.FailedGetToAddress);
            }

            GetTaxRequest request = new GetTaxRequest();

            request.CompanyCode        = CompanyCodeFromBranch(doc.TaxZoneID, doc.BranchID);
            request.CurrencyCode       = doc.CuryID;
            request.CustomerCode       = cust.AcctCD;
            request.OriginAddress      = AddressConverter.ConvertTaxAddress(fromAddress);
            request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
            request.DocCode            = $"PM.{doc.RefNbr}";
            request.DocDate            = doc.InvoiceDate.GetValueOrDefault();
            request.LocationCode       = GetExternalTaxProviderLocationCode(doc);
            request.DocType            = TaxDocumentType.SalesOrder;

            if (!string.IsNullOrEmpty(doc.AvalaraCustomerUsageType))
            {
                request.CustomerUsageType = doc.AvalaraCustomerUsageType;
            }
            if (!string.IsNullOrEmpty(loc.CAvalaraExemptionNumber))
            {
                request.ExemptionNo = loc.CAvalaraExemptionNumber;
            }

            foreach (PMProformaProgressLine tran in Base.ProgressiveLines.Select())
            {
                InventoryItem item         = (InventoryItem)PXSelectorAttribute.Select <PMProformaProgressLine.inventoryID>(Base.ProgressiveLines.Cache, tran);
                Account       salesAccount = (Account)PXSelectorAttribute.Select <PMProformaProgressLine.accountID>(Base.ProgressiveLines.Cache, tran);

                var line = new TaxCartItem();
                line.Index = tran.LineNbr ?? 0;

                line.Amount = tran.CuryLineTotal.GetValueOrDefault();

                line.Description        = tran.Description;
                line.DestinationAddress = request.DestinationAddress;
                line.OriginAddress      = request.OriginAddress;
                line.ItemCode           = item.InventoryCD;
                line.Quantity           = tran.Qty.GetValueOrDefault();
                line.Discounted         = request.Discount > 0;
                line.RevAcct            = salesAccount.AccountCD;

                line.TaxCode = tran.TaxCategoryID;

                request.CartItems.Add(line);
            }

            foreach (PMProformaTransactLine tran in Base.TransactionLines.Select())
            {
                InventoryItem item         = (InventoryItem)PXSelectorAttribute.Select <PMProformaTransactLine.inventoryID>(Base.TransactionLines.Cache, tran);
                Account       salesAccount = (Account)PXSelectorAttribute.Select <PMProformaTransactLine.accountID>(Base.TransactionLines.Cache, tran);

                var line = new TaxCartItem();
                line.Index = tran.LineNbr ?? 0;

                line.Amount = tran.CuryLineTotal.GetValueOrDefault();

                line.Description        = tran.Description;
                line.DestinationAddress = request.DestinationAddress;
                line.OriginAddress      = request.OriginAddress;
                line.ItemCode           = item.InventoryCD;
                line.Quantity           = tran.Qty.GetValueOrDefault();
                line.Discounted         = request.Discount > 0;
                line.RevAcct            = salesAccount.AccountCD;

                line.TaxCode = tran.TaxCategoryID;

                request.CartItems.Add(line);
            }

            return(request);
        }
Пример #19
0
        protected override BqlCommand WhereAnd(PXCache sender, PXSelectorAttribute selattr, Type Where)
        {
            Type newWhere = IsReportOrInterBranchFeatureEnabled(sender) ? EmptyWhere : _interBranchWhere;

            return(base.WhereAnd(sender, selattr, newWhere));
        }
        public virtual Result Calculate(PMTran pmt, PMAccountGroup ag, Account acc, int mult)
        {
            PMBudget status = SelectProjectBalance(pmt);

            int?      inventoryID = status != null ? status.InventoryID : PMInventorySelectorAttribute.EmptyInventoryID;
            int?      costCodeID  = status != null ? status.CostCodeID : CostCodeAttribute.GetDefaultCostCode();
            RollupQty rollup      = null;

            if (settings.CostBudgetUpdateMode == CostBudgetUpdateModes.Detailed && ag.IsExpense == true && pmt.InventoryID != settings.EmptyInventoryID)
            {
                if (status == null || status.InventoryID == settings.EmptyInventoryID)
                {
                    rollup      = new RollupQty(pmt.UOM, pmt.Qty);
                    inventoryID = pmt.InventoryID;
                    if (pmt.CostCodeID != null)
                    {
                        costCodeID = pmt.CostCodeID;
                    }
                }
            }

            if (rollup == null)
            {
                rollup = CalculateRollupQty(pmt, status);
            }

            List <PMHistory> list = new List <PMHistory>();

            PMTaskTotal ta = null;
            PMBudget    ps = null;

            if (pmt.TaskID != null && (rollup.Qty != 0 || pmt.Amount != 0))             //TaskID will be null for Contract
            {
                ps                = new PMBudget();
                ps.ProjectID      = pmt.ProjectID;
                ps.ProjectTaskID  = pmt.TaskID;
                ps.AccountGroupID = ag.GroupID;
                if (ag.Type == PMAccountType.OffBalance)
                {
                    ps.Type = ag.IsExpense == true ? GL.AccountType.Expense : ag.Type;
                }
                else
                {
                    ps.Type = ag.Type;
                }
                ps.InventoryID = inventoryID;
                ps.CostCodeID  = costCodeID;
                ps.UOM         = rollup.UOM;
                if (status != null)
                {
                    ps.IsProduction = status.IsProduction;
                }

                decimal amt = mult * pmt.Amount.GetValueOrDefault();

                if (!string.IsNullOrEmpty(ps.UOM))
                {
                    ps.ActualQty = rollup.Qty;                     // commented out otherwise invoice produces -ve Qty. * mult;
                }
                ps.ActualAmount = amt;

                #region PMTask Totals Update

                ta           = new PMTaskTotal();
                ta.ProjectID = pmt.ProjectID;
                ta.TaskID    = pmt.TaskID;

                string accType = null;
                int    multFix = 1;             //flip back the sign if it was changed because of ag.Type<>acc.type
                if (pmt.TranType == BatchModule.PM && acc != null && !string.IsNullOrEmpty(acc.Type))
                {
                    //Only transactions that originated in PM were inverted and require to be fixed.
                    accType = ag.Type;

                    if (acc.Type != ag.Type)
                    {
                        multFix = -1;
                    }
                }
                else
                {
                    accType = ag.Type;
                }

                switch (accType)
                {
                case AccountType.Asset:
                    ta.Asset = amt * multFix;
                    break;

                case AccountType.Liability:
                    ta.Liability = amt * multFix;
                    break;

                case AccountType.Income:
                    ta.Income = amt * multFix;
                    break;

                case AccountType.Expense:
                    ta.Expense = amt * multFix;
                    break;
                }

                #endregion

                #region History
                PMHistory hist = new PMHistory();
                hist.ProjectID      = pmt.ProjectID;
                hist.ProjectTaskID  = pmt.TaskID;
                hist.AccountGroupID = ag.GroupID;
                hist.InventoryID    = pmt.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID;
                hist.CostCodeID     = pmt.CostCodeID ?? CostCodeAttribute.GetDefaultCostCode();
                hist.PeriodID       = pmt.FinPeriodID;
                decimal baseQty = 0;
                list.Add(hist);
                if (pmt.InventoryID != null && pmt.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID && pmt.Qty != 0 && !string.IsNullOrEmpty(rollup.UOM))
                {
                    if (PXAccess.FeatureInstalled <FeaturesSet.multipleUnitMeasure>())
                    {
                        baseQty = mult * IN.INUnitAttribute.ConvertToBase(graph.Caches[typeof(PMHistory)], pmt.InventoryID, pmt.UOM, pmt.Qty.Value, PX.Objects.IN.INPrecision.QUANTITY);
                    }
                    else
                    {
                        IN.InventoryItem initem = PXSelectorAttribute.Select <PMTran.inventoryID>(graph.Caches[typeof(PMTran)], pmt) as IN.InventoryItem;
                        if (initem != null)
                        {
                            baseQty = mult * IN.INUnitAttribute.ConvertGlobalUnits(graph, pmt.UOM, initem.BaseUnit, pmt.Qty ?? 0, IN.INPrecision.QUANTITY);
                        }
                    }
                }
                hist.FinPTDAmount = amt;
                hist.FinYTDAmount = amt;
                hist.FinPTDQty    = baseQty;
                hist.FinYTDQty    = baseQty;
                if (pmt.FinPeriodID == pmt.TranPeriodID)
                {
                    hist.TranPTDAmount = amt;
                    hist.TranYTDAmount = amt;
                    hist.TranPTDQty    = baseQty;
                    hist.TranYTDQty    = baseQty;
                }
                else
                {
                    PMHistory tranHist = new PMHistory();
                    tranHist.ProjectID      = pmt.ProjectID;
                    tranHist.ProjectTaskID  = pmt.TaskID;
                    tranHist.AccountGroupID = ag.GroupID;
                    tranHist.InventoryID    = pmt.InventoryID ?? PM.PMInventorySelectorAttribute.EmptyInventoryID;
                    tranHist.CostCodeID     = pmt.CostCodeID ?? CostCodeAttribute.GetDefaultCostCode();
                    tranHist.PeriodID       = pmt.TranPeriodID;
                    list.Add(tranHist);
                    tranHist.TranPTDAmount = amt;
                    tranHist.TranYTDAmount = amt;
                    tranHist.TranPTDQty    = baseQty;
                    tranHist.TranYTDQty    = baseQty;
                }
                #endregion
            }
            return(new Result(list, ps, ta));
        }
Пример #21
0
        // <summary>
        /// Get the total BOM/Operations material cost.
        /// Copy standard method and add one more parameter to control qty round-up.
        /// </summary>
        protected virtual OperationCosts GetMaterialCost(AMBomCost currentAMBomCost, IEnumerable <PXResult <AMBomMatl, InventoryItem> > material, bool isMultLevel, out List <string> materialMessage, bool roundup = true)
        {
            materialMessage = new List <string>();

            if (currentAMBomCost == null || string.IsNullOrWhiteSpace(currentAMBomCost.BOMID) || material == null)
            {
                return(null);
            }

            var operationMaterialCosts = new OperationCosts();

            foreach (var result in material)
            {
                var matlRec       = (AMBomMatl)result;
                var inventoryItem = (InventoryItem)result;

                if (matlRec?.BOMID == null || inventoryItem?.InventoryCD == null)
                {
                    continue;
                }

                decimal?unitcost   = null;
                var     matlSiteID = matlRec.SiteID ?? currentAMBomCost.SiteID;
                if (isMultLevel)
                {
                    var bomManager = new PrimaryBomIDManager(this);
                    var bomItem    = PrimaryBomIDManager.GetNotArchivedRevisionBomItem(this, bomManager.GetPrimaryAllLevels(inventoryItem,
                                                                                                                            JAMS.AM.InventoryHelper.CacheQueryINItemSite(ItemSiteRecs.Cache, matlRec.InventoryID, matlSiteID),
                                                                                                                            matlRec.SubItemID));
                    unitcost = GetCurrentBomCost(bomItem?.BOMID, bomItem?.RevisionID);
                }

                if (unitcost == null)
                {
                    unitcost = GetUnitCost(inventoryItem, matlSiteID);
                }

                var inUnit = (INUnit)PXSelectorAttribute.Select <AMBomMatl.uOM>(this.Caches <AMBomMatl>(), matlRec) ??
                             (INUnit)PXSelect <INUnit, Where <INUnit.inventoryID, Equal <Required <INUnit.inventoryID> >,
                                                              And <INUnit.fromUnit, Equal <Required <INUnit.fromUnit> > > > > .Select(this, matlRec.InventoryID, matlRec.UOM);

                if (inUnit == null)
                {
                    materialMessage.Add(JAMS.AM.Messages.GetLocal(JAMS.AM.Messages.InvalidUOMForMaterialonBOM, matlRec.UOM.TrimIfNotNullEmpty(), inventoryItem.InventoryCD, matlRec.BOMID, matlRec.RevisionID));
                    continue;
                }

                if (UomHelper.TryConvertToBaseCost <AMBomMatl.inventoryID>(BomMatlRecs.Cache, matlRec, matlRec.UOM, unitcost.GetValueOrDefault(), out var matlUnitCost))
                {
                    unitcost = matlUnitCost.GetValueOrDefault();
                }

                var itemExt = inventoryItem.GetExtension <JAMS.AEF.InventoryItemAMExtension>();

                var totalQtyRequired = matlRec.QtyReq.GetValueOrDefault() *
                                       (1 + (Settings.Current.IncMatScrp.GetValueOrDefault() ? matlRec.ScrapFactor.GetValueOrDefault() : 0m)) * (matlRec.BatchSize.GetValueOrDefault() == 0m
                                       ? 1m
                                       : currentAMBomCost.LotSize.GetValueOrDefault() / matlRec.BatchSize.GetValueOrDefault());

                // Use new parameter to determine the qty request round-up per Peter's request.
                if (roundup == true)
                {
                    totalQtyRequired = itemExt.AMQtyRoundUp == false ? totalQtyRequired : Math.Ceiling(totalQtyRequired);
                }

                var matlCost = totalQtyRequired * unitcost.GetValueOrDefault();

                operationMaterialCosts.Add(matlRec.OperationID, matlCost, true);

                if (Settings.Current.UpdateMaterial.GetValueOrDefault())
                {
                    UpdateMaterialUnitCost(matlRec, unitcost);
                }
            }

            return(operationMaterialCosts);
        }