Пример #1
0
        protected virtual void Location_IsAPAccountSameAsMain_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            CR.Location record = (CR.Location)e.Row;

            if (record.IsAPAccountSameAsMain == false)
            {
                LocationAPAccountSub mainloc = APAccountSubLocation.Select();
                record.VAPAccountID         = mainloc.VAPAccountID;
                record.VAPSubID             = mainloc.VAPSubID;
                record.VAPAccountLocationID = record.LocationID;

                LocationAPAccountSub copyloc = new LocationAPAccountSub();
                copyloc.BAccountID   = record.BAccountID;
                copyloc.LocationID   = record.LocationID;
                copyloc.VAPAccountID = record.VAPAccountID;
                copyloc.VAPSubID     = record.VAPSubID;

                BusinessAccount.Cache.Current = (BAccount)PXParentAttribute.SelectParent(sender, e.Row, typeof(BAccount));
                APAccountSubLocation.Insert(copyloc);
            }
            if (record.IsAPAccountSameAsMain == true)
            {
                record.VAPAccountID = null;
                record.VAPSubID     = null;
                BAccount baccount = (BAccount)PXParentAttribute.SelectParent(sender, e.Row, typeof(BAccount));
                if (baccount != null)
                {
                    record.VAPAccountLocationID = baccount.DefLocationID;
                }
            }
        }
        protected IAddressBase GetToAddress(PMQuote quote)
        {
            CRAddress crShipAddress = PXSelect <CRAddress, Where <CRAddress.addressID, Equal <Required <CRAddress.addressID> > > > .Select(Base, quote.OpportunityAddressID);

            if (crShipAddress != null)
            {
                return(crShipAddress);
            }

            Address shipAddress = null;

            CR.Location loc = (CR.Location) PXSelect <CR.Location,
                                                      Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .
                              Select(Base, quote.BAccountID, quote.LocationID);

            if (loc != null)
            {
                shipAddress = PXSelect <Address, Where <Address.addressID, Equal <Required <Address.addressID> > > > .Select(Base, loc.DefAddressID);
            }

            return(shipAddress);
        }
        protected IAddressBase GetToAddress(PMQuote quote)
        {
            var crShipAddress = (CRShippingAddress)Base.Shipping_Address.View.SelectSingleBound(new object[] { quote });

            if (crShipAddress != null)
            {
                return(crShipAddress);
            }

            Address shipAddress = null;

            CR.Location loc = (CR.Location) PXSelect <CR.Location,
                                                      Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .
                              Select(Base, quote.BAccountID, quote.LocationID);

            if (loc != null)
            {
                shipAddress = PXSelect <Address, Where <Address.addressID, Equal <Required <Address.addressID> > > > .Select(Base, loc.DefAddressID);
            }

            return(shipAddress);
        }
        protected virtual void _(Events.FieldDefaulting <PMBudget, PMBudget.rate> e)
        {
            PMAccountGroup ag = PXSelect <PMAccountGroup, Where <PMAccountGroup.groupID, Equal <Required <PMAccountGroup.groupID> > > > .Select(this, e.Row.AccountGroupID);

            if (ag != null)
            {
                if (ag.IsExpense == true)
                {
                    if (e.Row.InventoryID != null && e.Row.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID)
                    {
                        InventoryItem item = (InventoryItem)PXSelectorAttribute.Select <PMCostBudget.inventoryID>(e.Cache, e.Row);
                        e.NewValue = item?.StdCost;
                    }
                }
                else
                {
                    if (e.Row.InventoryID != null && e.Row.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID)
                    {
                        string customerPriceClass = ARPriceClass.EmptyPriceClass;

                        PMTask      projectTask = (PMTask)PXSelectorAttribute.Select <PMRevenueBudget.projectTaskID>(e.Cache, e.Row);
                        CR.Location c           = (CR.Location)PXSelectorAttribute.Select <PMTask.locationID>(e.Cache, projectTask);
                        if (c != null && !string.IsNullOrEmpty(c.CPriceClassID))
                        {
                            customerPriceClass = c.CPriceClassID;
                        }

                        CM.CurrencyInfo dummy = new CM.CurrencyInfo();
                        dummy.CuryID     = Accessinfo.BaseCuryID;
                        dummy.BaseCuryID = Accessinfo.BaseCuryID;
                        dummy.CuryRate   = 1;

                        e.NewValue = ARSalesPriceMaint.CalculateSalesPrice(Caches[typeof(PMTran)], customerPriceClass, projectTask.CustomerID, e.Row.InventoryID, dummy, e.Row.Qty, e.Row.UOM, Accessinfo.BusinessDate.Value, true);
                    }
                }
            }
        }
