Ejemplo n.º 1
0
        public static void ProcessSurvey(List <SurveyCollector> recs, SurveyFilter filter)
        {
            var collGraph = CreateInstance <SurveyCollectorMaint>();
            var action    = filter.Action;

            if (string.IsNullOrEmpty(action))
            {
                throw new PXException(Messages.SurveyActionNotRecognised);
            }
            SurveyProcess surveyProcessGraph = PXGraph.CreateInstance <SurveyProcess>();

            surveyProcessGraph.Filter.Insert(filter);
            var collCache     = collGraph.Collector.Cache;
            var errorOccurred = false;
            var docCount      = 0;

            foreach (var rec in recs)
            {
                var row = (SurveyCollector)collCache.CreateCopy(rec);
                collGraph.Collector.Current = row;
                try {
                    PXProcessing <SurveyCollector> .SetCurrentItem(rec);

                    switch (action)
                    {
                    case SurveyAction.SendNew:
                        collGraph.DoSendNewNotification(row);
                        break;

                    case SurveyAction.RemindOnly:
                        collGraph.DoSendReminder(row, filter.DurationTimeSpan);
                        break;

                    case SurveyAction.ExpireOnly:
                        row.Status  = CollectorStatus.Expired;
                        row.Message = null;
                        collGraph.Collector.Update(row);
                        break;
                    }
                    if (++docCount % 10 == 0)
                    {
                        surveyProcessGraph.Actions.PressSave();
                    }
                    PXProcessing <SurveyCollector> .SetInfo(recs.IndexOf(rec), string.Format("The survey collector {0} has been updated", rec.CollectorID));

                    PXProcessing <SurveyCollector> .SetProcessed();
                } catch (Exception ex) {
                    row.Status  = CollectorStatus.Error;
                    row.Message = ex.Message;
                    surveyProcessGraph.Documents.Update(row);
                    surveyProcessGraph.Actions.PressSave();
                    PXTrace.WriteError(ex);
                    string errorMessage = ex.Message + ": ";
                    if (ex is PXOuterException pex && pex.InnerMessages != null)
                    {
                        foreach (string message in pex.InnerMessages)
                        {
                            errorMessage += message + ", ";
                        }
                    }
Ejemplo n.º 2
0
 public DeleteDocsProcess()
 {
     Docs.SetProcessCaption(Messages.DeleteProc);
     Docs.SetProcessAllCaption(Messages.DeleteAllProc);
     Docs.SetProcessDelegate(delegate(List <FARegister> list)
     {
         bool failed = false;
         TransactionEntry entryGraph = CreateInstance <TransactionEntry>();
         foreach (FARegister register in list)
         {
             PXProcessing.SetCurrentItem(register);
             try
             {
                 entryGraph.Clear();
                 entryGraph.Document.Current = entryGraph.Document.Search <FARegister.refNbr>(register.RefNbr);
                 entryGraph.Delete.Press();
                 PXProcessing.SetProcessed();
             }
             catch (Exception e)
             {
                 failed = true;
                 PXProcessing.SetError(e);
             }
         }
         if (failed)
         {
             throw new PXOperationCompletedWithErrorException(ErrorMessages.SeveralItemsFailed);
         }
     });
 }
Ejemplo n.º 3
0
        protected void _(Events.RowSelected <AMMultiLevelBomFilter> e)
        {
            AMMultiLevelBomFilter row = e.Row;

            if (row != null)
            {
                bool enabled = PXSelect <LifeSyncPreference> .Select(this).TopFirst.EnableProdCostAnlys ?? false;

                PXUIFieldAttribute.SetEnabled <AMMultiLevelBomFilterExt.usrEnblItemRoundUp>(e.Cache, row, enabled);
            }

            Results.SetProcessDelegate(delegate(List <LUMStdBomCost> lists)
            {
                try
                {
                    GenerateBOMCost(lists, row);

                    PXProcessing.SetProcessed();
                }
                catch (Exception ex)
                {
                    PXProcessing.SetError(ex);
                    throw;
                }
            });
        }
        private static void InitializeAdjustments(APAdjust adjustment, PayBillsFilter filter)
        {
            PXProcessing <APAdjust> .SetCurrentItem(adjustment);

            adjustment.AdjgDocDate     = filter.PayDate;
            adjustment.AdjgFinPeriodID = filter.PayFinPeriodID;
            PXProcessing <APAdjust> .SetProcessed();
        }
        protected override void ProcessLienWaiver(NotificationSourceModel notificationSourceModel,
                                                  ComplianceDocument complianceDocument)
        {
            base.ProcessLienWaiver(notificationSourceModel, complianceDocument);
            ConfigurePrintActionParameters(notificationSourceModel.NotificationSource.ReportID,
                                           notificationSourceModel.NotificationSource.NBranchID);
            UpdateLienWaiverProcessedStatus(complianceDocument);

            PXProcessing.SetProcessed();
        }
Ejemplo n.º 6
0
        protected override void ProcessLienWaiver(NotificationSourceModel notificationSourceModel,
                                                  ComplianceDocument complianceDocument)
        {
            base.ProcessLienWaiver(notificationSourceModel, complianceDocument);
            var notificationRecipients = GetNotificationRecipients(
                notificationSourceModel.NotificationSource, notificationSourceModel.VendorId);

            notificationRecipients.ForEach(nr =>
                                           SendEmail(nr, notificationSourceModel, complianceDocument));

            PXProcessing.SetProcessed();
        }
        private static bool ApproveSubcontract(SubcontractEntry graph,
                                               KeyValuePair <EPApprovalProcess.EPOwned, POOrder> subcontractApprovalPair)
        {
            try
            {
                PXProcessing <EPApproval> .SetCurrentItem(subcontractApprovalPair.Key);

                ApproveSingleSubcontract(graph, subcontractApprovalPair.Value);
                PXProcessing <EPApproval> .SetProcessed();

                return(false);
            }
            catch (Exception exception)
            {
                PXProcessing <EPApproval> .SetError(exception);

                return(true);
            }
        }
Ejemplo n.º 8
0
        public static void CreateShipment(System.Collections.Generic.List <SOShipmentPlan> list)
        {
            int num1 = 0;

            try
            {
                SOShipmentEntry instance = PXGraph.CreateInstance <SOShipmentEntry>();
                DocumentList <PX.Objects.SO.SOShipment> list1 = new DocumentList <PX.Objects.SO.SOShipment>((PXGraph)instance);
                Dictionary <long, PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder> > dictionary = new Dictionary <long, PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder> >();
                SOShipmentPlan        soShipmentPlan1 = new SOShipmentPlan();
                PX.Objects.SO.SOOrder soOrder         = new PX.Objects.SO.SOOrder();
                for (int index = 0; index < list.Count; ++index)
                {
                    SOShipmentPlan        i0 = list[index];
                    PX.Objects.SO.SOOrder i1 = SelectFrom <PX.Objects.SO.SOOrder> .Where <PX.Objects.SO.SOOrder.orderType.IsEqual <P.AsString>
                                                                                          .And <PX.Objects.SO.SOOrder.orderNbr.IsEqual <P.AsString> > > .View.Select((PXGraph)instance, (object)i0.OrderType, (object)i0.OrderNbr);

                    int?nullable1;
                    int?customerLocationId;
                    int?nullable2;
                    int num2;
                    if (num1 != 0)
                    {
                        int num3 = num1;
                        nullable1          = i1.CustomerID;
                        customerLocationId = i1.CustomerLocationID;
                        nullable2          = nullable1.HasValue & customerLocationId.HasValue ? new int?(nullable1.GetValueOrDefault() + customerLocationId.GetValueOrDefault()) : new int?();
                        int valueOrDefault = nullable2.GetValueOrDefault();
                        num2 = num3 == valueOrDefault & nullable2.HasValue ? 1 : 0;
                    }
                    else
                    {
                        num2 = 1;
                    }
                    if (num2 == 0)
                    {
                        throw new PXException("Please Only Select The Same Customer ID & Location For One Shipment");
                    }
                    nullable2          = i1.CustomerID;
                    customerLocationId = i1.CustomerLocationID;
                    int?nullable3;
                    if (!(nullable2.HasValue & customerLocationId.HasValue))
                    {
                        nullable1 = new int?();
                        nullable3 = nullable1;
                    }
                    else
                    {
                        nullable3 = new int?(nullable2.GetValueOrDefault() + customerLocationId.GetValueOrDefault());
                    }
                    nullable1 = nullable3;
                    num1      = nullable1.Value;
                    dictionary.Add(i0.PlanID.Value, new PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder>(i0, i1));
                }
                PX.Objects.SO.SOOrder order = new PX.Objects.SO.SOOrder();
                foreach (PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder> pxResult in dictionary.Values)
                {
                    SOShipmentPlan soShipmentPlan2 = (SOShipmentPlan)pxResult;
                    if (order.OrderNbr != pxResult.GetItem <PX.Objects.SO.SOOrder>().OrderNbr)
                    {
                        order = (PX.Objects.SO.SOOrder)pxResult;
                        instance.GetExtension <SOShipmentEntry_Extension>().CreateShipment2(order, soShipmentPlan2.SiteID, soShipmentPlan2.PlanDate, new bool?(false), "I", list1, list);
                    }
                }
                throw new PXPopupRedirectException((PXGraph)instance, "Shipment <*> is created", true);
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("Shipment <*> is created"))
                {
                    PXProcessing.SetProcessed();
                }
                else
                {
                    PXProcessing.SetError(ex);
                }
                throw;
            }
        }
Ejemplo n.º 9
0
        public void Revalue(RevalueFilter filter, List <RevaluedGLHistory> list)
        {
            JournalEntry je        = PXGraph.CreateInstance <JournalEntry>();
            PostGraph    pg        = PXGraph.CreateInstance <PostGraph>();
            PXCache      basecache = je.Caches[typeof(AcctHist)];

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

            string extRefNbrNumbering = je.CMSetup.Current.ExtRefNbrNumberingID;

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

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

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

            bool hasErrors = false;

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

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

                        continue;
                    }

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

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

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

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

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

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

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

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

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

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

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

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

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

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

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

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

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

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

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

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

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

                    PXProcessing <RevaluedGLHistory> .SetProcessed();
                }

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

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

                ts.Complete();
            }

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

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

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

                throw new PXException(ErrorMessages.SeveralItemsFailed);
            }

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

            decimal val = 0m;

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

            if (val == 0)
            {
                throw new PXOperationCompletedWithWarningException(Messages.NoRevaluationEntryWasMade);
            }
        }
        public virtual IEnumerable Action(
            PXAdapter adapter,
            [PXInt]
            [PXIntList(new int[] { 1, 2, 3, 4, 5 }, new string[] { "Create Shipment", "Apply Assignment Rules", "Create Invoice", "Post Invoice to IN", "Create Purchase Order" })]
            int?actionID,
            [PXDate]
            DateTime?shipDate,
            [PXSelector(typeof(INSite.siteCD))]
            string siteCD,
            [SOOperation.List]
            string operation,
            [PXString()]
            string ActionName,
            Func <PXAdapter, int?, DateTime?, string, string, string, IEnumerable> baseMtd)
        {
            switch (actionID)
            {
            case 1:
            {
                if (!string.IsNullOrEmpty(ActionName))
                {
                    PXAction action = Base.Actions[ActionName];

                    if (action != null)
                    {
                        Base.Save.Press();
                        List <object> result = new List <object>();
                        foreach (object data in action.Press(adapter))
                        {
                            result.Add(data);
                        }
                        return(result);
                    }
                }

                List <SOOrder> list = new List <SOOrder>();
                foreach (SOOrder order in adapter.Get <SOOrder>())
                {
                    list.Add(order);
                }

                if (shipDate != null)
                {
                    Base.soparamfilter.Current.ShipDate = shipDate;
                }

                if (Base.soparamfilter.Current.ShipDate == null)
                {
                    Base.soparamfilter.Current.ShipDate = Base.Accessinfo.BusinessDate;
                }

                if (siteCD != null)
                {
                    Base.soparamfilter.Cache.SetValueExt <SOParamFilter.siteID>(Base.soparamfilter.Current, siteCD);
                }

                if (!adapter.MassProcess)
                {
                    if (Base.soparamfilter.Current.SiteID == null)
                    {
                        Base.soparamfilter.Current.SiteID = GetPreferedSiteID();
                    }
                    if (adapter.ExternalCall)
                    {
                        Base.soparamfilter.AskExt(true);
                    }
                }
                if (Base.soparamfilter.Current.SiteID != null || adapter.MassProcess)
                {
                    try
                    {
                        Base.RecalculateExternalTaxesSync = true;
                        Base.Save.Press();
                    }
                    finally
                    {
                        Base.RecalculateExternalTaxesSync = false;
                    }
                    PXAutomation.RemovePersisted(Base, typeof(SOOrder), new List <object>(list));

                    SOParamFilter filter = Base.soparamfilter.Current;
                    PXLongOperation.StartOperation(Base, delegate()
                        {
                            bool anyfailed                    = false;
                            SOShipmentEntry docgraph          = PXGraph.CreateInstance <SOShipmentEntry>();
                            SOOrderEntry ordgraph             = PXGraph.CreateInstance <SOOrderEntry>();
                            DocumentList <SOShipment> created = new DocumentList <SOShipment>(docgraph);

                            //address AC-92776
                            for (int i = 0; i < list.Count; i++)
                            {
                                SOOrder order = list[i];
                                if (adapter.MassProcess)
                                {
                                    PXProcessing <SOOrder> .SetCurrentItem(order);
                                }

                                SOOrder ordercopy = (SOOrder)Base.Caches[typeof(SOOrder)].CreateCopy(order);
                                try
                                {
                                    if (operation == SOOperation.Issue)
                                    {
                                        ReviewWarehouseAvailability(ordgraph, order);
                                    }
                                }
                                catch (SOShipmentException ex)
                                {
                                    Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                    if (!adapter.MassProcess)
                                    {
                                        throw;
                                    }

                                    order.LastShipDate = filter.ShipDate;
                                    order.Status       = SOOrderStatus.Shipping; //Automation will set the order to back order since no shipments were created

                                    docgraph.Clear();

                                    var ordergraph = PXGraph.CreateInstance <SOOrderEntry>();
                                    ordergraph.Clear();

                                    ordergraph.Document.Cache.MarkUpdated(order);
                                    PXAutomation.CompleteSimple(ordergraph.Document.View);
                                    try
                                    {
                                        ordergraph.Save.Press();
                                        PXAutomation.RemovePersisted(ordergraph, order);

                                        PXTrace.WriteInformation(ex);
                                        PXProcessing <SOOrder> .SetWarning(ex);
                                    }
                                    catch (Exception inner)
                                    {
                                        Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                        PXProcessing <SOOrder> .SetError(inner);
                                        anyfailed = true;
                                    }
                                    continue;     //Stop there for this order
                                }
                                catch (Exception ex)
                                {
                                    if (!adapter.MassProcess)
                                    {
                                        throw;
                                    }
                                    PXProcessing <SOOrder> .SetError(ex);
                                    anyfailed = true;
                                    continue;
                                }

                                List <int?> sites = new List <int?>();

                                if (filter.SiteID != null)
                                {
                                    sites.Add(filter.SiteID);
                                }
                                else
                                {
                                    foreach (SOShipmentPlan plan in PXSelectGroupBy <SOShipmentPlan, Where <SOShipmentPlan.orderType, Equal <Current <SOOrder.orderType> >, And <SOShipmentPlan.orderNbr, Equal <Current <SOOrder.orderNbr> > > >, Aggregate <GroupBy <SOShipmentPlan.siteID> >, OrderBy <Asc <SOShipmentPlan.siteID> > > .SelectMultiBound(docgraph, new object[] { order }))
                                    {
                                        sites.Add(plan.SiteID);
                                    }
                                }

                                foreach (int?SiteID in sites)
                                {
                                    ordercopy = (SOOrder)Base.Caches[typeof(SOOrder)].CreateCopy(order);
                                    try
                                    {
                                        using (var ts = new PXTransactionScope())
                                        {
                                            PXTimeStampScope.SetRecordComesFirst(typeof(SOOrder), true);
                                            docgraph.CreateShipment(order, SiteID, filter.ShipDate, adapter.MassProcess, operation, created, adapter.QuickProcessFlow);
                                            ts.Complete();
                                        }

                                        if (adapter.MassProcess)
                                        {
                                            PXProcessing <SOOrder> .SetProcessed();
                                        }
                                    }
                                    catch (SOShipmentException ex)
                                    {
                                        Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                        if (!adapter.MassProcess)
                                        {
                                            throw;
                                        }
                                        order.LastSiteID   = SiteID;
                                        order.LastShipDate = filter.ShipDate;
                                        order.Status       = SOOrderStatus.Shipping;

                                        docgraph.Clear();

                                        var ordergraph = PXGraph.CreateInstance <SOOrderEntry>();
                                        ordergraph.Clear();

                                        ordergraph.Document.Cache.MarkUpdated(order);
                                        PXAutomation.CompleteSimple(ordergraph.Document.View);
                                        try
                                        {
                                            ordergraph.Save.Press();
                                            PXAutomation.RemovePersisted(ordergraph, order);

                                            PXTrace.WriteInformation(ex);
                                            PXProcessing <SOOrder> .SetWarning(ex);
                                        }
                                        catch (Exception inner)
                                        {
                                            Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                            PXProcessing <SOOrder> .SetError(inner);
                                            anyfailed = true;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                        docgraph.Clear();

                                        if (!adapter.MassProcess)
                                        {
                                            throw;
                                        }
                                        PXProcessing <SOOrder> .SetError(ex);
                                        anyfailed = true;
                                    }
                                }
                            }

                            if (adapter.AllowRedirect && !adapter.MassProcess && created.Count > 0)
                            {
                                using (new PXTimeStampScope(null))
                                {
                                    docgraph.Clear();
                                    docgraph.Document.Current = docgraph.Document.Search <SOShipment.shipmentNbr>(created[0].ShipmentNbr);
                                    throw new PXRedirectRequiredException(docgraph, "Shipment");
                                }
                            }

                            if (anyfailed)
                            {
                                throw new PXOperationCompletedWithErrorException(ErrorMessages.SeveralItemsFailed);
                            }
                        });
                }
                return(list);
            }

            default:
                return(baseMtd(adapter, actionID, shipDate, siteCD, operation, ActionName));
            }
        }
        public static void RunRecognition(List <ScheduledTran> trans, DateTime?filterDate)
        {
            ScheduleMaint scheduleMaint = PXGraph.CreateInstance <ScheduleMaint>();

            scheduleMaint.Clear();

            bool failed = false;

            List <ScheduledTran> items = GetValidatedItems(trans, scheduleMaint);

            failed = items.Count() < trans.Count();

            // Save virtual records:
            // -
            foreach (ScheduledTran tr in items)
            {
                PXProcessing <ScheduledTran> .SetCurrentItem(tr);

                if (tr.IsVirtual == true)
                {
                    try
                    {
                        scheduleMaint.Document.Current = PXSelect <DRScheduleDetail,
                                                                   Where <DRScheduleDetail.scheduleID, Equal <Required <DRScheduleDetail.scheduleID> >,
                                                                          And <DRScheduleDetail.componentID, Equal <Required <DRScheduleDetail.componentID> > > > >
                                                         .Select(scheduleMaint, tr.ScheduleID, tr.ComponentID ?? DRScheduleDetail.EmptyComponentID);

                        DRScheduleTran tran = new DRScheduleTran();
                        tran.BranchID    = tr.BranchID;
                        tran.AccountID   = tr.AccountID;
                        tran.SubID       = tr.SubID;
                        tran.AdjgDocType = tr.AdjgDocType;
                        tran.AdjgRefNbr  = tr.AdjgRefNbr;
                        tran.AdjNbr      = tr.AdjNbr;
                        tran.Amount      = tr.Amount;
                        tran.ComponentID = tr.ComponentID ?? DRScheduleDetail.EmptyComponentID;
                        tran.FinPeriodID = tr.FinPeriodID;
                        tran.ScheduleID  = tr.ScheduleID;
                        tran.RecDate     = tr.RecDate;
                        tran.Status      = DRScheduleTranStatus.Open;

                        tran       = scheduleMaint.OpenTransactions.Insert(tran);
                        tr.LineNbr = tran.LineNbr;

                        scheduleMaint.RebuildProjections();

                        scheduleMaint.Save.Press();
                        byte[] ts = scheduleMaint.TimeStamp;
                        scheduleMaint.Clear();
                        scheduleMaint.TimeStamp = ts;
                        PXProcessing <ScheduledTran> .SetProcessed();
                    }

                    catch (Exception ex)
                    {
                        failed = true;
                        PXProcessing <ScheduledTran> .SetError(ex.Message);
                    }
                }
                else
                {
                    PXProcessing <ScheduledTran> .SetProcessed();
                }
            }

            PXProcessing <ScheduledTran> .SetCurrentItem(null);

            List <DRBatch> list = SplitByFinPeriod(items);

            DRProcess process = CreateInstance <DRProcess>();

            process.Clear();
            process.TimeStamp = scheduleMaint.TimeStamp;
            List <Batch> batchlist = process.RunRecognition(list, filterDate);

            PostGraph pg = PXGraph.CreateInstance <PostGraph>();
            //Post Batches if AutoPost

            bool postFailed = false;

            if (pg.AutoPost)
            {
                foreach (Batch batch in batchlist)
                {
                    try
                    {
                        pg.Clear();
                        pg.TimeStamp = batch.tstamp;
                        pg.PostBatchProc(batch);
                    }
                    catch (Exception)
                    {
                        postFailed = true;
                    }
                }
                if (postFailed)
                {
                    throw new PXException(Messages.AutoPostFailed);
                }
            }

            if (failed)
            {
                throw new PXException(GL.Messages.DocumentsNotReleased);
            }
        }
Ejemplo n.º 12
0
        protected virtual void PrintPayments(List <APPayment> list, PrintChecksFilter filter, PaymentMethod paymentMethod)
        {
            if (list.Count == 0)
            {
                return;
            }

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

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

            bool printAdditionRemit = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        printAdditionRemit |= seldoc.BillCntr > paymentMethod.APStubLines;

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

                        idxReportFilter++;

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

                        failed       = true;
                        nextCheckNbr = prevCheckNbr;
                    }
                }

                if (failed)
                {
                    PXReportRequiredException report = null;
                    if (d.Count > 0)
                    {
                        d[ReportMessages.CheckReportFlag] = ReportMessages.CheckReportFlagValue;
                        report = new PXReportRequiredException(d, paymentMethod.APCheckReportID, PXBaseRedirectException.WindowMode.New, "Check");
                    }
                    throw new PXOperationCompletedWithErrorException(GL.Messages.DocumentsNotReleased, report);
                }
                else
                {
                    if (d.Count > 0)
                    {
                        RedirectToResultNoBatch(pp, d, paymentMethod, printAdditionRemit, nextCheckNbr);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public static void ProcessPendingVATProc(List <TaxTran> list)
        {
            JournalEntry je = PXGraph.CreateInstance <JournalEntry>();

            PXCache dummycache = je.Caches[typeof(TaxTran)];

            dummycache = je.Caches[typeof(VATTaxTran)];
            je.Views.Caches.Add(typeof(VATTaxTran));

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

            foreach (TaxTran taxtran in list)
            {
                PXProcessing <TaxTran> .SetCurrentItem(taxtran);

                if (string.IsNullOrEmpty(taxtran.TaxInvoiceNbr) == true || taxtran.TaxInvoiceDate == null)
                {
                    //PXProcessing<TaxTran>.SetWarning(Messages.CannotProcessW);
                    PXProcessing <TaxTran> .SetError(Messages.CannotProcessW);
                }
                else
                {
                    using (PXTransactionScope ts = new PXTransactionScope())
                    {
                        foreach (PXResult <VATTaxTran, CurrencyInfo, Tax> res  in PXSelectJoin <VATTaxTran, InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <VATTaxTran.curyInfoID> >, InnerJoin <Tax, On <Tax.taxID, Equal <VATTaxTran.taxID> > > >, Where <VATTaxTran.module, Equal <Current <TaxTran.module> >, And <VATTaxTran.tranType, Equal <Current <TaxTran.tranType> >, And <VATTaxTran.refNbr, Equal <Current <TaxTran.refNbr> >, And <VATTaxTran.taxID, Equal <Current <TaxTran.taxID> > > > > > > .SelectSingleBound(je, new object[] { taxtran }))
                        {
                            VATTaxTran   n    = (VATTaxTran)res;
                            CurrencyInfo info = (CurrencyInfo)res;
                            Tax          x    = (Tax)res;

                            string strFinPeriodID = FinPeriodSelectorAttribute.PeriodFromDate(taxtran.TaxInvoiceDate);
                            SegregateBatch(je, info.CuryID, taxtran.TaxInvoiceDate, strFinPeriodID, created);

                            n.TaxInvoiceNbr  = taxtran.TaxInvoiceNbr;
                            n.TaxInvoiceDate = taxtran.TaxInvoiceDate;

                            je.Caches[typeof(VATTaxTran)].Update(n);

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

                            new_info.CuryInfoID = null;
                            new_info.ModuleCode = "GL";
                            new_info.BaseCalc   = false;
                            new_info            = je.currencyinfo.Insert(new_info) ?? new_info;

                            //reverse original transaction
                            {
                                GLTran tran = new GLTran();
                                tran.AccountID     = n.AccountID;
                                tran.SubID         = n.SubID;
                                tran.CuryDebitAmt  = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? n.CuryTaxAmt : 0m;
                                tran.DebitAmt      = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? n.TaxAmt : 0m;
                                tran.CuryCreditAmt = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? 0m : n.CuryTaxAmt;
                                tran.CreditAmt     = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? 0m : n.TaxAmt;
                                tran.TranType      = n.TranType;
                                tran.TranClass     = "N";
                                tran.RefNbr        = n.RefNbr;
                                tran.TranDesc      = n.TaxInvoiceNbr;
                                tran.TranPeriodID  = strFinPeriodID;
                                tran.FinPeriodID   = strFinPeriodID;
                                tran.TranDate      = n.TaxInvoiceDate;
                                tran.CuryInfoID    = new_info.CuryInfoID;
                                tran.Released      = true;

                                je.GLTranModuleBatNbr.Insert(tran);

                                VATTaxTran newtran = PXCache <VATTaxTran> .CreateCopy(n);

                                newtran.Module         = "GL";
                                newtran.TranType       = (n.TaxType == TaxType.PendingSales) ? TaxAdjustmentType.ReverseOutputVAT : TaxAdjustmentType.ReverseInputVAT;
                                newtran.RefNbr         = newtran.TaxInvoiceNbr;
                                newtran.TranDate       = newtran.TaxInvoiceDate;
                                newtran.CuryTaxableAmt = -ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.CuryTaxableAmt;
                                newtran.TaxableAmt     = -ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.TaxableAmt;
                                newtran.CuryTaxAmt     = -ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.CuryTaxAmt;
                                newtran.TaxAmt         = -ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.TaxAmt;

                                je.Caches[typeof(VATTaxTran)].Insert(newtran);
                            }

                            //reclassify to VAT account
                            {
                                GLTran tran = new GLTran();
                                tran.AccountID     = (n.TaxType == TaxType.PendingSales) ? x.SalesTaxAcctID : x.PurchTaxAcctID;
                                tran.SubID         = (n.TaxType == TaxType.PendingSales) ? x.SalesTaxSubID : x.PurchTaxSubID;
                                tran.CuryDebitAmt  = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? 0m : n.CuryTaxAmt;
                                tran.DebitAmt      = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? 0m : n.TaxAmt;
                                tran.CuryCreditAmt = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? n.CuryTaxAmt : 0m;
                                tran.CreditAmt     = (n.TaxType == TaxType.PendingSales && ReportTaxProcess.GetMult(n) == 1m) ? n.TaxAmt : 0m;
                                tran.TranType      = n.TranType;
                                tran.TranClass     = "N";
                                tran.RefNbr        = n.RefNbr;
                                tran.TranDesc      = n.TaxInvoiceNbr;
                                tran.TranPeriodID  = strFinPeriodID;
                                tran.FinPeriodID   = strFinPeriodID;
                                tran.TranDate      = n.TaxInvoiceDate;
                                tran.CuryInfoID    = new_info.CuryInfoID;
                                tran.Released      = true;

                                je.GLTranModuleBatNbr.Insert(tran);

                                VATTaxTran newtran = PXCache <VATTaxTran> .CreateCopy(n);

                                newtran.Module         = "GL";
                                newtran.TranType       = (n.TaxType == TaxType.PendingSales) ? TaxAdjustmentType.OutputVAT : TaxAdjustmentType.InputVAT;
                                newtran.TaxType        = (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase;
                                newtran.AccountID      = (n.TaxType == TaxType.PendingSales) ? x.SalesTaxAcctID : x.PurchTaxAcctID;
                                newtran.SubID          = (n.TaxType == TaxType.PendingSales) ? x.SalesTaxSubID : x.PurchTaxSubID;
                                newtran.RefNbr         = newtran.TaxInvoiceNbr;
                                newtran.TranDate       = newtran.TaxInvoiceDate;
                                newtran.CuryTaxableAmt = ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.CuryTaxableAmt;
                                newtran.TaxableAmt     = ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.TaxableAmt;
                                newtran.CuryTaxAmt     = ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.CuryTaxAmt;
                                newtran.TaxAmt         = ReportTaxProcess.GetMult(n.Module, n.TranType, (n.TaxType == TaxType.PendingSales) ? TaxType.Sales : TaxType.Purchase, (short)1) * newtran.TaxAmt;

                                je.Caches[typeof(VATTaxTran)].Insert(newtran);
                            }
                        }

                        je.Save.Press();

                        ts.Complete();
                    }
                    PXProcessing <TaxTran> .SetProcessed();
                }
            }
        }
Ejemplo n.º 14
0
        public void Revalue(RevalueFilter filter, List <RevaluedAPHistory> list)
        {
            JournalEntry je        = PXGraph.CreateInstance <JournalEntry>();
            PostGraph    pg        = PXGraph.CreateInstance <PostGraph>();
            PXCache      cache     = je.Caches[typeof(CuryAPHist)];
            PXCache      basecache = je.Caches[typeof(APHist)];

            je.Views.Caches.Add(typeof(CuryAPHist));
            je.Views.Caches.Add(typeof(APHist));

            string extRefNbrNumbering = je.CMSetup.Current.ExtRefNbrNumberingID;

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

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

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

            bool hasErrors = false;

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (RevaluedAPHistory hist in list)
                {
                    if (hist.FinPtdRevalued == 0m)
                    {
                        continue;
                    }

                    PXProcessing <RevaluedAPHistory> .SetCurrentItem(hist);

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

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

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

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

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

                        cmbatch              = new Batch();
                        cmbatch.BranchID     = hist.BranchID;
                        cmbatch.Module       = "CM";
                        cmbatch.Status       = "U";
                        cmbatch.AutoReverse  = true;
                        cmbatch.Released     = true;
                        cmbatch.Hold         = false;
                        cmbatch.DateEntered  = filter.CuryEffDate;
                        cmbatch.FinPeriodID  = filter.FinPeriodID;
                        cmbatch.TranPeriodID = filter.FinPeriodID;
                        cmbatch.CuryID       = hist.CuryID;
                        cmbatch.CuryInfoID   = info.CuryInfoID;
                        cmbatch.DebitTotal   = 0m;
                        cmbatch.CreditTotal  = 0m;
                        cmbatch.Description  = filter.Description;
                        je.BatchModule.Insert(cmbatch);

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

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

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

                        tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;
                        tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;

                        tran.TranType     = "REV";
                        tran.TranClass    = AccountType.Liability;
                        tran.RefNbr       = string.Empty;
                        tran.TranDesc     = filter.Description;
                        tran.TranPeriodID = filter.FinPeriodID;
                        tran.FinPeriodID  = filter.FinPeriodID;
                        tran.TranDate     = filter.CuryEffDate;
                        tran.CuryInfoID   = null;
                        tran.Released     = true;
                        tran.ReferenceID  = hist.VendorID;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    VendorClass vendclass = PXSelectReadonly <VendorClass, Where <VendorClass.vendorClassID, Equal <Required <VendorClass.vendorClassID> > > > .Select(je, hist.VendorClassID);

                    if (vendclass == null)
                    {
                        vendclass = new VendorClass();
                    }

                    if (vendclass.UnrealizedGainAcctID == null)
                    {
                        vendclass.UnrealizedGainSubID = null;
                    }

                    if (vendclass.UnrealizedLossAcctID == null)
                    {
                        vendclass.UnrealizedLossSubID = null;
                    }

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

                        if (je.BatchModule.Current.DebitTotal > je.BatchModule.Current.CreditTotal)
                        {
                            tran.AccountID = vendclass.UnrealizedGainAcctID ?? currency.UnrealizedGainAcctID;
                            tran.SubID     = vendclass.UnrealizedGainSubID ?? GainLossSubAccountMaskAttribute.GetSubID <Currency.unrealizedGainSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = 0m;
                            tran.CreditAmt = (je.BatchModule.Current.DebitTotal - je.BatchModule.Current.CreditTotal);
                        }
                        else
                        {
                            tran.AccountID = vendclass.UnrealizedLossAcctID ?? currency.UnrealizedLossAcctID;
                            tran.SubID     = vendclass.UnrealizedLossSubID ?? GainLossSubAccountMaskAttribute.GetSubID <Currency.unrealizedLossSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = (je.BatchModule.Current.CreditTotal - je.BatchModule.Current.DebitTotal);
                            tran.CreditAmt = 0m;
                        }

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

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    {
                        CuryAPHist aphist = new CuryAPHist();
                        aphist.BranchID    = hist.BranchID;
                        aphist.AccountID   = hist.AccountID;
                        aphist.SubID       = hist.SubID;
                        aphist.FinPeriodID = filter.FinPeriodID;
                        aphist.VendorID    = hist.VendorID;
                        aphist.CuryID      = hist.CuryID;

                        aphist = (CuryAPHist)cache.Insert(aphist);
                        aphist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    {
                        APHist aphist = new APHist();
                        aphist.BranchID    = hist.BranchID;
                        aphist.AccountID   = hist.AccountID;
                        aphist.SubID       = hist.SubID;
                        aphist.FinPeriodID = filter.FinPeriodID;
                        aphist.VendorID    = hist.VendorID;

                        aphist = (APHist)basecache.Insert(aphist);
                        aphist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    PXProcessing <RevaluedAPHistory> .SetProcessed();
                }

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

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

                ts.Complete();
            }

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

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

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

                throw new PXException(ErrorMessages.SeveralItemsFailed);
            }

            if (created.Count > 0)
            {
                je.BatchModule.Current = created[created.Count - 1];
                throw new PXRedirectRequiredException(je, "Preview");
            }
        }
Ejemplo n.º 15
0
        public static void BuildIndex(FullTextIndexRebuildProc graph, RecordType item)
        {
            Debug.Print("Start processing {0}", item.Name);
            Stopwatch sw = new Stopwatch();

            graph.Caches.Clear();
            graph.Clear(PXClearOption.ClearAll);

            PXProcessing <RecordType> .SetCurrentItem(item);

            Type entity = GraphHelper.GetType(item.Entity);

            PXSearchableAttribute searchableAttribute = null;
            var list = graph.Caches[entity].GetAttributes("NoteID");

            foreach (PXEventSubscriberAttribute att in list)
            {
                PXSearchableAttribute attribute = att as PXSearchableAttribute;
                if (attribute != null)
                {
                    searchableAttribute = attribute;
                    break;
                }
            }

            if (searchableAttribute == null)
            {
                return;
            }

            Type viewType;


            Type joinNote = typeof(LeftJoin <Note, On <Note.noteID, Equal <SearchIndex.noteID> > >);

            if (searchableAttribute.SelectForFastIndexing != null)
            {
                Type noteentity = entity;
                if (searchableAttribute.SelectForFastIndexing.IsGenericType)
                {
                    Type[] tables = searchableAttribute.SelectForFastIndexing.GetGenericArguments();
                    if (tables != null && tables.Length > 0 && typeof(IBqlTable).IsAssignableFrom(tables[0]))
                    {
                        noteentity = tables[0];
                    }
                }
                Type joinSearchIndex = BqlCommand.Compose(
                    typeof(LeftJoin <,>),
                    typeof(SearchIndex),
                    typeof(On <,>),
                    typeof(SearchIndex.noteID),
                    typeof(Equal <>),
                    noteentity.GetNestedType("noteID"));

                viewType = BqlCommand.AppendJoin(searchableAttribute.SelectForFastIndexing, joinSearchIndex);
                viewType = BqlCommand.AppendJoin(viewType, joinNote);
            }
            else
            {
                Type joinSearchIndex = BqlCommand.Compose(
                    typeof(LeftJoin <,>),
                    typeof(SearchIndex),
                    typeof(On <,>),
                    typeof(SearchIndex.noteID),
                    typeof(Equal <>),
                    entity.GetNestedType("noteID"));

                viewType = BqlCommand.Compose(typeof(Select <>), entity);
                viewType = BqlCommand.AppendJoin(viewType, joinSearchIndex);
                viewType = BqlCommand.AppendJoin(viewType, joinNote);
            }

            BqlCommand cmd = BqlCommand.CreateInstance(viewType);

            PXView        itemView = new PXView(graph, true, cmd);
            List <object> resultset;

            List <Type> fieldList       = new List <Type>(searchableAttribute.GetSearchableFields(graph.Caches[entity]));
            Type        entityForNoteId = entity;

            while (typeof(IBqlTable).IsAssignableFrom(entityForNoteId))
            {
                Type tN = entityForNoteId.GetNestedType("noteID");
                if (null != tN)
                {
                    fieldList.Add(tN);
                }
                entityForNoteId = entityForNoteId.BaseType;
            }
            fieldList.Add(typeof(SearchIndex.noteID));
            fieldList.Add(typeof(SearchIndex.category));
            fieldList.Add(typeof(SearchIndex.content));
            fieldList.Add(typeof(SearchIndex.entityType));
            fieldList.Add(typeof(Note.noteID));
            fieldList.Add(typeof(Note.noteText));

            sw.Start();
            using (new PXFieldScope(itemView, fieldList))
            {
                resultset = itemView.SelectMulti();
            }
            sw.Stop();
            Debug.Print("{0} GetResultset in {1} sec. Total records={2}", item.DisplayName, sw.Elapsed.TotalSeconds, resultset.Count);
            sw.Reset();
            sw.Start();

            int totalcount = resultset.Count;
            int cx         = 0;
            int dx         = 0;

            try
            {
                Dictionary <Guid, SearchIndex> insertDict = new Dictionary <Guid, SearchIndex>(resultset.Count);
                foreach (var res in resultset)
                {
                    cx++;

                    bool isSearchable = searchableAttribute.IsSearchable(graph.Caches[entity], ((PXResult)res)[entity]);
                    if (isSearchable)
                    {
                        dx++;

                        Note        note = (Note)((PXResult)res)[typeof(Note)];
                        SearchIndex si   = searchableAttribute.BuildSearchIndex(graph.Caches[entity], ((PXResult)res)[entity],
                                                                                (PXResult)res, ExtractNoteText(note));
                        SearchIndex searchIndex = (SearchIndex)((PXResult)res)[typeof(SearchIndex)];

                        if (searchIndex.NoteID != null && searchIndex.NoteID != si.NoteID)
                        {
                            PXSearchableAttribute.Delete(si);
                        }

                        if (searchIndex.NoteID == null)
                        {
                            if (!insertDict.ContainsKey(si.NoteID.Value))
                            {
                                insertDict.Add(si.NoteID.Value, si);
                            }
                        }
                        else if (si.Content != searchIndex.Content || si.Category != searchIndex.Category ||
                                 si.EntityType != searchIndex.EntityType)
                        {
                            PXSearchableAttribute.Update(si);
                        }
                    }
                }
                sw.Stop();
                Debug.Print("{0} Content building in {1} sec. Records processed = {2}. Searchable={3}", item.DisplayName, sw.Elapsed.TotalSeconds, totalcount, dx);
                sw.Reset();
                sw.Start();
                PXSearchableAttribute.BulkInsert(insertDict.Values);
                sw.Stop();
                Debug.Print("{0} BulkInsert in {1} sec.", item.DisplayName, sw.Elapsed.TotalSeconds);
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0} out of {1} processed. {2} are searchable. Error:{3}", cx, totalcount, dx, ex.Message);
                throw new Exception(msg, ex);
            }

            PXProcessing <RecordType> .SetProcessed();
        }
Ejemplo n.º 16
0
        protected virtual IEnumerable LumGenerate3PLUKFile(PXAdapter adapter, [PXDate] DateTime?shipDate, [PXInt] int?siteID, [SOOperation.List] string operation)
        {
            try
            {
                // Create SOShipment Graph
                var graph   = PXGraph.CreateInstance <SOShipmentEntry>();
                var soOrder = adapter.Get <SOOrder>().FirstOrDefault();
                using (PXTransactionScope sc = new PXTransactionScope())
                {
                    // FBM wont create Shipment, only upload file to FTP
                    if (soOrder.OrderType == "FM")
                    {
                        // Combine csv data
                        var result = graph.GetExtension <SOShipmentEntryExt>().CombineCSVForFBM(soOrder, "P3PL");
                        // Upload Graph
                        UploadFileMaintenance upload = PXGraph.CreateInstance <UploadFileMaintenance>();
                        // Create SM.FileInfo
                        var      fileName = $"{soOrder.OrderNbr}.csv";
                        var      data     = new UTF8Encoding(true).GetBytes(result.csvText.ToString());
                        FileInfo fi       = new FileInfo(fileName, null, data);

                        // upload file to FTP
                        #region 3PL UK FTP
                        var configYusen = SelectFrom <LUM3PLUKSetup> .View.Select(Base).RowCast <LUM3PLUKSetup>().FirstOrDefault();

                        FTP_Config config = new FTP_Config()
                        {
                            FtpHost = configYusen.FtpHost,
                            FtpUser = configYusen.FtpUser,
                            FtpPass = configYusen.FtpPass,
                            FtpPort = configYusen.FtpPort,
                            FtpPath = configYusen.FtpPath
                        };

                        var ftpResult = graph.GetExtension <SOShipmentEntryExt>().UploadFileByFTP(config, fileName, data);
                        //var ftpResult = true;
                        if (!ftpResult)
                        {
                            throw new Exception("Ftp Upload Fail!!");
                        }
                        #endregion

                        // upload file to Attachment
                        upload.SaveFile(fi);
                        PXNoteAttribute.SetFileNotes(Base.Document.Cache, Base.Document.Current, fi.UID.Value);
                        Base.Save.Press();
                        PXProcessing.SetProcessed();
                    }
                    else
                    {
                        // Create Shipment
                        Base.CreateShipmentIssue(adapter, shipDate, siteID);
                        if (PXProcessing <SOOrder> .GetItemMessage().ErrorLevel != PXErrorLevel.RowInfo)
                        {
                            return(null);
                        }

                        // Find SOShipment
                        var _soOrderShipment =
                            FbqlSelect <SelectFromBase <SOOrderShipment, TypeArrayOf <IFbqlJoin> .Empty> .Where <BqlChainableConditionBase <TypeArrayOf <IBqlBinary> .FilledWith <And <Compare <SOOrderShipment.orderType, Equal <P.AsString> > > > > .And <BqlOperand <SOOrderShipment.orderNbr, IBqlString> .IsEqual <P.AsString> > >, SOOrderShipment> .View.Select(Base, soOrder.OrderType, soOrder.OrderNbr)
                            .RowCast <SOOrderShipment>().FirstOrDefault();

                        // Create new Adapter
                        var newAdapter = new PXAdapter(graph.Document)
                        {
                            Searches = new Object[] { _soOrderShipment.ShipmentNbr }
                        };
                        // Generate UK csv file and upload to FTP
                        graph.GetExtension <SOShipmentEntryExt>().lumGenerate3PLUKFile.PressButton(newAdapter);
                        // Remove Hold
                        graph.releaseFromHold.PressButton(newAdapter);
                    }
                    if (PXProcessing <SOOrder> .GetItemMessage().ErrorLevel == PXErrorLevel.RowInfo)
                    {
                        sc.Complete();
                    }
                }
            }
            catch (Exception ex)
            {
                PXProcessing.SetError <SOOrder>(ex.Message);
            }
            return(adapter.Get());
        }
Ejemplo n.º 17
0
        private static void ClaimDetail(List <EPExpenseClaimDetails> details, bool isApiContext, bool singleOperation)
        {
            ExpenseClaimEntry expenseClaimEntry = CreateInstance <ExpenseClaimEntry>();
            PXSetup <EPSetup> epsetup           = new PXSetup <EPSetup>(PXGraph.CreateInstance(typeof(ExpenseClaimDetailEntry)));
            bool enabledApprovalReceipt         = PXAccess.FeatureInstalled <FeaturesSet.approvalWorkflow>() && epsetup.Current.ClaimDetailsAssignmentMapID != null;
            bool isError        = false;
            bool notAllApproved = false;
            Dictionary <string, EPExpenseClaim> result = new Dictionary <string, EPExpenseClaim>();

            IEnumerable <Receipts> List;

            if (epsetup.Current.AllowMixedTaxSettingInClaims == true)
            {
                List = details.Where(item => string.IsNullOrEmpty(item.RefNbr)).OrderBy(detail => detail.ClaimDetailID).GroupBy(
                    item => new
                {
                    item.EmployeeID,
                    item.BranchID,
                    item.CustomerID,
                    item.CustomerLocationID,
                    ClaimCuryID = GetClaimCuryID(expenseClaimEntry, item)
                },
                    (key, item) => new Receipts
                {
                    employee         = key.EmployeeID,
                    branch           = key.BranchID,
                    customer         = key.CustomerID,
                    customerLocation = key.CustomerLocationID,
                    claimCuryID      = key.ClaimCuryID,
                    details          = item
                }
                    );
            }
            else
            {
                List = details.Where(item => string.IsNullOrEmpty(item.RefNbr)).OrderBy(detail => detail.ClaimDetailID).GroupBy(
                    item => new
                {
                    item.EmployeeID,
                    item.BranchID,
                    item.CustomerID,
                    item.CustomerLocationID,
                    item.TaxZoneID,
                    item.TaxCalcMode,
                    ClaimCuryID = GetClaimCuryID(expenseClaimEntry, item)
                },
                    (key, item) => new Receipts
                {
                    employee         = key.EmployeeID,
                    branch           = key.BranchID,
                    customer         = key.CustomerID,
                    customerLocation = key.CustomerLocationID,
                    claimCuryID      = key.ClaimCuryID,
                    details          = item
                }
                    );
            }

            string errorMessage = null;

            foreach (Receipts item in List)
            {
                isError        = false;
                notAllApproved = false;
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    expenseClaimEntry.Clear();
                    expenseClaimEntry.SelectTimeStamp();
                    EPExpenseClaim expenseClaim = (EPExpenseClaim)expenseClaimEntry.ExpenseClaim.Cache.CreateInstance();
                    expenseClaim.EmployeeID         = item.employee;
                    expenseClaim.BranchID           = item.branch;
                    expenseClaim.CustomerID         = item.customer;
                    expenseClaim.DocDesc            = EP.Messages.SubmittedReceipt;
                    expenseClaim                    = expenseClaimEntry.ExpenseClaim.Update(expenseClaim);
                    expenseClaim.CuryID             = item.claimCuryID;
                    expenseClaim                    = expenseClaimEntry.ExpenseClaim.Update(expenseClaim);
                    expenseClaim.CustomerLocationID = item.customerLocation;
                    expenseClaim.TaxCalcMode        = item.details.First().TaxCalcMode;
                    expenseClaim.TaxZoneID          = item.details.First().TaxZoneID;

                    foreach (EPExpenseClaimDetails detail in item.details)
                    {
                        PXProcessing <EPExpenseClaimDetails> .SetCurrentItem(detail);

                        if (detail.Approved ?? false)
                        {
                            try
                            {
                                if (detail.IsPaidWithCard)
                                {
                                    EPEmployee employee =
                                        PXSelect <EPEmployee,
                                                  Where <EPEmployee.bAccountID, Equal <Required <EPEmployee.bAccountID> > > >
                                        .Select(expenseClaimEntry, item.employee);

                                    if (employee.AllowOverrideCury != true && detail.CardCuryID != employee.CuryID)
                                    {
                                        errorMessage = PXMessages.Localize(Messages.ClaimCannotBeCreatedForReceiptBecauseCuryCannotBeOverriden);

                                        isError = true;
                                    }
                                }

                                if (!isError && detail.TipAmt != 0 && epsetup.Current.NonTaxableTipItem == null)
                                {
                                    errorMessage = Messages.TipItemIsNotDefined;
                                    isError      = true;
                                }

                                if (!isError)
                                {
                                    expenseClaimEntry.ReceiptEntryExt.SubmitReceiptExt(expenseClaimEntry.ExpenseClaim.Cache,
                                                                                       expenseClaimEntry.ExpenseClaimDetails.Cache, expenseClaimEntry.ExpenseClaim.Current, detail);

                                    expenseClaimEntry.Save.Press();
                                    if (!result.ContainsKey(expenseClaim.RefNbr))
                                    {
                                        result.Add(expenseClaim.RefNbr, expenseClaim);
                                    }
                                    detail.RefNbr = expenseClaim.RefNbr;

                                    PXProcessing <EPExpenseClaimDetails> .SetProcessed();
                                }
                            }
                            catch (Exception ex)
                            {
                                errorMessage = ex.Message;
                                isError      = true;
                            }
                        }
                        else
                        {
                            errorMessage = enabledApprovalReceipt
                                                                ? Messages.ReceiptNotApproved
                                                                : Messages.ReceiptTakenOffHold;

                            notAllApproved = true;
                        }

                        if (errorMessage != null)
                        {
                            PXProcessing <EPExpenseClaimDetails> .SetError(errorMessage);
                        }
                    }
                    if (!isError)
                    {
                        ts.Complete();
                    }
                }
            }

            if (!isError && !notAllApproved)
            {
                if (result.Count == 1 && isApiContext == false)
                {
                    expenseClaimEntry = CreateInstance <ExpenseClaimEntry>();
                    PXRedirectHelper.TryRedirect(expenseClaimEntry, result.First().Value, PXRedirectHelper.WindowMode.InlineWindow);
                }
            }
            else
            {
                PXProcessing <EPExpenseClaimDetails> .SetCurrentItem(null);

                if (singleOperation)
                {
                    throw new PXException(errorMessage);
                }
                else
                {
                    throw new PXException(Messages.ErrorProcessingReceipts);
                }
            }
        }
Ejemplo n.º 18
0
        public void Process(List <MISC1099EFileProcessingInfo> records, MISC1099EFileFilter filter)
        {
            using (new PXReadBranchRestrictedScope(MarkedBranches))
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (StreamWriter sw = new StreamWriter(stream, Encoding.Unicode))
                    {
                        BranchMaint graph = CreateInstance <BranchMaint>();

                        foreach (PXResult <Branch, BranchMaint.BranchBAccount, Contact, Address, LocationExtAddress> transmitter in Payer.Select(filter.MasterBranchID))
                        {
                            TransmitterTRecord trecord      = CreateTransmitterRecord(transmitter, transmitter, transmitter, filter, 0);
                            List <object>      data1099Misc = new List <object> {
                                trecord
                            };

                            List <IGrouping <int?, MISC1099EFileProcessingInfo> > groups = records.GroupBy(rec => rec.PayerBranchID).ToList();
                            foreach (IGrouping <int?, MISC1099EFileProcessingInfo> group in groups)
                            {
                                foreach (PXResult <Branch, BranchMaint.BranchBAccount, Contact, Address, LocationExtAddress> payer in Payer.Select(@group.Key))
                                {
                                    Contact rowShipContact = PXSelectJoin <Contact,
                                                                           InnerJoin <Location, On <Contact.bAccountID, Equal <Location.bAccountID>,
                                                                                                    And <Contact.contactID, Equal <Location.defContactID> > > >,
                                                                           Where <Location.bAccountID, Equal <Required <BAccount.bAccountID> >,
                                                                                  And <Location.locationID, Equal <Required <BAccount.defLocationID> > > > >
                                                             .Select(graph, ((BranchMaint.BranchBAccount)payer).BranchBAccountID, ((BranchMaint.BranchBAccount)payer).DefLocationID);

                                    data1099Misc.Add(CreatePayerARecord(payer, payer, payer, payer, rowShipContact, filter));

                                    List <PayeeRecordB> payeeRecs = new List <PayeeRecordB>();
                                    foreach (MISC1099EFileProcessingInfo rec in @group)
                                    {
                                        PXProcessing <AP1099History> .SetCurrentItem(rec);

                                        payeeRecs.Add(CreatePayeeBRecord(graph, payer, rec, filter));
                                        PXProcessing <AP1099History> .SetProcessed();
                                    }
                                    payeeRecs = payeeRecs.WhereNotNull().ToList();
                                    trecord.TotalNumberofPayees = payeeRecs.Count.ToString();
                                    data1099Misc.AddRange(payeeRecs);
                                    data1099Misc.Add(CreateEndOfPayerRecordC(payeeRecs));

                                    //If combined State Filer then only generate K Record.
                                    if (((Branch)payer).CFSFiler == true)
                                    {
                                        data1099Misc.AddRange(payeeRecs
                                                              .Where(x => !string.IsNullOrWhiteSpace(x.PayeeState))
                                                              .GroupBy(x => x.PayeeState.Trim(), StringComparer.CurrentCultureIgnoreCase)
                                                              .Select(y => CreateStateTotalsRecordK(y.ToList()))
                                                              .Where(kRecord => kRecord != null));
                                    }
                                }
                            }

                            data1099Misc.Add(CreateEndOfTransmissionRecordF(groups.Count, records.Count));

                            //Write to file
                            FixedLengthFile flatFile = new FixedLengthFile();

                            flatFile.WriteToFile(data1099Misc, sw);
                            sw.Flush();

                            const string   path = "1099-MISC.txt";
                            PX.SM.FileInfo info = new PX.SM.FileInfo(path, null, stream.ToArray());

                            throw new PXRedirectToFileException(info, true);
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private static void ClaimDetail(List <EPExpenseClaimDetails> details)
        {
            PXSetup <EPSetup> epsetup   = new PXSetup <EPSetup>(PXGraph.CreateInstance(typeof(ExpenseClaimDetailEntry)));
            bool enabledApprovalReceipt = PXAccess.FeatureInstalled <FeaturesSet.approvalWorkflow>() && epsetup.Current.ClaimDetailsAssignmentMapID != null;
            bool isError        = false;
            bool notAllApproved = false;
            bool emptyClaim     = true;
            var  List           = details.Where(item => string.IsNullOrEmpty(item.RefNbr)).OrderBy(detail => detail.ClaimDetailID).GroupBy(
                item => new { item.EmployeeID, item.BranchID, item.CustomerID, item.CustomerLocationID }
                , (key, item) => new { employee = key.EmployeeID, branch = key.BranchID, customer = key.CustomerID, customerLocation = key.CustomerLocationID, details = item }
                );

            List <EPExpenseClaim> result = new List <EPExpenseClaim>();

            foreach (var item in List)
            {
                isError        = false;
                notAllApproved = false;
                emptyClaim     = true;
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    ExpenseClaimEntry expenseClaimEntry = CreateInstance <ExpenseClaimEntry>();
                    EPExpenseClaim    expenseClaim      = (EPExpenseClaim)expenseClaimEntry.ExpenseClaim.Cache.CreateInstance();
                    expenseClaim.EmployeeID         = item.employee;
                    expenseClaim.BranchID           = item.branch;
                    expenseClaim.CustomerID         = item.customer;
                    expenseClaim.DocDesc            = EP.Messages.SubmittedReceipt;
                    expenseClaim                    = expenseClaimEntry.ExpenseClaim.Update(expenseClaim);
                    expenseClaim.CustomerLocationID = item.customerLocation;

                    foreach (EPExpenseClaimDetails detail in item.details)
                    {
                        PXProcessing <EPExpenseClaimDetails> .SetCurrentItem(detail);

                        if (detail.Approved ?? false)
                        {
                            try
                            {
                                expenseClaimEntry.SubmitDetail(detail);
                                PXProcessing <EPExpenseClaimDetails> .SetProcessed();

                                emptyClaim = false;
                            }
                            catch (Exception ex)
                            {
                                PXProcessing <EPExpenseClaimDetails> .SetError(ex);

                                isError = true;
                            }
                        }
                        else
                        {
                            PXProcessing.SetError(enabledApprovalReceipt
                                ? Messages.ReceiptNotApproved
                                : Messages.ReceiptTakenOffHold);
                            notAllApproved = true;
                        }
                    }

                    if (!emptyClaim)
                    {
                        try
                        {
                            expenseClaimEntry.Actions.PressSave();
                            result.Add(expenseClaim);
                        }
                        catch (Exception ex)
                        {
                            foreach (EPExpenseClaimDetails detail in item.details)
                            {
                                PXProcessing <EPExpenseClaimDetails> .SetCurrentItem(detail);

                                PXProcessing <EPExpenseClaimDetails> .SetError(ex);
                            }
                            isError = true;
                        }
                    }
                    if (!isError)
                    {
                        ts.Complete();
                    }
                }
            }

            if (!isError && !notAllApproved)
            {
                if (result.Count == 1)
                {
                    ExpenseClaimEntry expenseClaimEntry = CreateInstance <ExpenseClaimEntry>();
                    PXRedirectHelper.TryRedirect(expenseClaimEntry, result[0], PXRedirectHelper.WindowMode.InlineWindow);
                }
            }
            else
            {
                PXProcessing <EPExpenseClaimDetails> .SetCurrentItem(null);

                throw new PXException(Messages.ErrorProcessingReceipts);
            }
        }
        private static void ClaimDetail(List <EPExpenseClaimDetails> details)
        {
            PXSetup <EPSetup> epsetup   = new PXSetup <EPSetup>(PXGraph.CreateInstance(typeof(ExpenseClaimDetailEntry)));
            bool enabledApprovalReceipt = PXAccess.FeatureInstalled <FeaturesSet.approvalWorkflow>() && epsetup.Current.ClaimDetailsAssignmentMapID != null;
            bool isError        = false;
            bool notAllApproved = false;
            Dictionary <string, EPExpenseClaim> result = new Dictionary <string, EPExpenseClaim>();

            IEnumerable <Receipts> List;

            if (epsetup.Current.AllowMixedTaxSettingInClaims == true)
            {
                List = details.Where(item => string.IsNullOrEmpty(item.RefNbr)).OrderBy(detail => detail.ClaimDetailID).GroupBy(
                    item => new
                {
                    item.EmployeeID,
                    item.BranchID,
                    item.CustomerID,
                    item.CustomerLocationID,
                },
                    (key, item) => new Receipts
                {
                    employee         = key.EmployeeID,
                    branch           = key.BranchID,
                    customer         = key.CustomerID,
                    customerLocation = key.CustomerLocationID,
                    details          = item
                }
                    );
            }
            else
            {
                List = details.Where(item => string.IsNullOrEmpty(item.RefNbr)).OrderBy(detail => detail.ClaimDetailID).GroupBy(
                    item => new
                {
                    item.EmployeeID,
                    item.BranchID,
                    item.CustomerID,
                    item.CustomerLocationID,
                    item.TaxZoneID,
                    item.TaxCalcMode
                },
                    (key, item) => new Receipts
                {
                    employee         = key.EmployeeID,
                    branch           = key.BranchID,
                    customer         = key.CustomerID,
                    customerLocation = key.CustomerLocationID,
                    details          = item
                }
                    );
            }

            foreach (Receipts item in List)
            {
                isError        = false;
                notAllApproved = false;
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    ExpenseClaimEntry expenseClaimEntry = CreateInstance <ExpenseClaimEntry>();
                    expenseClaimEntry.SelectTimeStamp();
                    EPExpenseClaim expenseClaim = (EPExpenseClaim)expenseClaimEntry.ExpenseClaim.Cache.CreateInstance();
                    expenseClaim.EmployeeID         = item.employee;
                    expenseClaim.BranchID           = item.branch;
                    expenseClaim.CustomerID         = item.customer;
                    expenseClaim.DocDesc            = EP.Messages.SubmittedReceipt;
                    expenseClaim                    = expenseClaimEntry.ExpenseClaim.Update(expenseClaim);
                    expenseClaim.CustomerLocationID = item.customerLocation;
                    expenseClaim.TaxCalcMode        = item.details.First().TaxCalcMode;
                    expenseClaim.TaxZoneID          = item.details.First().TaxZoneID;

                    foreach (EPExpenseClaimDetails detail in item.details)
                    {
                        PXProcessing <EPExpenseClaimDetails> .SetCurrentItem(detail);

                        if (detail.Approved ?? false)
                        {
                            try
                            {
                                if (detail.TipAmt != 0 && epsetup.Current.NonTaxableTipItem == null)
                                {
                                    PXProcessing <EPExpenseClaimDetails> .SetError(Messages.TipItemIsNotDefined);

                                    isError = true;
                                }
                                else
                                {
                                    EPClaimReceiptController.SubmitReceipt(expenseClaimEntry.ExpenseClaim.Cache,
                                                                           expenseClaimEntry.ExpenseClaimDetails.Cache, expenseClaimEntry.ExpenseClaim.Current, detail);

                                    PXProcessing <EPExpenseClaimDetails> .SetProcessed();
                                }


                                expenseClaimEntry.Save.Press();
                                if (!result.ContainsKey(expenseClaim.RefNbr))
                                {
                                    result.Add(expenseClaim.RefNbr, expenseClaim);
                                }
                                detail.RefNbr = expenseClaim.RefNbr;
                            }
                            catch (Exception ex)
                            {
                                PXProcessing <EPExpenseClaimDetails> .SetError(ex);

                                isError = true;
                            }
                        }
                        else
                        {
                            PXProcessing.SetError(enabledApprovalReceipt
                                                                ? Messages.ReceiptNotApproved
                                                                : Messages.ReceiptTakenOffHold);
                            notAllApproved = true;
                        }
                    }
                    if (!isError)
                    {
                        ts.Complete();
                    }
                }
            }



            if (!isError && !notAllApproved)
            {
                if (result.Count == 1)
                {
                    ExpenseClaimEntry expenseClaimEntry = CreateInstance <ExpenseClaimEntry>();
                    PXRedirectHelper.TryRedirect(expenseClaimEntry, result.First().Value, PXRedirectHelper.WindowMode.InlineWindow);
                }
            }
            else
            {
                PXProcessing <EPExpenseClaimDetails> .SetCurrentItem(null);

                throw new PXException(Messages.ErrorProcessingReceipts);
            }
        }