Пример #5
0
        public virtual decimal GetItemPrice(PXCache sender, string curyID, int?customerID, int?locationID, string contractStatus, int?contractItemID, int?itemID, string itemType, string priceOption, decimal?fixedPrice, decimal?setupPrice, decimal?qty, DateTime?date)
        {
            decimal      itemPrice = 0m;
            ContractItem item      = PXSelect <ContractItem, Where <ContractItem.contractItemID, Equal <Required <ContractItem.contractItemID> > > > .Select(sender.Graph, contractItemID);

            if (item != null)
            {
                IN.InventoryItem nonstock = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(sender.Graph, itemID);

                CR.Location customerLocation = PXSelect <
                    CR.Location,
                    Where <
                        CR.Location.bAccountID, Equal <Required <Contract.customerID> >,
                        And <CR.Location.locationID, Equal <Required <Contract.locationID> > > > >
                                               .Select(sender.Graph, customerID, locationID);

                string customerPriceClass = string.IsNullOrEmpty(customerLocation?.CPriceClassID)
                                        ? ARPriceClass.EmptyPriceClass
                                        : customerLocation.CPriceClassID;

                if (priceOption == null)
                {
                    switch (itemType)
                    {
                    case ContractDetailType.Setup:
                        priceOption = item.BasePriceOption;
                        break;

                    case ContractDetailType.Renewal:
                        priceOption = item.RenewalPriceOption;
                        break;

                    case ContractDetailType.Billing:
                        priceOption = item.FixedRecurringPriceOption;
                        break;

                    case ContractDetailType.UsagePrice:
                        priceOption = item.UsagePriceOption;
                        break;
                    }
                }

                CM.CurrencyInfo currencyInfo = new CM.CurrencyInfo();
                currencyInfo.BaseCuryID = new PXSetup <Company>(sender.Graph).Current.BaseCuryID;
                currencyInfo.CuryID     = curyID;
                Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(sender.Graph, customerID);

                if (customer != null && customer.CuryRateTypeID != null)
                {
                    currencyInfo.CuryRateTypeID = customer.CuryRateTypeID;
                }

                currencyInfo.SetCuryEffDate(sender.Graph.Caches[typeof(CM.CurrencyInfo)], date);

                if (nonstock != null && currencyInfo != null)
                {
                    switch (priceOption)
                    {
                    case PriceOption.ItemPrice:
                        itemPrice = ARSalesPriceMaint.CalculateSalesPrice(sender, customerPriceClass, customerID, itemID, currencyInfo, qty, nonstock.BaseUnit, date ?? DateTime.Now, false) ?? 0m;
                        break;

                    case PriceOption.ItemPercent:
                        itemPrice = ((ARSalesPriceMaint.CalculateSalesPrice(sender, customerPriceClass, customerID, itemID, currencyInfo, qty, nonstock.BaseUnit, date ?? DateTime.Now, false) ?? 0m) / 100m * (fixedPrice ?? 0m));
                        break;

                    case PriceOption.BasePercent:
                        itemPrice = (setupPrice ?? 0m) / 100m * (fixedPrice ?? 0m);
                        break;

                    case PriceOption.Manually:
                        itemPrice = fixedPrice ?? 0m;
                        break;
                    }
                }
            }
            return(itemPrice);
        }
Пример #6
0
        protected virtual List <BillingData> BillTask(PMTask task, PMBillingRule rule, DateTime billingDate)
        {
            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(this, task.ProjectID);

            Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(this, project.CustomerID);

            List <BillingData>               list         = new List <BillingData>();
            Dictionary <int, decimal>        availableQty = new Dictionary <int, decimal>();
            Dictionary <int, ContractDetail> billingItems = new Dictionary <int, ContractDetail>();

            //recurent Billing:
            PXSelectBase <ContractDetail> selectBilling = new PXSelect <ContractDetail,
                                                                        Where <ContractDetail.contractID, Equal <Required <ContractDetail.contractID> >,
                                                                               And <ContractDetail.taskID, Equal <Required <ContractDetail.taskID> > > > >(this);

            foreach (ContractDetail billing in selectBilling.Select(task.ProjectID, task.TaskID))
            {
                billingItems.Add(billing.InventoryID.Value, billing);

                if (billing.Included > 0)
                {
                    if (billing.ResetUsage == ResetUsageOption.OnBilling)
                    {
                        availableQty.Add(billing.InventoryID.Value, billing.Included.Value);
                    }
                    else
                    {
                        decimal qtyLeft = billing.Included.Value - billing.LastBilledQty ?? 0;

                        if (qtyLeft > 0)
                        {
                            availableQty.Add(billing.InventoryID.Value, qtyLeft);
                        }
                    }
                }

                bool bill = false;
                if (billing.ResetUsage == ResetUsageOption.OnBilling)
                {
                    bill = true;
                }
                else
                {
                    if (billing.LastBilledDate == null)
                    {
                        bill = true;
                    }
                }

                if (bill)
                {
                    ARTran arTran = new ARTran();
                    arTran.InventoryID    = billing.InventoryID;
                    arTran.TranDesc       = billing.Description;
                    arTran.Qty            = billing.Included;
                    arTran.UOM            = billing.UOM;
                    arTran.ExtPrice       = billing.ItemFee;
                    arTran.TranAmt        = arTran.ExtPrice;
                    arTran.ProjectID      = task.ProjectID;
                    arTran.TaskID         = task.TaskID;
                    arTran.Commissionable = false;                     //todo

                    string subCD = null;
                    #region Set Account and Subaccount
                    if (billing.AccountSource != PMAccountSource.None)
                    {
                        if (rule.AccountSource == PMAccountSource.RecurringBillingItem)
                        {
                            if (billing.AccountID != null)
                            {
                                arTran.AccountID = billing.AccountID;
                            }
                            else
                            {
                                InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                throw new PXException(Messages.BillingRuleAccountIsNotConfiguredForBillingRecurent, item.InventoryCD);
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.Project)
                        {
                            if (project.DefaultAccountID != null)
                            {
                                arTran.AccountID = project.DefaultAccountID;
                            }
                            else
                            {
                                InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                throw new PXException(Messages.ProjectAccountIsNotConfiguredForBillingRecurent, item.InventoryCD, project.ContractCD);
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.Task)
                        {
                            if (task.DefaultAccountID != null)
                            {
                                arTran.AccountID = task.DefaultAccountID;
                            }
                            else
                            {
                                InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                throw new PXException(Messages.TaskAccountIsNotConfiguredForBillingRecurent, item.InventoryCD, project.ContractCD, task.TaskCD);
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.InventoryItem)
                        {
                            InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                            if (item != null)
                            {
                                if (item.SalesAcctID != null)
                                {
                                    arTran.AccountID = item.SalesAcctID;
                                }
                                else
                                {
                                    throw new PXException(Messages.InventoryAccountIsNotConfiguredForBillingRecurent, item.InventoryCD);
                                }
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.Customer && customer != null)
                        {
                            CR.Location customerLoc = PXSelect <CR.Location, Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .Select(this, customer.BAccountID, customer.DefLocationID);

                            if (customerLoc != null)
                            {
                                if (customerLoc.CSalesAcctID != null)
                                {
                                    arTran.AccountID = customerLoc.CSalesAcctID;
                                }
                                else
                                {
                                    InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                    throw new PXException(Messages.CustomerAccountIsNotConfiguredForBillingRecurent, item.InventoryCD, customer.AcctCD);
                                }
                            }
                        }

                        if (arTran.AccountID == null && !string.IsNullOrEmpty(billing.SubMask))
                        {
                            InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                            throw new PXException(Messages.SubAccountCannotBeComposed, item.InventoryCD);
                        }
                        else if (arTran.AccountID != null && !string.IsNullOrEmpty(billing.SubMask))
                        {
                            subCD = PMRecurentBillSubAccountMaskAttribute.MakeSub <PMBillingRule.subMask>(this, billing.SubMask,
                                                                                                          new object[] { billing.SubID, project.DefaultSubID, task.DefaultSubID },
                                                                                                          new Type[] { typeof(PMBillingRule.subID), typeof(PMProject.defaultSubID), typeof(PMTask.defaultSubID) });
                        }
                    }

                    #endregion

                    list.Add(new BillingData(arTran, rule, null, subCD, null, null));

                    billing.LastBilledDate = billingDate;
                    ContractDetail.Update(billing);
                }
            }



            int            mult = 1;
            PMAccountGroup ag   = PXSelect <PMAccountGroup, Where <PMAccountGroup.groupID, Equal <Required <PMAccountGroup.groupID> > > > .Select(this, rule.AccountGroupID);

            if (ag == null)
            {
                throw new PXException(Messages.AccountGroupInBillingRuleNotFound, rule.BillingID, rule.AccountGroupID);
            }
            if (ag.Type == GL.AccountType.Liability || ag.Type == GL.AccountType.Income)
            {
                mult = -1;
            }

            DateTime cuttofDate = billingDate;            //all transactions  excluding the current day.
            ContractBillingSchedule schedule = PXSelect <ContractBillingSchedule> .Search <ContractBillingSchedule.contractID>(this, task.ProjectID);

            if (schedule != null && schedule.Type == BillingType.OnDemand)
            {
                cuttofDate = billingDate.AddDays(1);                //all transactions including the current day.
            }
            else
            {
                if (IncludeTodaysTransactions)
                {
                    cuttofDate = billingDate.AddDays(1);
                }
            }

            List <PMTran> billingBase = SelectBillingBase(task.ProjectID, task.TaskID, rule.AccountGroupID, cuttofDate,
                                                          rule.IncludeNonBillable == true);

            foreach (PMTran tran in billingBase)
            {
                ARTran arTran = new ARTran();
                arTran.BranchID = tran.BranchID;
                if (tran.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID)
                {
                    arTran.InventoryID = tran.InventoryID;
                }
                arTran.TranDesc = tran.Description;
                arTran.UOM      = tran.UOM;
                arTran.Qty      = tran.BillableQty * mult;
                arTran.ExtPrice = tran.Amount * mult;
                if (arTran.Qty != 0)
                {
                    arTran.UnitPrice = arTran.ExtPrice / arTran.Qty;
                }
                else
                {
                    arTran.UnitPrice = 0;
                }
                arTran.TranAmt        = arTran.ExtPrice;
                arTran.ProjectID      = task.ProjectID;
                arTran.TaskID         = task.TaskID;
                arTran.PMTranID       = tran.TranID;
                arTran.Commissionable = false;                 //todo
                arTran.Date           = tran.Date;

                string subCD = null;
                #region Set Account and Subaccount

                int?employeeSubID = null;

                if (tran.ResourceID != null)
                {
                    EP.EPEmployee emp = PXSelect <EP.EPEmployee, Where <EP.EPEmployee.bAccountID, Equal <Required <EP.EPEmployee.bAccountID> > > > .Select(this, tran.ResourceID);

                    if (emp != null)
                    {
                        employeeSubID = emp.SalesSubID;
                    }
                }

                if (rule.AccountSource != PMAccountSource.None)
                {
                    if (rule.AccountSource == PMAccountSource.BillingRule)
                    {
                        if (rule.AccountID != null)
                        {
                            arTran.AccountID = rule.AccountID;
                        }
                        else
                        {
                            throw new PXException(Messages.BillingRuleAccountIsNotConfiguredForBilling, rule.BillingID);
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Project)
                    {
                        if (project.DefaultAccountID != null)
                        {
                            arTran.AccountID = project.DefaultAccountID;
                        }
                        else
                        {
                            throw new PXException(Messages.ProjectAccountIsNotConfiguredForBilling, rule.BillingID, project.ContractCD);
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Task)
                    {
                        if (task.DefaultAccountID != null)
                        {
                            arTran.AccountID = task.DefaultAccountID;
                        }
                        else
                        {
                            throw new PXException(Messages.TaskAccountIsNotConfiguredForBilling, rule.BillingID, project.ContractCD, task.TaskCD);
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.InventoryItem)
                    {
                        InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, tran.InventoryID);

                        if (item != null)
                        {
                            if (item.SalesAcctID != null)
                            {
                                arTran.AccountID = item.SalesAcctID;
                            }
                            else
                            {
                                throw new PXException(Messages.InventoryAccountIsNotConfiguredForBilling, rule.BillingID, item.InventoryCD);
                            }
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Customer && customer != null)
                    {
                        CR.Location customerLoc = PXSelect <CR.Location, Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .Select(this, customer.BAccountID, customer.DefLocationID);

                        if (customerLoc != null)
                        {
                            if (customerLoc.CSalesAcctID != null)
                            {
                                arTran.AccountID = customerLoc.CSalesAcctID;
                            }
                            else
                            {
                                throw new PXException(Messages.CustomerAccountIsNotConfiguredForBilling, rule.BillingID, customer.AcctCD);
                            }
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Resource)
                    {
                        EP.EPEmployee emp = PXSelect <EP.EPEmployee, Where <EP.EPEmployee.bAccountID, Equal <Required <EP.EPEmployee.bAccountID> > > > .Select(this, tran.ResourceID);

                        if (emp != null)
                        {
                            if (emp.SalesAcctID != null)
                            {
                                arTran.AccountID = emp.SalesAcctID;
                            }
                            else
                            {
                                throw new PXException(Messages.EmployeeAccountIsNotConfiguredForBilling, rule.BillingID, emp.AcctCD);
                            }
                        }
                    }

                    if (arTran.AccountID == null && !string.IsNullOrEmpty(rule.SubMask))
                    {
                        throw new PXException(Messages.SubAccountCannotBeComposed, rule.BillingID);
                    }
                    else if (arTran.AccountID != null && !string.IsNullOrEmpty(rule.SubMask))
                    {
                        subCD = PMBillSubAccountMaskAttribute.MakeSub <PMBillingRule.subMask>(this, rule.SubMask,
                                                                                              new object[] { tran.SubID, rule.SubID, project.DefaultSubID, task.DefaultSubID, employeeSubID },
                                                                                              new Type[] { typeof(PMTran.subID), typeof(PMBillingRule.subID), typeof(PMProject.defaultSubID), typeof(PMTask.defaultSubID), typeof(EP.EPEmployee.salesSubID) });
                    }
                }

                #endregion

                string note  = PXNoteAttribute.GetNote(Transactions.Cache, tran);
                Guid[] files = PXNoteAttribute.GetFileNotes(Transactions.Cache, tran);
                list.Add(new BillingData(arTran, rule, tran, subCD, note, files));

                if (billingItems.ContainsKey(tran.InventoryID.Value))
                {
                    if (availableQty.ContainsKey(tran.InventoryID.Value))
                    {
                        decimal available = availableQty[tran.InventoryID.Value];

                        if (tran.BillableQty <= available)
                        {
                            //Transaction is already payed for as a post payment included. Thus it should be free.
                            arTran.TranDesc = PXMessages.LocalizeNoPrefix(CT.Messages.PrefixIncludedUsage) + " " + tran.Description;
                            availableQty[tran.InventoryID.Value] -= arTran.Qty.Value;                            //decrease available qty
                            arTran.UnitPrice = 0;
                            arTran.ExtPrice  = 0;
                            arTran.TranAmt   = 0;
                        }
                        else
                        {
                            arTran.TranDesc = PXMessages.LocalizeNoPrefix(CT.Messages.PrefixOverused) + " " + tran.Description;
                            arTran.Qty      = arTran.Qty - available;
                            availableQty[tran.InventoryID.Value] = 0;                            //all available qty was used.
                        }
                    }
                }

                tran.Billed     = true;
                tran.BilledDate = billingDate;

                Transactions.Update(tran);
            }

            return(list);
        }
Пример #7
0
        public virtual CommitTaxRequest BuildCommitTaxRequestWithFrt(ARInvoice invoice)
        {
            if (invoice == null)
            {
                throw new PXArgumentException(nameof(invoice), ErrorMessages.ArgumentNullException);
            }

            Customer cust = (Customer)Base.customer.View.SelectSingleBound(new object[] { invoice });

            CR.Location loc = (CR.Location)Base.location.View.SelectSingleBound(new object[] { invoice });

            CommitTaxRequest request = new CommitTaxRequest();

            request.CompanyCode       = Base1.CompanyCodeFromBranch(invoice.TaxZoneID, invoice.BranchID);
            request.CurrencyCode      = invoice.CuryID;
            request.CustomerCode      = cust.AcctCD;
            request.TaxRegistrationID = loc?.TaxRegistrationID;
            IAddressBase fromAddress = Base1.GetFromAddress(invoice);
            IAddressBase toAddress   = Base1.GetToAddress(invoice);

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

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

            request.OriginAddress      = AddressConverter.ConvertTaxAddress(fromAddress);
            request.DestinationAddress = AddressConverter.ConvertTaxAddress(toAddress);
            request.DocCode            = $"AR.{invoice.DocType}.{invoice.RefNbr}";
            request.DocDate            = invoice.DocDate.GetValueOrDefault();
            request.LocationCode       = GetExternalTaxProviderLocationCode <ARTran, ARTran.FK.Invoice.SameAsCurrent, ARTran.siteID>(invoice);
            request.CustomerUsageType  = invoice.AvalaraCustomerUsageType;

            if (!string.IsNullOrEmpty(invoice.ExternalTaxExemptionNumber))
            {
                request.ExemptionNo = invoice.ExternalTaxExemptionNumber;
            }

            request.DocType = Base1.GetTaxDocumentType(invoice);
            Sign sign = Base1.GetDocumentSign(invoice);

            PXSelectBase <ARTran> select = new PXSelectJoin <ARTran, LeftJoin <InventoryItem, On <InventoryItem.inventoryID, Equal <ARTran.inventoryID> >,
                                                                               LeftJoin <Account, On <Account.accountID, Equal <ARTran.accountID> > > >,
                                                             Where <ARTran.tranType, Equal <Current <ARInvoice.docType> >,
                                                                    And <ARTran.refNbr, Equal <Current <ARInvoice.refNbr> >,
                                                                         And <Where <ARTran.lineType, NotEqual <SOLineType.discount>, Or <ARTran.lineType, IsNull> > > > >,
                                                             OrderBy <Asc <ARTran.tranType, Asc <ARTran.refNbr, Asc <ARTran.lineNbr> > > > >(Base);

            request.Discount = Base.Document.Current.CuryDiscTot.GetValueOrDefault();
            DateTime?taxDate = invoice.OrigDocDate;

            bool applyRetainage = Base.ARSetup.Current?.RetainTaxes != true && invoice.IsOriginalRetainageDocument();

            /// <summary>
            /// Add the following condition and logic per Jira [IP-23]
            /// </summary>>
            string taxCategory = (Base as SOInvoiceEntry).FreightDetails.Current?.TaxCategoryID;

            if (invoice.CuryFreightTot > 0 && GL.Branch.PK.Find(Base, Base.Accessinfo.BranchID).CountryID == Country_US && invoice.TaxZoneID == TaxCloud && !string.IsNullOrEmpty(taxCategory))
            {
                var line = new TaxCartItem();
                line.Index              = short.MinValue;
                line.Quantity           = 1;
                line.UOM                = "EA";
                line.Amount             = sign * invoice.CuryFreightTot.GetValueOrDefault();
                line.Description        = PXMessages.LocalizeNoPrefix(SO.Messages.FreightDesc);
                line.DestinationAddress = request.DestinationAddress;
                line.OriginAddress      = request.OriginAddress;
                line.ItemCode           = "N/A";
                line.Discounted         = false;
                line.TaxCode            = taxCategory;

                request.CartItems.Add(line);
            }

            foreach (PXResult <ARTran, InventoryItem, Account> res in select.View.SelectMultiBound(new object[] { invoice }))
            {
                ARTran        tran         = (ARTran)res;
                InventoryItem item         = (InventoryItem)res;
                Account       salesAccount = (Account)res;

                var line = new TaxCartItem();
                line.Index              = tran.LineNbr ?? 0;
                line.Amount             = sign * (tran.CuryTranAmt.GetValueOrDefault() + (applyRetainage ? tran.CuryRetainageAmt.GetValueOrDefault() : 0m));
                line.Description        = tran.TranDesc;
                line.DestinationAddress = AddressConverter.ConvertTaxAddress(Base1.GetToAddress(invoice, tran));
                line.OriginAddress      = AddressConverter.ConvertTaxAddress(Base1.GetFromAddress(invoice, tran));
                line.ItemCode           = item.InventoryCD;
                line.Quantity           = Math.Abs(tran.Qty.GetValueOrDefault());
                line.UOM        = tran.UOM;
                line.Discounted = tran.LineType != SOLineType.Freight && request.Discount > 0;
                line.RevAcct    = salesAccount.AccountCD;

                line.TaxCode           = tran.TaxCategoryID;
                line.CustomerUsageType = tran.AvalaraCustomerUsageType;

                if (tran.OrigInvoiceDate != null)
                {
                    taxDate = tran.OrigInvoiceDate;
                }

                request.CartItems.Add(line);
            }

            if (applyRetainage)
            {
                var line = new TaxCartItem();
                line.Index              = invoice.LineCntr.GetValueOrDefault() + 1;
                line.Amount             = Sign.Minus * sign * invoice.CuryLineRetainageTotal.GetValueOrDefault();
                line.Description        = PXMessages.LocalizeFormatNoPrefix(AP.Messages.RetainageForTransactionDescription, GetLabel.For <ARDocType>(invoice.DocType), invoice.RefNbr);
                line.DestinationAddress = request.DestinationAddress;
                line.OriginAddress      = request.OriginAddress;
                line.ItemCode           = "Retainage";
                line.Discounted         = false;
                line.NonTaxable         = true;

                request.CartItems.Add(line);
            }

            if ((invoice.DocType == ARDocType.CreditMemo || invoice.DocType == ARDocType.CashReturn) && invoice.OrigDocDate != null)
            {
                request.TaxOverride.Reason          = Messages.ReturnReason;
                request.TaxOverride.TaxDate         = taxDate.Value;
                request.TaxOverride.TaxOverrideType = TaxOverrideType.TaxDate;
                sign = Sign.Minus;
            }

            return(request);
        }
        public static void ConvertToAccount(Contact contact, AccountsFilter param)
        {
            BusinessAccountMaint accountMaint = CreateInstance <BusinessAccountMaint>();
            object cd = param.BAccountID;

            accountMaint.BAccount.Cache.RaiseFieldUpdating <BAccount.acctCD>(null, ref cd);
            BAccount account = new BAccount
            {
                AcctCD           = (string)cd,
                AcctName         = param.AccountName,
                Type             = BAccountType.ProspectType,
                ClassID          = param.AccountClass,
                ParentBAccountID = contact.ParentBAccountID
            };

            #region Set Contact and Address fields
            CRContactClass cls = PXSelect <CRContactClass, Where <CRContactClass.classID, Equal <Current <Contact.classID> > > > .SelectSingleBound(accountMaint, new object[] { contact });

            if (cls != null && cls.OwnerToBAccount == true)
            {
                account.WorkgroupID = contact.WorkgroupID;
                account.OwnerID     = contact.OwnerID;
            }

            try
            {
                object newValue = account.OwnerID;
                accountMaint.BAccount.Cache.RaiseFieldVerifying <BAccount.ownerID>(account, ref newValue);
            }
            catch (PXSetPropertyException)
            {
                account.OwnerID = null;
            }

            account = accountMaint.BAccount.Insert(account);

            accountMaint.Answers.CopyAllAttributes(account, contact);

            Contact defContact = PXCache <Contact> .CreateCopy(PXSelect <Contact, Where <Contact.contactID, Equal <Current <BAccount.defContactID> > > > .SelectSingleBound(accountMaint, new object[] { account }));

            var defContactNoteID = defContact.NoteID;
            PXCache <Contact> .RestoreCopy(defContact, contact);

            defContact.ContactType     = ContactTypesAttribute.BAccountProperty;
            defContact.FullName        = account.AcctName;
            defContact.ContactID       = account.DefContactID;
            defContact.BAccountID      = account.BAccountID;
            defContact.DuplicateStatus = DuplicateStatusAttribute.NotValidated;
            defContact.DuplicateFound  = false;
            defContact.WorkgroupID     = null;
            defContact.OwnerID         = null;
            defContact.NoteID          = defContactNoteID;
            defContact = accountMaint.DefContact.Update(defContact);

            Address contactAddress = PXSelect <Address, Where <Address.addressID, Equal <Required <Contact.defAddressID> > > > .Select(accountMaint, contact.DefAddressID);

            if (contactAddress == null)
            {
                throw new PXException(Messages.DefAddressNotExists, contact.DisplayName);
            }
            contactAddress.BAccountID = account.BAccountID;
            accountMaint.AddressCurrent.Cache.Clear();

            defContact.DefAddressID = contactAddress.AddressID;
            defContact = accountMaint.DefContact.Update(defContact);

            contactAddress = accountMaint.AddressCurrent.Update(contactAddress);

            account.DefAddressID = contactAddress.AddressID;
            accountMaint.BAccount.Update(account);

            contact.BAccountID      = account.BAccountID;
            contact.DuplicateStatus = DuplicateStatusAttribute.NotValidated;
            contact.DuplicateFound  = false;
            if (contact.QualificationDate == null)
            {
                contact.QualificationDate = PXTimeZoneInfo.Now;
            }
            accountMaint.Contacts.Cache.SetStatus(contact, PXEntryStatus.Updated);
            CR.Location location = accountMaint.DefLocation.Select();
            location.DefAddressID = contactAddress.AddressID;
            accountMaint.DefLocation.Update(location);

            account.NoteID = PXNoteAttribute.GetNoteID <CRActivity.noteID>(accountMaint.CurrentBAccount.Cache, account);
            foreach (CRPMTimeActivity a in PXSelect <CRPMTimeActivity, Where <CRPMTimeActivity.refNoteID, Equal <Required <Contact.noteID> > > > .Select(accountMaint, contact.NoteID))
            {
                a.BAccountID = account.BAccountID;
                accountMaint.Activities.Cache.Update(a);
            }
            #endregion

            // Copy Note text and Files references
            CRSetup setup = PXSetupOptional <CRSetup> .Select(accountMaint);

            PXNoteAttribute.CopyNoteAndFiles(accountMaint.Contacts.Cache, contact, accountMaint.CurrentBAccount.Cache, account, setup);

            throw new PXRedirectRequiredException(accountMaint, "Business Account");
        }
Пример #9
0
        protected virtual void Location_IsAPPaymentInfoSameAsMain_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            CR.Location record = (CR.Location)e.Row;

            if (record.IsAPPaymentInfoSameAsMain == false)
            {
                LocationAPPaymentInfo mainloc = APPaymentInfoLocation.Select();
                record.VCashAccountID           = mainloc.VCashAccountID;
                record.VPaymentMethodID         = mainloc.VPaymentMethodID;
                record.VPaymentLeadTime         = mainloc.VPaymentLeadTime;
                record.VPaymentByType           = mainloc.VPaymentByType;
                record.VSeparateCheck           = mainloc.VSeparateCheck;
                record.IsRemitAddressSameAsMain = mainloc.IsRemitAddressSameAsMain;
                record.VRemitAddressID          = mainloc.VRemitAddressID;
                record.IsRemitContactSameAsMain = mainloc.IsRemitContactSameAsMain;
                record.VRemitContactID          = mainloc.VRemitContactID;
                record.VPaymentInfoLocationID   = record.LocationID;

                LocationAPPaymentInfo copyloc = new LocationAPPaymentInfo();
                copyloc.BAccountID               = record.BAccountID;
                copyloc.LocationID               = record.LocationID;
                copyloc.VCashAccountID           = record.VCashAccountID;
                copyloc.VPaymentMethodID         = record.VPaymentMethodID;
                copyloc.VPaymentLeadTime         = record.VPaymentLeadTime;
                copyloc.VPaymentByType           = record.VPaymentByType;
                copyloc.VSeparateCheck           = record.VSeparateCheck;
                copyloc.IsRemitAddressSameAsMain = record.IsRemitAddressSameAsMain;
                copyloc.VDefAddressID            = record.VDefAddressID;
                copyloc.VRemitAddressID          = record.VRemitAddressID;
                copyloc.IsRemitContactSameAsMain = record.IsRemitContactSameAsMain;
                copyloc.VRemitContactID          = record.VRemitContactID;
                copyloc.VDefContactID            = record.VDefContactID;

                if (copyloc.VDefAddressID != copyloc.VRemitAddressID)
                {
                    Address copyaddr = FindAddress(copyloc.VRemitAddressID);
                    copyaddr = PXCache <Address> .CreateCopy(copyaddr);

                    copyaddr.AddressID = null;

                    copyaddr = RemitAddress.Insert(copyaddr);
                    copyloc.VRemitAddressID = copyaddr.AddressID;
                    record.VRemitAddressID  = copyaddr.AddressID;
                }

                if (copyloc.VDefContactID != copyloc.VRemitContactID)
                {
                    Contact copycont = FindContact(copyloc.VRemitContactID);
                    copycont = PXCache <Contact> .CreateCopy(copycont);

                    copycont.ContactID = null;
                    copycont.NoteID    = null;

                    copycont = RemitContact.Insert(copycont);
                    copyloc.VRemitContactID = copycont.ContactID;
                    record.VRemitContactID  = copycont.ContactID;
                }

                foreach (VendorPaymentMethodDetail maindet in this.PaymentDetails.Select(mainloc.BAccountID, mainloc.LocationID, mainloc.VPaymentMethodID))
                {
                    VendorPaymentMethodDetail copydet = PXCache <VendorPaymentMethodDetail> .CreateCopy(maindet);

                    copydet.LocationID = copyloc.LocationID;

                    this.PaymentDetails.Insert(copydet);
                }

                BusinessAccount.Cache.Current = (BAccount)PXParentAttribute.SelectParent(sender, e.Row, typeof(BAccount));
                APPaymentInfoLocation.Insert(copyloc);
            }
            if (record.IsAPPaymentInfoSameAsMain == true)
            {
                foreach (VendorPaymentMethodDetail copydet in this.PaymentDetails.Select(record.BAccountID, record.LocationID, record.VPaymentMethodID))
                {
                    this.PaymentDetails.Delete(copydet);
                }

                BAccount baccount = (BAccount)PXParentAttribute.SelectParent(sender, e.Row, typeof(BAccount));
                if (baccount != null)
                {
                    record.VPaymentInfoLocationID = baccount.DefLocationID;

                    Location mainloc = PXSelect <CR.Location, Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .Select(sender.Graph, baccount.BAccountID, baccount.DefLocationID);

                    if (mainloc != null)
                    {
                        if (record.DefAddressID != record.VRemitAddressID && mainloc.VRemitAddressID != record.VRemitAddressID)
                        {
                            Address copyaddr = FindAddress(record.VRemitAddressID);
                            RemitAddress.Delete(copyaddr);
                        }

                        if (record.DefContactID != record.VRemitContactID && mainloc.VRemitContactID != record.VRemitContactID)
                        {
                            Contact copycont = FindContact(record.VRemitContactID);
                            RemitContact.Delete(copycont);
                        }
                    }
                }

                record.VCashAccountID   = null;
                record.VPaymentMethodID = null;
                record.VPaymentLeadTime = 0;
                record.VSeparateCheck   = false;
                record.VRemitAddressID  = null;
                record.VRemitContactID  = null;
            }
        }
        protected override BAccount CreateMaster(BusinessAccountMaint graph, AccountConversionOptions config)
        {
            var param      = AccountInfo.Current;
            var document   = Documents.Current;
            var docContact = Contacts.Current ?? Contacts.SelectSingle();
            var docAddress = Addresses.Current ?? Addresses.SelectSingle();

            object cd = param.BAccountID;

            graph.BAccount.Cache.RaiseFieldUpdating <BAccount.acctCD>(null, ref cd);

            BAccount account = graph.BAccount.Insert(new BAccount
            {
                AcctCD           = (string)cd,
                AcctName         = param.AccountName,
                Type             = BAccountType.ProspectType,
                ParentBAccountID = document.ParentBAccountID,
                CampaignSourceID = document.CampaignID,
            });

            account.ClassID = param.AccountClass;             // In case of (param.AccountClass == null) constructor fills ClassID with default value, so we have to set this directly.

            CRCustomerClass ocls = PXSelect <
                CRCustomerClass,
                Where <
                    CRCustomerClass.cRCustomerClassID, Equal <Required <CRCustomerClass.cRCustomerClassID> > > >
                                   .SelectSingleBound(graph, null, account.ClassID);

            if (ocls?.DefaultOwner == CRDefaultOwnerAttribute.Source)
            {
                account.WorkgroupID = document.WorkgroupID;
                account.OwnerID     = document.OwnerID;
            }

            account = graph.BAccount.Update(account);

            if (param.LinkContactToAccount == true)
            {
                // in case of opportunity
                Contact contact = PXSelect <Contact, Where <Contact.contactID, Equal <Required <CROpportunity.contactID> > > > .Select(graph, document.RefContactID);

                if (contact != null)
                {
                    graph.Answers.CopyAttributes(account, contact);
                    contact.BAccountID = account.BAccountID;
                    graph.Contacts.Update(contact);
                }
            }


            var defContact = graph.DefContact.SelectSingle()
                             ?? throw new InvalidOperationException("Cannot get Contact for Business Account.");    // just to ensure

            MapContact(docContact, account, ref defContact);
            MapConsentable(docContact, defContact);
            defContact = graph.DefContact.Update(defContact);

            var defAddress = graph.AddressCurrent.SelectSingle()
                             ?? throw new InvalidOperationException("Cannot get Address for Business Account.");    // just to ensure

            MapAddress(docAddress, account, ref defAddress);
            defAddress = graph.AddressCurrent.Update(defAddress);

            CR.Location location = graph.DefLocation.Select();
            location.DefAddressID = defAddress.AddressID;
            location.CTaxZoneID   = document.TaxZoneID;           // Saving tax zone before ReverseDocumentUpdate() removes it
            graph.DefLocation.Update(location);

            ReverseDocumentUpdate(graph, account);

            FillRelations(graph.Relations, account);

            FillAttributes(graph.Answers, account);

            TransferActivities(graph, account);

            // Copy Note text and Files references
            CRSetup setup = PXSetupOptional <CRSetup> .Select(graph);

            PXNoteAttribute.CopyNoteAndFiles(graph.Caches <TMain>(), GetMain(document), graph.CurrentBAccount.Cache, account, setup);

            return(account);
        }
        protected GetTaxRequest BuildGetTaxRequest(PMQuote quote)
        {
            if (quote == null)
            {
                throw new PXArgumentException(ErrorMessages.ArgumentNullException);
            }

            BAccount cust = (BAccount)PXSelect <BAccount,
                                                Where <BAccount.bAccountID, Equal <Required <BAccount.bAccountID> > > > .
                            Select(Base, quote.BAccountID);

            CR.Location loc = (CR.Location) PXSelect <CR.Location,
                                                      Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .
                              Select(Base, quote.BAccountID, quote.LocationID);

            IAddressBase addressFrom = GetFromAddress(quote);
            IAddressBase addressTo   = GetToAddress(quote);

            if (addressFrom == null)
            {
                throw new PXException(CR.Messages.FailedGetFromAddressCR);
            }

            if (addressTo == null)
            {
                throw new PXException(CR.Messages.FailedGetToAddressCR);
            }

            GetTaxRequest request = new GetTaxRequest();

            request.CompanyCode        = CompanyCodeFromBranch(quote.TaxZoneID, Base.Accessinfo.BranchID);
            request.CurrencyCode       = quote.CuryID;
            request.CustomerCode       = cust.AcctCD;
            request.OriginAddress      = AddressConverter.ConvertTaxAddress(addressFrom);
            request.DestinationAddress = AddressConverter.ConvertTaxAddress(addressTo);
            request.DocCode            = string.Format("CR.{0}", quote.OpportunityID);
            request.DocDate            = quote.DocumentDate.GetValueOrDefault();
            request.Discount           = quote.CuryLineDocDiscountTotal.GetValueOrDefault();

            int mult = 1;

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

            request.DocType = TaxDocumentType.SalesOrder;

            var select = PXSelectJoin <CROpportunityProducts,
                                       LeftJoin <InventoryItem, On <InventoryItem.inventoryID, Equal <CROpportunityProducts.inventoryID> >,
                                                 LeftJoin <Account, On <Account.accountID, Equal <InventoryItem.salesAcctID> > > >,
                                       Where <CROpportunityProducts.quoteID, Equal <Required <PMQuote.quoteID> > >,
                                       OrderBy <Asc <CROpportunityProducts.lineNbr> > > .Select(Base, quote.QuoteID);

            foreach (PXResult <CROpportunityProducts, InventoryItem, Account> res in select)
            {
                CROpportunityProducts tran = (CROpportunityProducts)res;
                InventoryItem         item = (InventoryItem)res;
                Account salesAccount       = (Account)res;

                var line = new TaxCartItem();
                line.Index              = tran.LineNbr ?? 0;
                line.Amount             = mult * tran.CuryAmount.GetValueOrDefault();
                line.Description        = tran.Descr;
                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);
        }